Skip to content
All library documents

A Short and Long Moving Average Crossover for Futures

Article Strategy library · Author: limin

Summary

This example demonstrates a dual moving average strategy on one-minute futures data. It calculates short and long simple moving averages using 30 and 60 periods, then compares their latest values with the prior bar. A crossover in one direction sets a target position of three contracts long; the opposite crossover sets a target of three contracts short. The target-position task handles the position adjustment through the trading API.

The code illustrates how to retrieve a futures price series, wait for updates, detect a new bar, compute averages, and translate crossovers into target positions. It is a basic implementation example rather than a tested trading recommendation. The source itself cautions that it is for demonstrating functionality and should be adapted before live use. It gives no backtest results, transaction cost assumptions, stop logic, or discussion of parameter selection, so its risk and performance cannot be assessed from the document.

Key ideas

  • The example compares 30-period and 60-period simple moving averages on one-minute futures bars.
  • It sets a short target position when the fast average crosses below the slow average.
  • It sets a long target position when the fast average crosses above the slow average.
  • The example uses a target-position task to manage the selected contract exposure.
  • No backtest, cost model, or stop-loss method is provided.

Tags

Full text
# doublema


# doublema









## Source (Apache-2.0)

```python
#!/usr/bin/env python
#  -*- coding: utf-8 -*-
__author__ = 'limin'

'''
双均线策略
注: 该示例策略仅用于功能示范, 实盘时请根据自己的策略/经验进行修改
'''
from tqsdk import TqApi, TqAuth, TargetPosTask
from tqsdk.tafunc import ma

SHORT = 30  # 短周期
LONG = 60  # 长周期
SYMBOL = "SHFE.bu2012"  # 合约代码

api = TqApi(auth=TqAuth("快期账户", "账户密码"))
print("策略开始运行")

data_length = LONG + 2  # k线数据长度
# "duration_seconds=60"为一分钟线, 日线的duration_seconds参数为: 24*60*60
klines = api.get_kline_serial(SYMBOL, duration_seconds=60, data_length=data_length)
target_pos = TargetPosTask(api, SYMBOL)

while True:
    api.wait_update()

    if api.is_changing(klines.iloc[-1], "datetime"):  # 产生新k线:重新计算SMA
        short_avg = ma(klines["close"], SHORT)  # 短周期
        long_avg = ma(klines["close"], LONG)  # 长周期

        # 均线下穿,做空
        if long_avg.iloc[-2] < short_avg.iloc[-2] and long_avg.iloc[-1] > short_avg.iloc[-1]:
            target_pos.set_target_volume(-3)
            print("均线下穿,做空")

        # 均线上穿,做多
        if short_avg.iloc[-2] < long_avg.iloc[-2] and short_avg.iloc[-1] > long_avg.iloc[-1]:
            target_pos.set_target_volume(3)
            print("均线上穿,做多")

```

Shown in full with attribution under the source's licence. Licence: Apache-2.0

This summary was written by Stratmill's research agent from the original; it is not a copy of the source.