Simple backtester to evaluate and analyse options strategies over historical price data.
- Python >= 3.6
- pipenv
Install pipenv
$> pip install pipenv
Create environment and download dependencies
$> make install
Activate environment
$> make env
Run Jupyter notebook
$> make notebook
Run tests
$> make test
We'll run a backtest of a stock portfolio holding $AAPL
and $GOOG
, and simultaneously buying 10% OTM calls and puts on $SPX
(long strangle).
We'll allocate 97% of our capital to stocks and the rest to options, and do a rebalance every month.
from backtester import Backtest, Type, Direction, Stock
from backtester.strategy import Strategy, StrategyLeg
from backtester.datahandler import HistoricalOptionsData, TiingoData
# Stocks data
stocks_data = TiingoData('stocks.csv')
stocks = [Stock(symbol='AAPL', percentage=0.5), Stock(symbol='GOOG', percentage=0.5)]
# Options data
options_data = HistoricalOptionsData('options.h5', key='/SPX')
schema = options_data.schema
# Long strangle
leg_1 = StrategyLeg('leg_1', schema, option_type=Type.PUT, direction=Direction.BUY)
leg_1.entry_filter = (schema.underlying == 'SPX') & (schema.dte >= 60) & (schema.underlying_last <=
1.1 * schema.strike)
leg_1.exit_filter = (schema.dte <= 30)
leg_2 = StrategyLeg('leg_2', schema, option_type=Type.CALL, direction=Direction.BUY)
leg_2.entry_filter = (schema.underlying == 'SPX') & (schema.dte >= 60) & (schema.underlying_last >=
0.9 * schema.strike)
leg_2.exit_filter = (schema.dte <= 30)
strategy = Strategy(schema)
strategy.add_legs([leg_1, leg_2])
allocation = {'stocks': .97, 'options': .03}
initial_capital = 1_000_000
bt = Backtest(allocation, initial_capital)
bt.stocks = stocks
bt.stocks_data = stocks_data
bt.options_data = options_data
bt.options_strategy = strategy
bt.run(rebalance_freq=1)
You can explore more usage examples in the Jupyter notebooks.
For complete novices in finance and economics, this post gives a comprehensive introduction.
- Option Volatility and Pricing 2nd Ed. - Natemberg, 2014
- Options, Futures, and Other Derivatives 10th Ed. - Hull 2017
- Trading Options Greeks: How Time, Volatility, and Other Pricing Factors Drive Profits 2nd Ed. - Passarelli 2012
- Trading Volatility - Bennet 2014
- Volatility Trading 2nd Ed. - Sinclair 2013
- Dynamic Hedging - Taleb 1997
- The Volatility Surface: A Practitioner's Guide - Gatheral 2006
- The Volatility Smile - Derman & Miller 2016
- Volatility: A New Return Driver?
- Easy Volatility Investing
- Everybody’s Doing It: Short Volatility Strategies and Shadow Financial Insurers
- Volatility-of-Volatility Risk
- The Distribution of Returns
- Safe Haven Investing Part I - Not all risk mitigation is created equal
- Safe Haven Investing Part II - Not all risk is created equal
- Safe Haven Investing Part III - Those wonderful tenbaggers
- Insurance makes wealth grow faster
- Ergodicity economics
- The Rate of Return on Everything, 1870–2015
- Volatility and the Alchemy of Risk