Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Trade using a simple strategy
- def trade(S1, S2, window1, window2):
- # If window length is 0, algorithm doesn't make sense, so exit
- if (window1 == 0) or (window2 == 0):
- return 0
- # Compute rolling mean and rolling standard deviation
- ratios = S1/S2
- ma1 = ratios.rolling(window=window1,
- center=False).mean()
- ma2 = ratios.rolling(window=window2,
- center=False).mean()
- std = ratios.rolling(window=window2,
- center=False).std()
- zscore = (ma1 - ma2)/std
- # Simulate trading
- # Start with no money and no positions
- money = 0
- countS1 = 0
- countS2 = 0
- for i in range(len(ratios)):
- # Sell short if the z-score is > 1
- if zscore[i] < -1:
- money += S1[i] - S2[i] * ratios[i]
- countS1 -= 1
- countS2 += ratios[i]
- #print('Selling Ratio %s %s %s %s'%(money, ratios[i], countS1,countS2))
- # Buy long if the z-score is < -1
- elif zscore[i] > 1:
- money -= S1[i] - S2[i] * ratios[i]
- countS1 += 1
- countS2 -= ratios[i]
- #print('Buying Ratio %s %s %s %s'%(money,ratios[i], countS1,countS2))
- # Clear positions if the z-score between -.5 and .5
- elif abs(zscore[i]) < 0.75:
- money += S1[i] * countS1 + S2[i] * countS2
- countS1 = 0
- countS2 = 0
- #print('Exit pos %s %s %s %s'%(money,ratios[i], countS1,countS2))
- return money
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement