Skip to content

Instantly share code, notes, and snippets.

@yoshyoshi
Created July 24, 2018 00:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save yoshyoshi/d88cf7bdce246d9f0144077734a43546 to your computer and use it in GitHub Desktop.
Save yoshyoshi/d88cf7bdce246d9f0144077734a43546 to your computer and use it in GitHub Desktop.
a multi-symbol back-tester based on position handler
import matplotlib.pyplot as plt
from datetime import datetime
import alpaca_trade_api as tradeapi
api = tradeapi.REST(key_id=<your key id>,secret_key=<your secret key>)
backtester = positionHandler(startingBalance=10000,liveTrading=False) # Using position handler from previous article
backtestSymbolList = ["SPY","AAPL","BBRY"]
positionSizing = 0.33
cashBalanceList = []
timeSteps = len(dateList) # It can be helpful to have a list of the dates associated with their respective bars
barIterator = 0
while barIterator < timeSteps:
for symbol in backtestSymbolList:
# Historical data input has to be adjusted for your own data pipeline
# Simple moving average cross strategy
price = data[symbol]["close"]
SMA20 = data[symbol]["SMA20"]
SMA50 = data[symbol]["SMA50"]
if SMA20 > SMA50:
openPosition = backtester.returnOpenPosition(symbol)
if openPosition = 0:
cashBalance = backtester.cashBalance
targetPositionSize = cashBalance / (price / positionSizing) # Calculates required position size
backtester.placeOrder(symbol,targetPositionSize,"buy","market","gtc") # Market order to open position
else:
openPosition = backtester.returnOpenPosition(symbol)
backtester.placeOrder(symbol,openPosition,"sell","market","gtc") # Market order to fully close position
cashBalance.append(backtester.cashBalance)
tradeHistory = backtester.tradeHistory
positionHistory = backtester.positionHistory
finalBalance = backtester.cashBalance
# Defines the plot for each trading symbol
f, ax = plt.subplots()
f.suptitle(symbol)
timeList = []
for date in dateList:
timeList.append(datetime.strptime(date,'%Y-%m-%dT%H:%M:%SZ'))
timeList = np.array(timeList)
# Plots market data and indicators
ax.plot(timeList,cashBalanceList,label=symbol,color="black")
# Add functions to analyse performance over time and calculate metrics
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment