Strategy Backtest is a python program built with pandas that backtests various strategies
Stats
Stats
Ticker AAPL
Start Time 2013-01-02 00:00:00
End Time 2022-05-20 00:00:00
Start Amount 5000
End Amount 83708.247
Average Hold Time 156 days 13:30:00
Average Losses -7242.993
Average Profits 12216.62
Biggest Loss -31825.015
Biggest Win 50857.595
Compound Annual Growth Rate (%) 36.766
Max Drawdown (%) -49.13
Average Drawdown (%) -11.827
Net Profit 78708.247
Profit Factor 2.811
Risk Reward 0.071
Sharpe Ratio 1.051
Volatility Annualized (% change) 0.454
Beta 0.209
Alpha 15.265
R-Squared 0.565
The frontend can only backtest the crossover strategy over a specified date for any stock. Upon first use the data loading may take some time.
The strategy backtest framework works by pulling data from the yahoo finance api (unofficial) or allowing the user to supply their own data. The user can create their own strategy or use one of the provided ones. A strategy is created by making indicators that manipulate the data. For example there is a crossover strategy that compares a fast SMA (20 day) and a slow SMA (100 day).
The data is then entered into pandas DataFrames and then a strategy can be made with a manipulation of the DataFrame data. After the strategy is created it the strategy can be backtested on market stock data. It can also be plotted and the orders that the strategy makes, and the strategy metrics can also be displayed.
pip install numpy
pip install pandas
pip install yfinance
pip install praw
pip install pytest
pip install strat-backtest
Clone the github repo to the folder where the backtest is going to be run. Once all the dependencies are met the program can be implemented correctly. For a quicker installation download the backtest folder and then follow usage instructions3
from strat_backtest.backtest import Backtest, download_data, load_data
from strat_backtest.backtest.custom_strats import MA_Cross_Strat, Ten_Percent_Strat
# Download data for tickers
# download_data('AAPL', 'MSFT', 'TSLA').AAPL.to_csv("./data/aapl.csv")
# Load data from a directory
data = load_data("./data")["aapl"].last("10Y")
# Initialize backtest and run strategy
backtest = Backtest(5000, "AAPL", MA_Cross_Strat, input_data=data, fast=20, lagging=100)
output = backtest.run()
backtest = Backtest(5000, "AAPL", MA_Cross_Strat, input_data=data, fast=20, lagging=100)
optimal_nums, net_worth = backtest.optimize(
init_state=[10, 60],
fast=[36, 42, 2],
lagging=[40, 210, 10],
opt_type="grid_search",
common_stock=True,
)
# Outputs the optimized numbers for the algorithm
print(optimal_nums, net_worth)
# Plotting
backtest.strat.plot_data(
((output[["net_worth", "SP500"]].last("10Y").pct_change() + 1).cumprod() * 100)
- 100,
title="Percent return of Crossover strategy against time",
ylabel="Percent Returns",
color="LIGHT",
)
# Graph will be stored in ./Graphs
# metrics for the backtest
backtest = Backtest(...)
# print output to stdout if output is marked True
stats = backtest.metrics(output=False)
# Download data for tickers
# Comes as a dictionary of dataframes of OHLCV data
data = download_data('AAPL', 'MSFT', 'TSLA')
# Access data for individual ticker
aapl = data.AAPL
# For Example:
# data.MSFT
# data.TSLA
# Store data in a csv
aapl.to_csv("./data/aapl.csv")
# Orders
# Get orders (have to convert to dataframe for easy access)
orders = backtest.strat.orders
orders.to_df().to_csv("orders.csv")
INI setup if using ini for information
SAMPLE CONFIG INI
[REDDIT]
API_KEY = <api key (app id)>
SECRET = <secret>
USER_AGENT = <user agent>
Python setup
rc = common_stock.RedditConfig('APP_ID', 'SECRET', 'USER_AGENT')
From root directory of project run
python -m pytest
- Add more strategies
- Adapt code to work with options
Make script to analyze other sources of data to get better insight into which stocks to backtestAdd more stats- Add more items so framework is more robust
- Rewrite and improve documentation
- Maybe: Add algotrading bot to program