Skip to content

Instantly share code, notes, and snippets.

@umitanuki
Last active February 9, 2022 07:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save umitanuki/b0c9615a59c3239f01ef969296805b80 to your computer and use it in GitHub Desktop.
Save umitanuki/b0c9615a59c3239f01ef969296805b80 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
@jimmydanol
Copy link

Where is the loader module coming from?? (import loader) Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment