vn.py量化社区
By Traders, For Traders.
Member
avatar
加入于:
帖子: 8
声望: 0
from datetime import datetime

from vnpy.app.cta_strategy.backtesting import BacktestingEngine
from vnpy.trader.constant import Interval
from vnpy.app.cta_strategy.base import BacktestingMode
import sys
sys.path.append(r"C:\Users\zzy\strategies")
from vnpy.app.cta_strategy.strategies.double_ma_strategy import DoubleMaStrategy as stg
import matplotlib.pyplot as plt
import copy
class BacktestingEngine(BacktestingEngine):
    def show_chart(self, df = None):
        """"""
        # Check DataFrame input exterior
        if df is None:
            df = self.daily_df

        # Check for init DataFrame
        if df is None:
            return

        plt.figure(figsize=(10, 16))

        balance_plot = plt.subplot(4, 1, 1)
        balance_plot.set_title("Balance")
        df["balance"].plot(legend=True)

        drawdown_plot = plt.subplot(4, 1, 2)
        drawdown_plot.set_title("Drawdown")
        drawdown_plot.fill_between(range(len(df)), df["drawdown"].values)

        pnl_plot = plt.subplot(4, 1, 3)
        pnl_plot.set_title("Daily Pnl")
        y=copy.deepcopy(df["net_pnl"])
        x=copy.deepcopy(df["net_pnl"])
        x[x<=0]=0
        y[y>0]=0
        x.plot(kind="bar", legend=False, grid=True, xticks=[],color='r')
        y.plot(kind="bar", legend=False, grid=True, xticks=[], color='g')


        distribution_plot = plt.subplot(4, 1, 4)
        distribution_plot.set_title("Daily Pnl Distribution")
        df["net_pnl"].hist(bins=50)

        plt.show()


engine = BacktestingEngine()
engine.clear_data()
engine.set_parameters(
    vt_symbol="M9999.DCE",
    interval=Interval.MINUTE,
    start=datetime(2017,2,28),
    rate=0.0001,
    slippage=1.0,
    size=10,
    pricetick=1.0,
    capital=100000,
    end=datetime(2020,2,28),
    mode=BacktestingMode.BAR,
    inverse=False
)
setting={'rsi_signal': 20, 'rsi_window': 14, 'fast_window': 5, 'slow_window': 20, 'fixed_size': 1}
#setting为策略的参数
engine.add_strategy(stg,setting)
engine.load_data()
engine.run_backtesting()
engine.calculate_result()
engine.calculate_statistics(output=True)
engine.show_chart()

大家有兴趣可以把参数优化给加上去,不过感觉要优化参数的话打开GUI界面比较方便。

Member
avatar
加入于:
帖子: 72
声望: 2

策略写在on_bar函数,bargenerator默认interval是minute,交易就是一分钟;跑回测参数设置只能是1m吗?如果选择1h,或者1d参数回测,是不是需要修改策略interval?

Member
avatar
加入于:
帖子: 1683
声望: 113

是的,如果基于一分钟线合成的话,K线合成时interval需要修改

© 2015-2019 上海韦纳软件科技有限公司
备案服务号:沪ICP备18006526号-3

沪公网安备 31011502017034号