本教程讓你快速瞭解 pybacktest's 的功能。爲此,咱們回測精典交易策略移動平均線MA交叉。python
軟件包在此下載 https://github.com/ematvey/pybacktestgit
pandas.DataFrame
,以時間戳爲索引,各列字段名稱爲 O
, H
, L
, C。實際上,目前只檢查字段O的值是否爲空。
從yahoo下載數據。github
O | H | L | C | V | AC | |
---|---|---|---|---|---|---|
Date | ||||||
2013-04-22 | 155.78 | 156.54 | 154.75 | 156.17 | 106501600 | 156.17 |
2013-04-23 | 156.95 | 157.93 | 156.17 | 157.78 | 165950600 | 157.78 |
2013-04-24 | 157.83 | 158.30 | 157.54 | 157.88 | 96724000 | 157.88 |
2013-04-25 | 158.34 | 159.27 | 158.10 | 158.52 | 130916000 | 158.52 |
2013-04-26 | 158.33 | 158.60 | 157.73 | 158.24 | 95904500 | 158.24 |
定義交易策略。要建立以 True和False 表示交易信號的 Series
,和以浮點數表示交易價格的 Series。
編程
夠簡單的吧?函數
> Short MA Date 2013-04-22 154.5438 2013-04-23 154.6634 2013-04-24 154.7856 2013-04-25 154.9156 2013-04-26 155.0374 > Long MA Date 2013-04-22 145.50725 2013-04-23 145.60910 2013-04-24 145.71455 2013-04-25 145.82970 2013-04-26 145.94430 > Buy/Cover signals Date 2013-04-22 False 2013-04-23 False 2013-04-24 False 2013-04-25 False 2013-04-26 False > Short/Sell signals Date 2013-04-22 False 2013-04-23 False 2013-04-24 False 2013-04-25 False 2013-04-26 False
開始回測吧。訪問類對象 Backtest
的第一個參數,是從字典式的對象中剝離出的交易信號、價格等。能夠是字典、pandas.DataFrame 或者其餘任何東西。ui
爲了簡化編程,把局部命名空間用函數 locals()傳遞過去。命名空間的內容,是至今你所建立的所有變量
。spa
Backtest
工做懶惰,只有在你訪問它的屬性時,它纔會進行運算。它所運算的屬性包括:> bt.signals Buy Cover Sell Short Date 2013-04-22 False False False False 2013-04-23 False False False False 2013-04-24 False False False False 2013-04-25 False False False False 2013-04-26 False False False False > bt.trades pos price vol Date 2009-06-23 1 90.16 2 2010-07-06 -1 103.13 -2 2010-10-22 1 119.14 2 2011-08-12 -1 119.19 -2 2012-01-31 1 132.29 2 > bt.positions Date 2009-06-23 1 2010-07-06 -1 2010-10-22 1 2011-08-12 -1 2012-01-31 1 > bt.equity Date 2009-06-23 58.66 2010-07-06 12.97 2010-10-22 -16.01 2011-08-12 0.05 2012-01-31 -13.10 > bt.trade_price Date 2013-04-22 156.95 2013-04-23 157.83 2013-04-24 158.34 2013-04-25 158.33 2013-04-26 NaN Name: O
================================================================= backtest: days: 6348 from: '1994-09-14 00:00:00' to: '2012-01-31 00:00:00' trades: 17 exposure: holding periods: max: 1476 days, 0:00:00 median: 354 days, 0:00:00 min: 7 days, 0:00:00 trades/month: 1.0625 performance: PF: 4.017 RF: 6.1555 averages: gain: 23.817 loss: -8.47 trade: 10.5224 payoff: 2.8119 profit: 178.88 winrate: 0.5882 risk/return profile: UPI: 1.0656 WCDD (monte-carlo 0.99 quantile): 52.09 maxdd: 74.67 sharpe: 0.4485 sortino: 1.6792 -----------------------------------------------------------------