返回列表 发布新帖

三均线策略

1603 1
发表于 2024-3-18 16:22:59 | 显示全部楼层 阅读模式
参考迅投示例里的双均线策略编写了一个三均线的策略,欢迎大家交流指正。

  1. # encoding:gbk

  2. import numpy as np

  3. '''
  4. 三均线策略:
  5. 长周期用来辅助,不参与短周期和中周期金叉、死叉判断
  6. 如:K线在EMA250上面, EMA12和50形成金叉,买入做多。如果K线在EMA250下面, EMA12和50形成死叉,卖出做空。
  7. '''


  8. class Custom(object):
  9.     pass


  10. custom = Custom()
  11. custom.short = 12
  12. custom.middle = 50
  13. custom.long = 250
  14. custom.account = ""


  15. def init(context):
  16.     context.account = custom.account
  17.     context.account_type = "STOCK"
  18.     stock_list = ["600000.SH", "000001.SZ"]
  19.     context.set_universe(stock_list)


  20. def handlebar(context):
  21.     # 使每次调用只执行一次
  22.     if not context.is_last_bar():
  23.         return
  24.     # 获取最新价格
  25.     # stock_list = context.get_universe()
  26.     # full_tick = context.get_full_tick(stock_list)
  27.     # for code in stock_list:
  28.     #     price = full_tick[code]['lastPrice']
  29.     close_dict = get_close_dict(context)
  30.     for stock, close_list in close_dict.items():
  31.         if cross_compare(close_list, custom.short, custom.middle) == 1 and ma_compare(close_list, 1, custom.long):
  32.             print(f"buy {stock}")
  33.         if cross_compare(close_list, custom.short, custom.middle) == 2 and not ma_compare(close_list, 1, custom.long):
  34.             print(f"sell {stock}")


  35. def get_close_dict(context):
  36.     df_dict = context.get_market_data_ex(['close'], stock_code=context.get_universe(), period='1d', count=custom.long + 1)
  37.     close_dict = {}
  38.     for stock, data in df_dict.items():
  39.         close_list = data.to_dict('list')['close']
  40.         close_dict[stock] = close_list
  41.     return close_dict


  42. def cross_compare(close_list, short, long):
  43.     pre_line1 = np.mean(close_list[-short - 1: -1])
  44.     pre_line2 = np.mean(close_list[-long - 1: -1])
  45.     current_line1 = np.mean(close_list[-short:])
  46.     current_line2 = np.mean(close_list[-long:])
  47.     # 如果快线穿过慢线(金叉),则买入委托;如果快线下穿慢线(死叉),则卖出委托
  48.     if pre_line1 < pre_line2 and current_line1 > current_line2:
  49.         return 1
  50.     elif pre_line1 > pre_line2 and current_line1 < current_line2:
  51.         return 2
  52.     return 0


  53. def ma_compare(close_list, short, long):
  54.     ma1_price = np.mean(close_list[-short:])
  55.     ma2_price = np.mean(close_list[-long:])
  56.     return ma1_price > ma2_price

复制代码


评论1

rzp
发表于 2024-3-28 09:21:55 | 显示全部楼层
前排学习

回复

您需要登录后才可以回帖 登录 | 立即注册

客服专线

400-080-8112

用思考的速度交易,用真诚的态度合作,我们是认真的!
  • 关注公众号
  • 添加微信客服
Copyright © 2001-2025 迅投QMT社区 版权所有 All Rights Reserved. 蜀ICP备19002686号-2
关灯 快速发帖
扫一扫添加微信客服
QQ客服返回顶部
快速回复 返回顶部 返回列表