vn.py量化社区
By Traders, For Traders.
Member
avatar
加入于:
帖子: 51
声望: 1

在 .vntrader 中新建了2个文件
demo_strategy_singleTimeframe.py 用于写策略
demo_backtesting_singleTimeframe.py 用于回测策略
我在demo_backtesting_singleTimeframe.py 做调试的时候,发现只能进到demo_strategy_singleTimeframe.py的 on_bar 函数中,整个执行过程中没有进到on_5min_bar 函数中。因此无交易记录,请问是什么原因?
在回测的时候, engine.load_data()执行完成后显示 历史数据加载完成,数据量:18720
所以说明数据是没问题的。

下面是代码

#demo_strategy_singleTimeframe.py

from typing import Any
from vnpy.trader.object import(
    BarData,
    TickData
    )
from vnpy.app.cta_strategy import(
    CtaTemplate,
    BarGenerator,   #k线合成器
    ArrayManager    #K线时间序列容器,将K线数据放到容器中去

)
from vnpy.trader.constant import Interval #注意,在这加载的interval
from typing import Callable

class DemoStrategy_SingleTimeFrame(CtaTemplate):


    author = "Smart Trader"

    #定义参数
    fast_window = 10
    slow_window = 20

    #定义变量
    fast_ma0 = 0.0
    fast_ma1 = 0.0
    slow_ma0 = 0.0
    slow_ma1 = 0.0


    parameters = [
        'fast_window', 
        'slow_window'
        ]

    variables = [
        'fast_ma0',
        'fast_ma1',
        'slow_ma0',
        'slow_ma1',
            ]

    def __init__(
        self,
        cta_engine: Any,
        strategy_name: str,
        vt_symbol: str,
        setting: dict,
        ):            

        super().__init__(cta_engine,strategy_name,vt_symbol,setting)
        self.bg = BarGenerator(self.on_bar,
                    window=5, 
                    on_window_bar=self.on_5min_bar, 
                    interval='1m')  
        self.am = ArrayManager()

    def on_init(self):
        """策略初始化"""
        #注册
        self.write_log('策略初始化')
        self.load_bar(10)

    def on_start(self):
        """启动"""
        self.write_log('策略启动')

    def on_stop(self):
        """停止"""
        self.write_log('策略停止')
    def on_tick(self,tick:TickData):
        """Tick更新"""
        self.bg.update_tick(tick)#bg会自动判断当前分钟是否已经走完,合成1分钟线

    def on_bar(self,bar:BarData):
        """k线更新"""
        self.bg.update_bar(bar)#将1分钟K线合成5分钟K线

    def on_5min_bar(self,bar:BarData):#执行5分钟的K线,本节课的重点,
        """ """
        am = self.am

        am.update_bar(bar)
        if not am.inited:
            return
        fast_ma = am.sma(self.fast_window, array= True)
        self.fast_ma0= fast_ma[-1]
        self.fast_ma1= fast_ma[-2]

        slow_ma = am.sma(self.slow_window, array= True)
        self.slow_ma0= slow_ma[-1]
        self.slow_ma1= slow_ma[-2]


        #判断均线定义
        cross_over = (self.fast_ma0>= self.slow_ma0 and 
                        self.fast_ma1< self.slow_ma1)
        cross_below = (self.fast_ma0<= self.slow_ma0 and 
                self.fast_ma1 > self.slow_ma1)

        if cross_over:
            price  = bar .close_price + 5

            if not self.pos:
                self.buy(price,1)
            elif self.pos < 0:
                self.cover(price,1)
                self.buy(price,1)
        elif cross_below:
            price  = bar .close_price - 5
            if not self.pos:
                self.short(price,1)
            elif self.pos > 0:
                self.sell(price,1)
                self.short(price,1)
        #更新图形界面
        self.put_event()

==============================================分割线===================================================

#demo_strategy_singleTimeframe.py

from vnpy.app.cta_strategy.backtesting import BacktestingEngine, OptimizationSetting
from demo_strategy_singleTimeframe import DemoStrategy_SingleTimeFrame
from datetime import datetime

if __name__ == "__main__":
    engine = BacktestingEngine()
    engine.set_parameters(
        vt_symbol="IF88.CFFEX",
        interval="1m",
        start=datetime(2019, 1, 1),
        end=datetime(2019, 4, 30),
        rate=0.3/10000,
        slippage=0.2,
        size=300,
        pricetick=0.2,
        capital=1_000_000,
    )

    engine.add_strategy(DemoStrategy_SingleTimeFrame, {      #注意下面赋值的写法,每个变量都要带引号
            'fast_window' : 10,
            'slow_window' : 20 })

    engine.load_data()
    engine.run_backtesting()
    df = engine.calculate_result()
    engine.calculate_statistics()
    engine.show_chart()
Member
avatar
加入于:
帖子: 51
声望: 1

自己回答一下
self.bg = BarGenerator(self.on_bar,
window=5,
on_window_bar=self.on_5min_bar,
interval='1m')
写错了
interval应该是Interval.MINUTE,不应该是'1m'

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