├── .gitignore ├── README.md ├── data └── spy_2000-2020.csv ├── requirements.txt ├── run_strategy.py └── strategies ├── BuyHold.py └── GoldenCross.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # crossover 2 | S&P 500 golden cross strategy 3 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pandas 2 | pandas_datareader 3 | backtrader 4 | -------------------------------------------------------------------------------- /run_strategy.py: -------------------------------------------------------------------------------- 1 | import os, sys, argparse 2 | import pandas as pd 3 | import backtrader as bt 4 | from backtrader import Cerebro 5 | from strategies.GoldenCross import GoldenCross 6 | from strategies.BuyHold import BuyHold 7 | 8 | cerebro = bt.Cerebro() 9 | 10 | prices = pd.read_csv('data/spy_2000-2020.csv', index_col='Date', parse_dates=True) 11 | 12 | # initialize the Cerebro engine 13 | cerebro = Cerebro() 14 | cerebro.broker.setcash(100000) 15 | 16 | # add OHLC data feed 17 | feed = bt.feeds.PandasData(dataname=prices) 18 | cerebro.adddata(feed) 19 | 20 | strategies = { 21 | "golden_cross": GoldenCross, 22 | "buy_hold": BuyHold 23 | } 24 | 25 | # parse command line arguments 26 | parser = argparse.ArgumentParser() 27 | parser.add_argument("strategy", help="Which strategy to run", type=str) 28 | args = parser.parse_args() 29 | 30 | if not args.strategy in strategies: 31 | print("Invalid strategy, must select one of {}".format(strategies.keys())) 32 | sys.exit() 33 | 34 | cerebro.addstrategy(strategy=strategies[args.strategy]) 35 | cerebro.run() 36 | cerebro.plot() -------------------------------------------------------------------------------- /strategies/BuyHold.py: -------------------------------------------------------------------------------- 1 | import backtrader as bt 2 | 3 | class BuyHold(bt.Strategy): 4 | def start(self): 5 | self.val_start = self.broker.get_cash() # keep the starting cash 6 | 7 | def nextstart(self): 8 | print("next start") 9 | # Buy all the available cash 10 | print(self.broker.get_cash()) 11 | size = int(self.broker.get_cash() / self.data) 12 | self.buy(size=size) 13 | 14 | def stop(self): 15 | # calculate the actual returns 16 | self.roi = (self.broker.get_value() / self.val_start) - 1.0 17 | print('ROI: {:.2f}%'.format(100.0 * self.roi)) -------------------------------------------------------------------------------- /strategies/GoldenCross.py: -------------------------------------------------------------------------------- 1 | import os, math 2 | import sys 3 | import pandas as pd 4 | import backtrader as bt 5 | 6 | class GoldenCross(bt.Strategy): 7 | params = (('fast', 50), 8 | ('slow', 200), 9 | ('order_pct', 0.95), 10 | ('ticker', 'SPY')) 11 | 12 | def __init__(self): 13 | self.fastma = bt.indicators.SimpleMovingAverage( 14 | self.data.close, 15 | period=self.p.fast, 16 | plotname='50 day' 17 | ) 18 | 19 | self.slowma = bt.indicators.SimpleMovingAverage( 20 | self.data.close, 21 | period=self.p.slow, 22 | plotname='200 day' 23 | ) 24 | 25 | self.crossover = bt.indicators.CrossOver( 26 | self.fastma, 27 | self.slowma 28 | ) 29 | 30 | def next(self): 31 | if self.position.size == 0: 32 | if self.crossover > 0: 33 | amount_to_invest = (self.p.order_pct * self.broker.cash) 34 | self.size = math.floor(amount_to_invest / self.data.close) 35 | 36 | print("Buy {} shares of {} at {}".format(self.size, self.p.ticker, self.data.close[0])) 37 | self.buy(size=self.size) 38 | 39 | if self.position.size > 0: 40 | if (self.crossover < 0): 41 | print("Sell {} shares of {} at {}".format(self.size, self.p.ticker, self.data.close[0])) 42 | self.close() --------------------------------------------------------------------------------