美文网首页
pybacktest教程

pybacktest教程

作者: dodorado | 来源:发表于2018-06-28 23:42 被阅读0次

pybacktest 教程

这个教程简要地展示了 pybacktest 的特性。因此,我们对经典的均线交易策略进行回测:

  • 当短期均线向上穿过长期均线时,做多
  • 当短期均线向下穿过长期均线时,做空
  • 开仓规则也是退出规则,所以交易策略必须是可逆的

pybacktest包可以从github下载:https://github.com/ematvey/pybacktest

from __future__ import print_function

import pybacktest  # obviously, you should install pybacktest before importing it
import pandas as pd

pybacktest 期望日线数据以 pandas.DataFrame 的形式存储,索引为 datetimestamps 时间戳类型,列名为 O, H, L, C。实际上,这个版本只检查 O,开盘价。

让我们从 yahoo 下载数据。
(yahoo在我们这里不管用,我改成tushare了)

# ohlc = pybacktest.load_from_yahoo('SPY')
import tushare as ts

data = ts.get_k_data('600240')
ohlc = data.set_index(pd.DatetimeIndex(data['date'])).rename(columns={'open': 'O', 'high': 'H', 'low': 'L', 'close': 'C', 'volume': 'V'}).drop('code', axis=1).drop('date', axis=1)
ohlc.tail()
date O C H L V
2018-06-19 6.41 6.60 6.66 5.81 198799.0
2018-06-20 7.25 7.23 7.26 6.88 359593.0
2018-06-21 7.00 6.75 7.09 6.72 216731.0
2018-06-22 6.75 7.06 7.24 6.60 210592.0
2018-06-25 7.15 7.07 7.15 6.85 139418.0

现在我们就来定义策略。所有要做的事情就是:创建两个信号 Series(买和卖),还有可选的交易价格 Series

够简单吧?

short_ma = 50
long_ma = 200

ms = ohlc.C.rolling(short_ma).mean()
ml = ohlc.C.rolling(long_ma).mean()
    
buy = cover = (ms > ml) & (ms.shift() < ml.shift())  # ma cross up
sell = short = (ms < ml) & (ms.shift() > ml.shift())  # ma cross down

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())

>Short MA
date
2018-06-19 7.6080
2018-06-20 7.5878
2018-06-21 7.5606
2018-06-22 7.5390
2018-06-25 7.5162
Name: C, dtype: float64

> Long MA
date
2018-06-19 8.72870
2018-06-20 8.71975
2018-06-21 8.70815
2018-06-22 8.69725
2018-06-25 8.68585
Name: C, dtype: float64

> Buy/Cover signals
date
2018-06-19 False
2018-06-20 False
2018-06-21 False
2018-06-22 False
2018-06-25 False
Name: C, dtype: bool

> Short/Sell signals
date
2018-06-19 False
2018-06-20 False
2018-06-21 False
2018-06-22 False
2018-06-25 False
Name: C, dtype: bool

现在运行回测。Backtest 会尝试着从传入第一个类字典参数中提取相关的信号、价格、日线数据。该参数可以是pandas.DataFrame,或其它类型。

此处为了举例简单,传入局部命名空间(通过调用 locals() 得到),其包含了到目前为止创建的所有变量。

bt = pybacktest.Backtest(locals(), 'ma_cross')

Backtest 惰性运行,意味着,它只在你调用其属性的时候才做相应计算。如下:

print(list(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())

['dataobj', 'default_price', 'eqplot', 'equity', 'name', 'ohlc', 'plot_equity', 'plot_trades', 'positions', 'prices', 'report', 'run_time', 'signals', 'sigplot', 'stats', 'summary', 'trade_price', 'trades', 'trdplot']

> bt.signals
Buy Cover Sell Short
date
2018-06-19 False False False False
2018-06-20 False False False False
2018-06-21 False False False False
2018-06-22 False False False False
2018-06-25 False False False False

> bt.trades
pos price vol
date
2016-09-12 1.0 11.045 1.0
2017-02-17 -1.0 10.679 -2.0
2017-11-03 1.0 9.270 2.0
2017-11-23 -1.0 8.970 -2.0

> bt.positions
date
2015-11-10 0.0
2016-09-09 1.0
2017-02-16 -1.0
2017-11-02 1.0
2017-11-22 -1.0
dtype: float64

> bt.equity
date
2016-09-12 0.000
2017-02-17 -0.366
2017-11-03 1.409
2017-11-23 -0.300
dtype: float64

> bt.trade_price
date
2018-06-19 6.41
2018-06-20 7.25
2018-06-21 7.00
2018-06-22 6.75
2018-06-25 7.15
Name: O, dtype: float64

一些常用的绩效统计可以通过调用 Backtestsummary 方法获得。

bt.summary()

输出如下:

----------------------------------------------
|  Backtest(ma_cross, 2018-25-06 17:49 CST)  |
----------------------------------------------
    
backtest:
      days: 279
      from: '2017-02-17 00:00:00'
      to: '2017-11-23 00:00:00'
      trades: 3
performance:
PF: 2.1156
      RF: 2.4767
      averages:
      gain: 1.409
        loss: -0.333
        trade: 0.2477
      payoff: 4.2312
      profit: 0.743
      winrate: 0.3333
risk/return profile:
MPI: 0.429
      UPI: 1.4299
      WCDD (monte-carlo 0.99 quantile): 0.666
      maxdd: 0.3
      sharpe: 0.4736
      sortino: 0.9026
    
    ----------------------------------------------

现在让我们看看资产净值曲线。

%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['figure.figsize'] = (15.0, 8.0)

bt.plot_equity()
收益曲线

但是你想看到的是:回测期间到底发生了什么?好吧,Backtest 可以绘制交易。为了节约空间,图例缺省是不显示的。

matplotlib.rcParams['figure.figsize'] = (15.0, 8.0)
bt.plot_trades()
ohlc.C.rolling(short_ma).mean().plot(c='green')
ohlc.C.rolling(long_ma).mean().plot(c='blue')
plt.legend(loc='upper right')
pass
加入了买卖点

看到啥了没?我看不太清楚。这就是为什么有一个特殊属性 trdplot,用来设置需要绘制图形的时间区间(使用标准的pandas索引机制)。还可以通过设置eqplot属性来调整资产净值曲线。

bt.trdplot['2017':'2017']
ohlc.C['2017':'2017'].rolling(short_ma).mean().plot(c='green')
ohlc.C['2017':'2017'].rolling(long_ma).mean().plot(c='blue')
pass
只显示某时间段

就是这些了。

相关文章

网友评论

      本文标题:pybacktest教程

      本文链接:https://www.haomeiwen.com/subject/xozgyftx.html