Skip to content

Instantly share code, notes, and snippets.

@caub
Last active August 29, 2015 14:00
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 caub/11298650 to your computer and use it in GitHub Desktop.
Save caub/11298650 to your computer and use it in GitHub Desktop.
from scipy import *
M = 22 #ma for rsi
N = 14 #rsi loopback
thresh = [20,80] #rsi thresholds
cost = 0.0001 # cost per trade (spread)
price = 1.3 + 0.1*randn(100) + sin(linspace(0,10,100))
ma = ema(price, M)
ri = rsindex(price-ma, N)
# Position signal
s = zeros(size(price))
# Crossing the lower threshold
indx = ri < thresh[1]
indx = concatenate(([false], indx[:-1] and ~indx[1:]))
s[indx] = 1
# Crossing the upper threshold
indx = ri > thresh[2]
indx = concatenate(([false], indx[:-1] and ~indx[1:]))
s[indx] = -1
# Fill in zero values with prior position
for i in range(len(s)):
if s[i] == 0:
s[i] = s[i-1]
# PNL Calculation
trades = concatenate(([0,0], diff(s[:-1])) ) #shift trading by 1 period
cash = cumsum(-trades*price-abs(trades)*cost/2);
pandl = concatenate(([0], s[:-1]))*price + cash;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment