Skip to content

Instantly share code, notes, and snippets.

@milktrader
Created April 19, 2014 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milktrader/11094671 to your computer and use it in GitHub Desktop.
Save milktrader/11094671 to your computer and use it in GitHub Desktop.
A backtest of the golden cross
# this is the data set that will be used
# note: Cl is simply OHLC["Close"]
julia> OHLC
16103x6 TimeArray{Float64,2} 1950-01-03 to 2013-12-31
Open High Low Close Volume Adj Close
1950-01-03 | 16.66 16.66 16.66 16.66 1.26e6 16.66
1950-01-04 | 16.85 16.85 16.85 16.85 1.89e6 16.85
1950-01-05 | 16.93 16.93 16.93 16.93 2.55e6 16.93
1950-01-06 | 16.98 16.98 16.98 16.98 2.01e6 16.98
2013-12-26 | 1834.96 1842.84 1834.96 1842.02 1.98227e9 1842.02
2013-12-27 | 1842.97 1844.89 1839.81 1841.4 2.05292e9 1841.4
2013-12-30 | 1841.47 1842.47 1838.77 1841.07 0.0 1841.07
2013-12-31 | 1842.61 1849.44 1842.41 1848.36 2.31284e9 1848.36
# Generating a blotter in three lines of code
julia> signal = (sma(Cl,50) .> sma(Cl,200));
julia> spx = FinancialTimeSeries(OHLC, "SPX");
julia> goldencross = Blotter(signal, spx)
65x2 Blotter 1950-10-19T23:59:59 UTC to 2012-02-01T23:59:59 UTC
Qty Fill
1950-10-19T23:59:59 UTC | 100 20.02
1953-05-12T23:59:59 UTC | -100 24.74
1953-12-22T23:59:59 UTC | 100 24.76
1956-10-29T23:59:59 UTC | -100 46.4
2010-07-06T23:59:59 UTC | -100 1028.09
2010-10-25T23:59:59 UTC | 100 1184.74
2011-08-15T23:59:59 UTC | -100 1178.86
2012-02-01T23:59:59 UTC | 100 1312.45
# trade statistics are a breeze ....
julia> trades = tradearray(goldencross, spx);
julia> pnls = float([(t.close-t.open) for t in trades]).*100;
julia> pos = pnls[pnls.>0];
julia> neg = pnls[pnls.<0];
julia> profitfactor = sum(pos)/abs(sum(neg))
27.427328391878795
@milktrader
Copy link
Author

Better to generalize pnls

float([(t.close-t.open)*t.quantity for t in trades])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment