Skip to content

Instantly share code, notes, and snippets.

@shashankvemuri
Created August 3, 2020 01:17
Show Gist options
  • Save shashankvemuri/d311da75a9d1675327c9e9250202ed58 to your computer and use it in GitHub Desktop.
Save shashankvemuri/d311da75a9d1675327c9e9250202ed58 to your computer and use it in GitHub Desktop.
Backtest
for signal in signals:
if signal.lower() == 'moving average':
print ('-'*60)
print ('Simple Moving Average: ')
# Let's calulate Simple Moving Average(SMA)
short_sma= 20
long_sma = 50
SMAs=[short_sma, long_sma]
for i in SMAs:
df["SMA_"+str(i)]= df.iloc[:,4].rolling(window=i).mean()
position=0 # 1 means we have already entered poistion, 0 means not already entered
counter=0
percentChange=[] # empty list to collect %changes
for i in df.index:
SMA_short=df['SMA_20']
SMA_long =df['SMA_50']
close=df['Adj Close'][i]
if(SMA_short[i] > SMA_long[i]):
if(position==0):
buyP=close #buy price
position=1 # turn position
elif(SMA_short[i] < SMA_long[i]):
if(position==1): # have a poistion in down trend
position=0 # selling position
sellP=close # sell price
perc=(sellP/buyP-1)*100
percentChange.append(perc)
if(counter==df["Adj Close"].count()-1 and position==1):
position=0
sellP=close
perc=(sellP/buyP-1)*100
percentChange.append(perc)
counter+=1
gains=0
numGains=0
losses=0
numLosses=0
totReturn=1
for i in percentChange:
if(i>0):
gains+=i
numGains+=1
else:
losses+=i
numLosses+=1
totReturn = totReturn*((i/100)+1)
totReturn=round((totReturn-1)*100,2)
print("These statistics are from "+str(start)+" up till now with "+str(numGains+numLosses)+" trades:")
print("SMAs used: "+str(SMAs))
print("Total return over "+str(numGains+numLosses)+ " trades: "+ str(totReturn)+"%")
if (numGains>0):
avgGain=gains/numGains
maxReturn= str(max(percentChange))
else:
avgGain=0
maxReturn=np.nan
if(numLosses>0):
avgLoss=losses/numLosses
maxLoss=str(min(percentChange))
ratioRR=str(-avgGain/avgLoss) # risk-reward ratio
else:
avgLoss=0
maxLoss=np.nan
ratioRR='inf'
df['PC'] = df['Close'].pct_change()
hold = round(df['PC'].sum() * 100, 2)
print ("Total return for a B&H strategy: " + str(hold)+'%')
print("Average Gain: "+ str(round(avgGain, 2)))
print("Average Loss: "+ str(round(avgLoss, 2)))
print("Max Return: "+ str(maxReturn))
print("Max Loss: "+ str(maxLoss))
print("Gain/loss ratio: "+ str(ratioRR))
if(numGains>0 or numLosses>0):
batAvg=numGains/(numGains+numLosses)
else:
batAvg=0
print("Success Rate: "+ str(batAvg))
change.append(totReturn)
trades = numGains+numLosses
num_of_trades.append(trades)
last_sell.append(sellP)
last_buy.append(buyP)
average_gain.append(avgGain)
average_loss.append(avgLoss)
max_return.append(float(maxReturn))
max_loss.append(float(maxLoss))
gain_loss.append(float(ratioRR))
success_rate.append(batAvg)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment