| 参考迅投示例里的双均线策略编写了一个三均线的策略,欢迎大家交流指正。 
 
 复制代码# encoding:gbk
import numpy as np
'''
三均线策略:
长周期用来辅助,不参与短周期和中周期金叉、死叉判断
如:K线在EMA250上面, EMA12和50形成金叉,买入做多。如果K线在EMA250下面, EMA12和50形成死叉,卖出做空。
'''
class Custom(object):
    pass
custom = Custom()
custom.short = 12
custom.middle = 50
custom.long = 250
custom.account = ""
def init(context):
    context.account = custom.account
    context.account_type = "STOCK"
    stock_list = ["600000.SH", "000001.SZ"]
    context.set_universe(stock_list)
def handlebar(context):
    # 使每次调用只执行一次
    if not context.is_last_bar():
        return
    # 获取最新价格
    # stock_list = context.get_universe()
    # full_tick = context.get_full_tick(stock_list)
    # for code in stock_list:
    #     price = full_tick[code]['lastPrice']
    close_dict = get_close_dict(context)
    for stock, close_list in close_dict.items():
        if cross_compare(close_list, custom.short, custom.middle) == 1 and ma_compare(close_list, 1, custom.long):
            print(f"buy {stock}")
        if cross_compare(close_list, custom.short, custom.middle) == 2 and not ma_compare(close_list, 1, custom.long):
            print(f"sell {stock}")
def get_close_dict(context):
    df_dict = context.get_market_data_ex(['close'], stock_code=context.get_universe(), period='1d', count=custom.long + 1)
    close_dict = {}
    for stock, data in df_dict.items():
        close_list = data.to_dict('list')['close']
        close_dict[stock] = close_list
    return close_dict
def cross_compare(close_list, short, long):
    pre_line1 = np.mean(close_list[-short - 1: -1])
    pre_line2 = np.mean(close_list[-long - 1: -1])
    current_line1 = np.mean(close_list[-short:])
    current_line2 = np.mean(close_list[-long:])
    # 如果快线穿过慢线(金叉),则买入委托;如果快线下穿慢线(死叉),则卖出委托
    if pre_line1 < pre_line2 and current_line1 > current_line2:
        return 1
    elif pre_line1 > pre_line2 and current_line1 < current_line2:
        return 2
    return 0
def ma_compare(close_list, short, long):
    ma1_price = np.mean(close_list[-short:])
    ma2_price = np.mean(close_list[-long:])
    return ma1_price > ma2_price
 
 |