pybacktest 的疑點python
第(一)節「教程」原文,是用 ipython notebook 寫成,程序代碼是一些片斷組成。函數
爲了閱讀方便,合併在一塊兒。ui
本文轉載於:http://blog.csdn.net/lawme/article/details/51773744spa
- import pybacktest
- import pandas as pd
-
- ohlc = pybacktest.load_from_yahoo('SPY')
- ohlc.tail()
-
- short_ma = 50
- long_ma = 200
-
- ms = pandas.rolling_mean(ohlc.C, short_ma)
- ml = pandas.rolling_mean(ohlc.C, long_ma)
-
- buy = cover = (ms > ml) & (ms.shift() < ml.shift())
- sell = short = (ms < ml) & (ms.shift() > ml.shift())
-
- print '> Short MA\n%s\n' % ms.tail()
- print '> Long MA\n%s\n' % ml.tail()
- print '> Buy/Cover signals\n%s\n' % buy.tail()
- print '> Short/Sell signals\n%s\n' % sell.tail()
-
- bt = pybacktest.Backtest(locals(), 'ma_cross')
-
- print filter(lambda x: not x.startswith('_'), dir(bt))
- print '\n> bt.signals\n%s' % bt.signals.tail()
- print '\n> bt.trades\n%s' % bt.trades.tail()
- print '\n> bt.positions\n%s' % bt.positions.tail()
- print '\n> bt.equity\n%s' % bt.equity.tail()
- print '\n> bt.trade_price\n%s' % bt.trade_price.tail()
-
- bt.summary()
-
- figsize(10, 5)
- bt.plot_equity()
-
- bt.plot_trades()
- pandas.rolling_mean(ohlc.C, short_ma).plot(c='green')
- pandas.rolling_mean(ohlc.C, long_ma).plot(c='blue')
- legend(loc='upper left')
-
- bt.trdplot['2004':'2007']
- pandas.rolling_mean(ohlc.C['2004':'2007'], short_ma).plot(c='green')
- pandas.rolling_mean(ohlc.C['2004':'2007'], long_ma).plot(c='blue')
從源碼和教程來看,pybacktest 用法的確簡單。.net
但教程中有幾句,沒有看懂。例如如下2句:orm
- figsize(10, 5)
- legend(loc='upper left')
不知道這兩個函數出自何處,且有時能經過「編譯」,有時卻不行。blog
緣由後來找到了。由於代碼是在ipython notebook中,教程
如有「魔術命令」%pylab inline 這兩個函數能夠直接調用。ip
該例程雖未顯式使用%pylab inline,但可能notebook對它有默認設置。內存
更有趣的是,數據源只能直接取自yahoo,如:
- ohlc = pybacktest.load_from_yahoo('SPY')
若是把ohlc存成csv文件,而後再讀入內存,並進行格式規整,如:
- ohlc.to_csv('SPY.csv')
- ohlc = pd.read_csv('SPY.csv')
- ohlc.index = ohlc['Date']
- del ohlc['Date']
這時,雖然數據格式徹底一致,但程序會出錯,運行失敗。
問題的緣由多是,yahoo直接傳回的DataFrame,包含屬性tz,即time zone,
pybacktest的運算邏輯,須要處理tz這個屬性。可是,從csv文件讀出的DataFrame
沒有tz這個屬性,所以形成程序異常中斷。
還有,程序運行得出的回測結果,是什麼含意,沒看懂。
Backtest('ma_cross', 2013-28-04 23:14:15 MSK) performance summary
=================================================================
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