Advertisement
Guest User

Untitled

a guest
Jul 17th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. # Trade using a simple strategy
  2. def trade(S1, S2, window1, window2):
  3.  
  4. # If window length is 0, algorithm doesn't make sense, so exit
  5. if (window1 == 0) or (window2 == 0):
  6. return 0
  7.  
  8. # Compute rolling mean and rolling standard deviation
  9. ratios = S1/S2
  10. ma1 = ratios.rolling(window=window1,
  11. center=False).mean()
  12. ma2 = ratios.rolling(window=window2,
  13. center=False).mean()
  14. std = ratios.rolling(window=window2,
  15. center=False).std()
  16. zscore = (ma1 - ma2)/std
  17.  
  18. # Simulate trading
  19. # Start with no money and no positions
  20. money = 0
  21. countS1 = 0
  22. countS2 = 0
  23. for i in range(len(ratios)):
  24. # Sell short if the z-score is > 1
  25. if zscore[i] < -1:
  26. money += S1[i] - S2[i] * ratios[i]
  27. countS1 -= 1
  28. countS2 += ratios[i]
  29. #print('Selling Ratio %s %s %s %s'%(money, ratios[i], countS1,countS2))
  30. # Buy long if the z-score is < -1
  31. elif zscore[i] > 1:
  32. money -= S1[i] - S2[i] * ratios[i]
  33. countS1 += 1
  34. countS2 -= ratios[i]
  35. #print('Buying Ratio %s %s %s %s'%(money,ratios[i], countS1,countS2))
  36. # Clear positions if the z-score between -.5 and .5
  37. elif abs(zscore[i]) < 0.75:
  38. money += S1[i] * countS1 + S2[i] * countS2
  39. countS1 = 0
  40. countS2 = 0
  41. #print('Exit pos %s %s %s %s'%(money,ratios[i], countS1,countS2))
  42.  
  43.  
  44. return money
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement