当前位置: 首页 > 工具软件 > VN.PY > 使用案例 >

量化交易之vn.py篇 - cta_strategy - DemoStrategy(一个稳定亏损的双均线策略...)

柳坚白
2023-12-01
from vnpy.app.cta_strategy import (
    CtaTemplate,
    BarGenerator,
    ArrayManager
)

from typing import Any

from vnpy.trader.object import (
    BarData,
    TickData,
)

class DemoStrategy(CtaTemplate):


    author = "Post-Truth"


    # 定义参数
    fast_window = 10
    slow_window = 20

    # 定义变量
    fast_ma_1 = 0
    fast_ma_2 = 0
    slow_ma_1 = 0
    slow_ma_2 = 0
    

    parameters = [
        "fast_window",
        "slow_window"
    ]

    variables = [
        "fast_ma_1",
        "fast_ma_2",
        "slow_ma_1",
        "slow_ma_2"
    ]

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

        self.bar_generator = BarGenerator(self.on_bar)
        self.array_manager = ArrayManager(10)
    

    def on_init(self):
        self.write_log("策略 DemoStrategy 初始化")
        
        self.load_bar(10)


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

    def on_stop(self):
        self.write_log("策略 DemoStrategy 停止")

    
    def on_bar(self, bar: BarData):
        array_manager = self.array_manager

        array_manager.update_bar(bar=bar)
        if array_manager.inited:
            return


        fast_ma = array_manager.sma(self.fast_window, array=True)
        self.fast_ma_1 = fast_ma[-1]
        self.fast_ma_2 = fast_ma[-2]


        slow_ma = array_manager.sma(self.fast_window, array=True)
        self.slow_ma_1 = slow_ma[-1]
        self.slow_ma_2 = slow_ma[-2]

        cross_up = (self.fast_ma_1 > self.slow_ma_1) and (self.fast_ma_2 < self.slow_ma_2)
        cross_down = (self.fast_ma_1 < self.slow_ma_1) and (self.fast_ma_2 > self.slow_ma_2)
        

        if cross_up:

            price = bar.close_price + 5

            if not self.pos:
                self.buy(price=price, volume=1)
            elif self.pos < 0:
                self.cover(price=price, volume=1)  # 先平空
                self.buy(price=price, volume=1)
        
        elif cross_down:

            price = bar.close_price - 5

            if not self.pos:
                self.short(price=price, volume=1)
            elif self.pos > 0:
                self.sell(price=price, volume=1)
                self.short(price=price, volume=1)
        

        # 更新 图形 界面
        self.put_event()


    def on_tick(self, tick: TickData):
        self.bar_generator.update_tick(tick)

 

 类似资料: