├── 01_ma_crossover.py └── data └── price_aapl.pkl /01_ma_crossover.py: -------------------------------------------------------------------------------- 1 | # QUANT SCIENCE UNIVERSITY 2 | # Goal: Get you started making progress with algorithmic trading 3 | # Pro-Tip: Visualize the Moving Average Crossover Strategy (At the End) 4 | # **** 5 | 6 | # Libraries 7 | import vectorbt as vbt 8 | import pandas as pd 9 | import numpy as np 10 | 11 | # Read data 12 | price_aapl = pd.read_pickle("data/price_aapl.pkl") 13 | price_aapl 14 | 15 | # Profit Level: Buy and Hold Strategy 16 | pf_buy_hold = vbt.Portfolio.from_holding( 17 | close=price_aapl, 18 | init_cash=10_000 19 | ) 20 | pf_buy_hold.total_profit() 21 | 22 | 23 | # 1.0 Simple Moving Average Crossover Strategy 5-20 Day (AAPL) 24 | 25 | # 1. Define the strategy 26 | fast_ma = vbt.MA.run(price_aapl, window=5) 27 | slow_ma = vbt.MA.run(price_aapl, window=20) 28 | 29 | entries = fast_ma.ma_crossed_above(slow_ma) 30 | exits = fast_ma.ma_crossed_below(slow_ma) 31 | 32 | # 2. Run the strategy 33 | pf_ma_strat = vbt.Portfolio.from_signals( 34 | close = price_aapl, 35 | entries=entries, 36 | exits=exits, 37 | init_cash=10_000, 38 | fees=0.001, 39 | ) 40 | 41 | pf_ma_strat.total_profit() 42 | 43 | pf_ma_strat.stats() 44 | 45 | pf_ma_strat.plot().show() 46 | 47 | # 2.0 Backtesting 100 windows for the Moving Average Crossover Strategy (AAPL) 48 | 49 | windows = np.arange(2, 101) 50 | fast_ma, slow_ma = vbt.MA.run_combs( 51 | close = price_aapl, 52 | window=windows, 53 | r=2, 54 | short_names=['fast', 'slow'] 55 | ) 56 | entries = fast_ma.ma_crossed_above(slow_ma) 57 | exits = fast_ma.ma_crossed_below(slow_ma) 58 | 59 | pf_100_ma_strats = vbt.Portfolio.from_signals( 60 | close = price_aapl, 61 | entries = entries, 62 | exits = exits, 63 | size=np.inf, 64 | fees=0.001, 65 | freq='1D', 66 | init_cash=10_000 67 | ) 68 | 69 | pf_100_ma_strats.total_profit().max() 70 | pf_100_ma_strats.total_profit().idxmax() 71 | 72 | best_index = pf_100_ma_strats.total_profit().idxmax() 73 | 74 | stats = pf_100_ma_strats[best_index].stats() 75 | stats 76 | 77 | pf_100_ma_strats[best_index].plot().show() 78 | 79 | # Conclusions ---- 80 | # You can do this! 81 | # There's a lot more to learn: 82 | # - More Trading Strategies 83 | # - Risk Management 84 | # - Portfolio Optimization 85 | # - Machine Learning 86 | # - Advanced Backtesting 87 | # - Live Trading & Execution 88 | -------------------------------------------------------------------------------- /data/price_aapl.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/quant-science/vectorbt_backtesting/04a42bc3d75212acc1a0f9fba02b5d3035e89356/data/price_aapl.pkl --------------------------------------------------------------------------------