用vnpy写一个双均线交易策略
时间: 2024-05-10 17:15:28 浏览: 170
双均线法定投策略在股票市场的实现_python代码
好的,下面是一个使用vnpy写的双均线交易策略的示例代码:
```python
from vnpy.app.cta_strategy import (
CtaTemplate,
TickData,
BarData,
TradeData,
OrderData,
BarGenerator,
ArrayManager
)
class DoubleMaStrategy(CtaTemplate):
""""""
author = "vnpy"
# 策略参数
fast_window = 10
slow_window = 20
fixed_size = 1
# 策略变量
pos = 0
fast_ma = 0.0
slow_ma = 0.0
ma_trend = 0
# 参数列表,保存了参数的名称
parameters = ["fast_window", "slow_window", "fixed_size"]
# 变量列表,保存了变量的名称
variables = ["pos", "fast_ma", "slow_ma", "ma_trend"]
def __init__(self, cta_engine, strategy_name, vt_symbol, setting):
""""""
super().__init__(cta_engine, strategy_name, vt_symbol, setting)
self.bg = BarGenerator(self.on_bar)
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):
""""""
self.bg.update_tick(tick)
def on_bar(self, bar: BarData):
""""""
self.cancel_all()
am = self.am
am.update_bar(bar)
if not am.inited:
return
# 计算快慢均线
self.fast_ma = am.sma(self.fast_window)
self.slow_ma = am.sma(self.slow_window)
# 判断交叉
if self.fast_ma > self.slow_ma and self.ma_trend <= 0:
self.buy(bar.close_price+5, self.fixed_size)
self.ma_trend = 1
elif self.fast_ma < self.slow_ma and self.ma_trend >= 0:
self.sell(bar.close_price-5, self.fixed_size)
self.ma_trend = -1
self.put_event()
def on_trade(self, trade: TradeData):
""""""
self.put_event()
def on_order(self, order: OrderData):
""""""
self.put_event()
def on_stop_order(self, stop_order: StopOrder):
""""""
self.put_event()
```
以上代码实现了一个简单的双均线交易策略,当快均线(10日均线)上穿慢均线(20日均线)时,做多开仓;当快均线下穿慢均线时,平掉全部仓位。
阅读全文