Skip to content

Instantly share code, notes, and snippets.

@markcheno
Forked from umitanuki/multisymbol.py
Created April 3, 2019 13:16
Show Gist options
  • Save markcheno/af6adecc2f12f58a73abf0b907a3ea45 to your computer and use it in GitHub Desktop.
Save markcheno/af6adecc2f12f58a73abf0b907a3ea45 to your computer and use it in GitHub Desktop.
import matplotlib.pyplot as plt
from datetime import datetime
import alpaca_trade_api as tradeapi
import numpy as np
from positionhandling import positionHandler
import loader
api = tradeapi.REST()
# Using position handler from previous article
backtester = positionHandler(startingBalance=10000, liveTrading=False)
backtestSymbolList = ["SPY", "AAPL", "BBRY"]
positionSizing = 0.33
cashBalanceList = []
dateList = loader.getDateList()
# It can be helpful to have a list of the dates associated with their
# respective bars
timeSteps = len(dateList)
barIterator = 0
while barIterator < timeSteps:
data = loader.get_data(barIterator)
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
# Calculates required position size
targetPositionSize = int(cashBalance / (price / positionSizing))
backtester.placeOrder(
symbol,
targetPositionSize,
"buy",
"market",
"gtc") # Market order to open position
else:
openPosition = backtester.returnOpenPosition(symbol)
# Market order to fully close position
backtester.placeOrder(
symbol, openPosition, "sell", "market", "gtc")
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