| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222 |
- # 导入函数库
- from jqdata import *
- from jqdata import finance
- import pandas as pd
- import numpy as np
- from datetime import date, datetime, timedelta
- import re
- # 多均线穿越突破策略 v001
- # 基于K线实体穿越多条均线的交易策略
- # 设置以便完整打印 DataFrame
- pd.set_option('display.max_rows', None)
- pd.set_option('display.max_columns', None)
- pd.set_option('display.width', None)
- pd.set_option('display.max_colwidth', 20)
- ## 初始化函数,设定基准等等
- def initialize(context):
- # 设定沪深300作为基准
- set_benchmark('000300.XSHG')
- # 开启动态复权模式(真实价格)
- set_option('use_real_price', True)
- # 输出内容到日志
- log.info('多均线穿越突破策略初始化开始')
- ### 期货相关设定 ###
- # 设定账户为金融账户
- set_subportfolios([SubPortfolioConfig(cash=context.portfolio.starting_cash, type='index_futures')])
- # 期货类每笔交易时的手续费是: 买入时万分之0.23,卖出时万分之0.23,平今仓为万分之23
- set_order_cost(OrderCost(open_commission=0.000023, close_commission=0.000023, close_today_commission=0.0023), type='index_futures')
-
- # 设置期货交易的滑点
- set_slippage(StepRelatedSlippage(2))
-
- # 初始化全局变量
- g.usage_percentage = 0.8 # 最大资金使用比例
- g.min_cross_mas = 3 # 最少穿越均线数量
- g.max_margin_per_position = 20000 # 单个标的最大持仓保证金(元)
- g.price_deviation_min = 0.005 # 价格偏离临界线最小比例(0.5%)
- g.price_deviation_max = 0.01 # 价格偏离临界线最大比例(1%)
-
- # 均线交叉数量检查相关参数
- g.max_ma_crosses = 4 # 最大允许的均线交叉数量
- g.ma_cross_check_days = 10 # 检查均线交叉的天数
-
- # 定义默认的保证金比例
- g.margin_rates = {
- 'long': {'A': 0.07, 'AG': 0.04, 'AL': 0.05, 'AO': 0.05, 'AP': 0.08, 'AU': 0.04, 'B': 0.05,
- 'BC': 0.13, 'BR': 0.07, 'BU': 0.04, 'C': 0.07, 'CF': 0.05, 'CJ': 0.07, 'CS': 0.07,
- 'CU': 0.05, 'CY': 0.05, 'EB': 0.12, 'EC': 0.12, 'EG': 0.05, 'FG': 0.05, 'FU': 0.08,
- 'HC': 0.04, 'I': 0.1, 'J': 0.22, 'JD': 0.08, 'JM': 0.22,
- 'L': 0.07, 'LC': 0.05, 'LH': 0.1, 'LR': 0.05, 'LU': 0.15, 'M': 0.07, 'MA': 0.05, 'NI': 0.05, 'NR': 0.13, 'OI': 0.05,
- 'P': 0.05, 'PB': 0.05, 'PF': 0.1, 'PG': 0.05, 'PK': 0.05,
- 'PP': 0.07, 'RB': 0.05, 'RI': 0.05, 'RM': 0.05, 'RU': 0.05,
- 'SA': 0.05, 'SC': 0.12, 'SF': 0.05, 'SH': 0.05, 'SI': 0.13, 'SM': 0.05, 'SN': 0.05, 'SP': 0.1, 'SR': 0.05,
- 'SS': 0.05, 'TA': 0.05, 'UR': 0.09, 'V': 0.07,
- 'Y': 0.05, 'ZC': 0.05, 'ZN': 0.05},
- 'short': {'A': 0.07, 'AG': 0.04, 'AL': 0.05, 'AO': 0.05, 'AP': 0.08, 'AU': 0.04, 'B': 0.05,
- 'BC': 0.13, 'BR': 0.07, 'BU': 0.04, 'C': 0.07, 'CF': 0.05, 'CJ': 0.07, 'CS': 0.07,
- 'CU': 0.05, 'CY': 0.05, 'EB': 0.12, 'EC': 0.12, 'EG': 0.05, 'FG': 0.05, 'FU': 0.08,
- 'HC': 0.04, 'I': 0.1, 'J': 0.22, 'JD': 0.08, 'JM': 0.22,
- 'L': 0.07, 'LC': 0.05, 'LH': 0.1, 'LR': 0.05, 'LU': 0.15, 'M': 0.07, 'MA': 0.05, 'NI': 0.05, 'NR': 0.13, 'OI': 0.05,
- 'P': 0.05, 'PB': 0.05, 'PF': 0.1, 'PG': 0.05, 'PK': 0.05,
- 'PP': 0.07, 'RB': 0.05, 'RI': 0.05, 'RM': 0.05, 'RU': 0.05,
- 'SA': 0.05, 'SC': 0.12, 'SF': 0.05, 'SH': 0.05, 'SI': 0.13, 'SM': 0.05, 'SN': 0.05, 'SP': 0.1, 'SR': 0.05,
- 'SS': 0.05, 'TA': 0.05, 'UR': 0.09, 'V': 0.07,
- 'Y': 0.05, 'ZC': 0.05, 'ZN': 0.05}
- }
-
- g.multiplier = {
- 'A': 10, 'AG': 15, 'AL': 5, 'AO': 20, 'AP': 10, 'AU': 1000, 'B': 10,
- 'BC': 5, 'BR': 5, 'BU': 10, 'C': 10, 'CF': 5, 'CJ': 5, 'CS': 10,
- 'CU': 5, 'CY': 5, 'EB': 5, 'EC': 50, 'EG': 10, 'FG': 20, 'FU': 10,
- 'HC': 10, 'I': 100, 'J': 60, 'JD': 5, 'JM': 100,
- 'L': 5, 'LC': 1, 'LH': 16, 'LR': 0.05, 'LU': 10, 'M': 10, 'MA': 10, 'NI': 1, 'NR': 10, 'OI': 10,
- 'P': 10, 'PB': 5, 'PF': 5, 'PG': 20, 'PK': 5,
- 'PP': 5, 'RB': 10, 'RI': 0.05, 'RM': 10, 'RU': 10,
- 'SA': 20, 'SC': 1000, 'SF': 5, 'SH': 30, 'SI': 5, 'SM': 5, 'SN': 1, 'SP': 10, 'SR': 10,
- 'SS': 5, 'TA': 5, 'UR': 20, 'V': 5,
- 'Y': 10, 'ZC': 0.05, 'ZN': 5
- }
-
- # 交易记录和数据存储
- g.trade_history = {}
- g.ma_cross_signals = {} # 存储多均线穿越信号
- g.daily_data_cache = {} # 存储历史日线数据缓存
- g.minute_data_cache = {} # 存储今日分钟数据缓存
- g.ma_data_cache = {} # 存储均线数据缓存
- g.ma_cross_filtered_futures = {} # 存储通过均线交叉检查的品种(每日缓存)
-
- # 保证金比例管理(g.margin_rates会根据实际交易校准)
- g.margin_rate_history = {} # 保证金比例变化历史记录
- g.today_trades = [] # 当日交易记录
-
- # 定时任务设置 - 根据新的时间安排
- # 夜盘开始
- run_daily(main_trading_21_05, time='21:05:00', reference_security='IF1808.CCFX')
- run_daily(main_trading_regular, time='21:35:00', reference_security='IF1808.CCFX')
- run_daily(main_trading_regular, time='22:05:00', reference_security='IF1808.CCFX')
- run_daily(main_trading_regular, time='22:35:00', reference_security='IF1808.CCFX')
-
- # 日盘开始
- run_daily(main_trading_09_05, time='09:05:00', reference_security='IF1808.CCFX')
- run_daily(main_trading_regular, time='09:35:00', reference_security='IF1808.CCFX')
- run_daily(main_trading_regular, time='10:05:00', reference_security='IF1808.CCFX')
- run_daily(main_trading_regular, time='10:35:00', reference_security='IF1808.CCFX')
- run_daily(main_trading_regular, time='11:05:00', reference_security='IF1808.CCFX')
- run_daily(main_trading_regular, time='11:25:00', reference_security='IF1808.CCFX')
- run_daily(main_trading_regular, time='13:35:00', reference_security='IF1808.CCFX')
- run_daily(main_trading_regular, time='14:05:00', reference_security='IF1808.CCFX')
-
- # 收盘前
- run_daily(main_trading_before_close, time='14:35:00', reference_security='IF1808.CCFX')
- run_daily(main_trading_before_close, time='14:55:00', reference_security='IF1808.CCFX')
-
- # 收盘后
- run_daily(after_market_close, time='15:30:00', reference_security='IF1808.CCFX')
- ############################ 主程序执行函数 ###################################
- def main_trading_21_05(context):
- """21:05 执行任务1, 2, 3, 4, 5, 6, 9"""
- log.info("-" * 50)
- log.info("21:05 多均线穿越突破策略 - 夜盘开始")
- log.info("执行任务: 1, 2, 3, 4, 5, 6, 9")
- log.info("-" * 50)
-
- # 任务1: 获取所有可交易品种
- task_1_get_tradable_futures(context)
-
- # 任务2: 获取历史数据并保存到内存
- task_2_load_historical_data(context)
-
- # 任务3: 检查均线交叉数量,过滤掉交叉过多的品种
- task_3_check_ma_crosses(context)
-
- # 任务4: 获取今日分钟数据并合并均线数据
- task_4_update_realtime_data(context)
-
- # 任务5: 判断上穿下穿情况
- task_5_analyze_ma_crosses(context)
-
- # 任务6: 检查开仓条件
- filtered_signals = task_6_check_opening_conditions(context)
- # 如果任务6有满足条件的,执行任务7开仓
- if filtered_signals:
- task_7_execute_trades(context, filtered_signals)
-
- # 任务9: 检查止损止盈
- task_9_check_stop_loss_profit(context)
- def main_trading_09_05(context):
- """09:05 执行任务1, 2, 3, 4, 5, 6, 9"""
- log.info("-" * 50)
- log.info("09:05 多均线穿越突破策略 - 日盘开始")
- log.info("执行任务: 1, 2, 3, 4, 5, 6, 9")
- log.info("-" * 50)
-
- # 任务1: 获取所有可交易品种
- task_1_get_tradable_futures(context)
-
- # 任务2: 获取历史数据并保存到内存
- task_2_load_historical_data(context)
-
- # 任务3: 检查均线交叉数量,过滤掉交叉过多的品种
- task_3_check_ma_crosses(context)
-
- # 任务4: 获取今日分钟数据并合并均线数据
- task_4_update_realtime_data(context)
-
- # 任务5: 判断上穿下穿情况
- task_5_analyze_ma_crosses(context)
-
- # 任务6: 检查开仓条件
- filtered_signals = task_6_check_opening_conditions(context)
- # 如果任务6有满足条件的,执行任务7开仓
- if filtered_signals:
- task_7_execute_trades(context, filtered_signals)
-
- # 任务9: 检查止损止盈
- task_9_check_stop_loss_profit(context)
- def main_trading_regular(context):
- """常规时间执行任务4, 5, 6, 9"""
- current_time = context.current_dt.strftime('%H:%M')
- # log.info(f"----- {current_time} 常规检查 -----")
- # log.info("执行任务: 4, 5, 6, 9")
-
- # 任务4: 获取今日分钟数据并合并均线数据
- task_4_update_realtime_data(context)
-
- # 任务5: 判断上穿下穿情况
- task_5_analyze_ma_crosses(context)
-
- # 任务6: 检查开仓条件
- filtered_signals = task_6_check_opening_conditions(context)
- # 如果任务6有满足条件的,执行任务7开仓
- if filtered_signals:
- task_7_execute_trades(context, filtered_signals)
-
- # 任务9: 检查止损止盈
- task_9_check_stop_loss_profit(context)
- def main_trading_before_close(context):
- """收盘前执行任务4, 5, 6, 8, 9"""
- current_time = context.current_dt.strftime('%H:%M')
- # log.info(f"----- {current_time} 收盘前检查 -----")
- # log.info("执行任务: 4, 5, 6, 8, 9")
-
- # 任务4: 获取今日分钟数据并合并均线数据
- task_4_update_realtime_data(context)
-
- # 任务5: 判断上穿下穿情况
- task_5_analyze_ma_crosses(context)
-
- # 任务6: 检查开仓条件
- filtered_signals = task_6_check_opening_conditions(context)
- # 如果任务6有满足条件的,执行任务7开仓
- if filtered_signals:
- task_7_execute_trades(context, filtered_signals)
-
- # 任务8: 检查换月移仓
- task_8_check_position_switch(context)
-
- # 任务9: 检查止损止盈
- task_9_check_stop_loss_profit(context)
- ############################ 核心任务函数 ###################################
- def task_1_get_tradable_futures(context):
- """任务1: 获取所有可交易品种(分白天和晚上)"""
- # log.info("执行任务1: 获取可交易品种")
-
- # 夜盘品种
- # potential_night_list = ['NI', 'CF', 'PF', 'Y', 'M', 'B', 'SN', 'RM', 'RB', 'HC', 'I', 'J', 'JM']
- potential_night_list = ['PF', 'Y', 'SN']
- # 日盘品种
- potential_day_list = ['PK']
- # potential_day_list = ['JD', 'UR', 'AP', 'CJ', 'PK']
-
- current_time = str(context.current_dt.time())[:2]
- if current_time in ('21', '22'):
- potential_icon_list = potential_night_list
- log.info(f"夜盘时间,可交易品种: {potential_night_list}")
- else:
- potential_icon_list = potential_day_list + potential_night_list
- log.info(f"日盘时间,可交易品种: {potential_icon_list}")
-
- potential_future_list = []
- for symbol in potential_icon_list:
- dominant_future = get_dominant_future(symbol)
- if dominant_future:
- potential_future_list.append(dominant_future)
-
- # 过滤掉已有持仓的品种
- existing_positions = set(g.trade_history.keys())
- potential_future_list = [f for f in potential_future_list if not check_symbol_prefix_match(f, existing_positions)]
-
- # 存储到全局变量
- g.tradable_futures = potential_future_list
- log.info(f"最终可交易期货品种数量: {len(potential_future_list)}")
-
- return potential_future_list
- def task_2_load_historical_data(context):
- """任务2: 获取所有可交易品种今天之前所需的数据,并保存到内存中"""
- # log.info("执行任务2: 加载历史数据到内存")
-
- if not hasattr(g, 'tradable_futures'):
- return
-
- for future_code in g.tradable_futures:
- try:
- # 获取50天历史数据(用于计算均线)
- data = attribute_history(future_code, 50, '1d',
- ['open', 'close', 'high', 'low', 'volume'],
- df=True)
-
- if data is not None and len(data) > 0:
- # 排除今天的数据
- today = context.current_dt.date()
- data = data[data.index.date < today]
-
- g.daily_data_cache[future_code] = data
- # log.info(f"已缓存 {future_code} 历史数据 {len(data)} 条")
-
- except Exception as e:
- log.warning(f"加载{future_code}历史数据时出错: {str(e)}")
- continue
-
- log.info(f"历史数据缓存完成,共缓存 {len(g.daily_data_cache)} 个品种")
- def task_3_check_ma_crosses(context):
- """任务3: 检查均线交叉数量,过滤掉交叉过多的品种"""
- # log.info("执行任务3: 检查均线交叉数量")
-
- if not hasattr(g, 'tradable_futures'):
- return
-
- # 存储通过均线交叉检查的品种
- today_date = context.current_dt.date()
- if today_date not in g.ma_cross_filtered_futures:
- g.ma_cross_filtered_futures[today_date] = []
-
- filtered_futures = []
-
- for future_code in g.tradable_futures:
- try:
- # 获取历史数据
- historical_data = g.daily_data_cache.get(future_code)
- if historical_data is None or len(historical_data) < 30:
- log.warning(f"{future_code} 历史数据不足,跳过")
- continue
-
- # 计算移动平均线
- data_with_ma = historical_data.copy()
- data_with_ma['MA5'] = data_with_ma['close'].rolling(window=5).mean()
- data_with_ma['MA10'] = data_with_ma['close'].rolling(window=10).mean()
- data_with_ma['MA20'] = data_with_ma['close'].rolling(window=20).mean()
- data_with_ma['MA30'] = data_with_ma['close'].rolling(window=30).mean()
-
- # 检查均线交叉数量
- ma_crosses = count_ma_crosses(data_with_ma, g.ma_cross_check_days)
-
- # 如果交叉数量在允许范围内,保留该品种
- if ma_crosses <= g.max_ma_crosses:
- filtered_futures.append(future_code)
- log.info(f"{future_code} 通过均线交叉检查,交叉数量: {ma_crosses}")
- else:
- log.info(f"{future_code} 均线交叉过多,被过滤,交叉数量: {ma_crosses} > {g.max_ma_crosses}")
-
- except Exception as e:
- log.warning(f"检查{future_code}均线交叉时出错: {str(e)}")
- continue
-
- # 更新可交易品种列表
- g.tradable_futures = filtered_futures
- g.ma_cross_filtered_futures[today_date] = filtered_futures
-
- log.info(f"均线交叉检查完成,剩余可交易品种数量: {len(g.tradable_futures)}")
- if len(g.tradable_futures) > 0:
- log.info(f"通过检查的品种: {g.tradable_futures}")
-
- return filtered_futures
- def task_4_update_realtime_data(context):
- """任务4: 获取所有可交易品种今天所需的分钟数据作为今天数据,和2中的数据合并出最新的均线数据,并保存到内存中"""
- # log.info("执行任务4: 更新实时数据和均线")
-
- if not hasattr(g, 'tradable_futures'):
- return
-
- for future_code in g.tradable_futures:
- log.info(f"任务4 future_code: {future_code}")
- try:
- # 获取今日分钟数据
- minute_data = get_today_minute_data(context, future_code)
- # log.info(f"minute_data: {minute_data}")
- if minute_data is None:
- continue
-
- # 获取历史数据
- historical_data = g.daily_data_cache.get(future_code)
- if historical_data is None:
- continue
-
- # 合并数据并计算均线
- combined_data = combine_and_calculate_ma(historical_data, minute_data)
- if combined_data is not None:
- g.ma_data_cache[future_code] = combined_data
- # log.info(f"已更新 {future_code} 均线数据")
-
- except Exception as e:
- log.warning(f"更新{future_code}实时数据时出错: {str(e)}")
- continue
-
- # log.info(f"实时数据更新完成,共更新 {len(g.ma_data_cache)} 个品种")
- def task_5_analyze_ma_crosses(context):
- """任务5: 根据交易品种的今天数据和均线数据,判断是否出现了上穿或者下穿的情况"""
- # log.info("执行任务5: 分析均线穿越")
-
- ma_cross_signals = []
-
- # 获取已持仓的品种列表
- existing_positions = set(g.trade_history.keys())
-
- for future_code, data in g.ma_data_cache.items():
- log.info(f"future_code: {future_code}")
- try:
- # 检查是否已有相似持仓,如果有则跳过分析
- if check_symbol_prefix_match(future_code, existing_positions):
- # log.(f"{future_code} 已有相似持仓,跳过均线穿越分析")
- continue
-
- # 检查最新的多均线穿越
- latest_cross = check_latest_multi_ma_cross(data, future_code)
- if latest_cross:
- ma_cross_signals.append(latest_cross)
- log.info(f"{future_code} 发现多均线穿越: {latest_cross['direction']}")
- log.info(f"开盘价格: {latest_cross['open']}, 当前价格: {latest_cross['close']}, 临界线: {latest_cross['critical_ma_name']}({latest_cross['critical_ma_value']:.2f}), 穿越数量: {latest_cross['crossed_count']}")
- log.info(f"MA5: {latest_cross['ma5']}, MA10: {latest_cross['ma10']}, MA20: {latest_cross['ma20']}, MA30: {latest_cross['ma30']}")
-
- except Exception as e:
- log.warning(f"分析{future_code}均线穿越时出错: {str(e)}")
- continue
-
- # 存储到全局变量
- g.ma_cross_signals = ma_cross_signals
- if len(ma_cross_signals) > 0:
- log.info(f"均线穿越分析完成,发现信号 {len(ma_cross_signals)} 个")
- log.debug(f"ma_cross_signals: {ma_cross_signals}")
-
- return ma_cross_signals
- def task_6_check_opening_conditions(context):
- """任务6: 针对那些有上穿和下穿的情况检查是否满足开仓条件"""
- # log.info("执行任务6: 检查开仓条件")
-
- if not hasattr(g, 'ma_cross_signals'):
- return []
-
- filtered_signals = []
-
- for signal in g.ma_cross_signals:
- # 检查是否已有相似持仓
- if check_symbol_prefix_match(signal['symbol'], set(g.trade_history.keys())):
- log.warning(f"{signal['symbol']} 已有相似持仓,跳过")
- continue
-
- # 检查价格位置合理性
- if not check_price_position(signal):
- log.warning(f"{signal['symbol']} 价格位置不合理,跳过")
- continue
-
- filtered_signals.append(signal)
- log.info(f"{signal['symbol']} 满足开仓条件")
-
- if len(filtered_signals) > 0:
- log.info(f"开仓条件检查完成,满足条件 {len(filtered_signals)} 个")
- return filtered_signals
- def task_7_execute_trades(context, filtered_signals):
- """任务7: 针对满足开仓条件的标的,计算购买的金额,并发起交易请求"""
- # log.info("执行任务7: 执行交易")
-
- for signal in filtered_signals:
- symbol = signal['symbol']
- direction = 'long' if signal['direction'] == 'up' else 'short'
-
- # 检查资金充足性
- if not check_sufficient_capital(context, symbol):
- log.warning(f"{symbol} 资金不足,跳过开仓")
- continue
-
- # 计算开仓金额
- order_value = calculate_order_value(context, symbol, direction)
- log.info(f"计算开仓金额: {symbol} {direction} 金额: {order_value}")
-
- # 如果计算出的金额为0,说明资金不足,跳过开仓
- if order_value <= 0:
- log.warning(f"资金不足,跳过开仓 {symbol} {direction}")
- continue
-
- # 执行开仓
- success = open_position(context, symbol, order_value, direction, signal)
-
- if success:
- # 获取实际保证金(只有在开仓成功时才能获取)
- actual_margin = g.trade_history[symbol]['actual_margin']
- log.info(f"成功开仓 {symbol} {direction} 金额: {order_value}, 实际保证金: {actual_margin:.0f}")
- else:
- log.warning(f"开仓失败 {symbol} {direction}")
- def task_8_check_position_switch(context):
- """任务8: 针对已经持仓的标的,检查是否换月移仓"""
- # log.info("执行任务8: 检查换月移仓")
-
- switch_result = position_auto_switch(context)
- if switch_result:
- log.info(f"执行了 {len(switch_result)} 次移仓换月")
- for result in switch_result:
- log.info(f"移仓: {result['before']} -> {result['after']}")
- # else:
- # log.info("无需移仓换月")
- def task_9_check_stop_loss_profit(context):
- """任务9: 针对已经持仓的标的,检查是否止损或止盈"""
- # log.info("执行任务9: 检查止损止盈")
-
- # 遍历所有持仓进行止损止盈检查
- subportfolio = context.subportfolios[0]
- long_positions = list(subportfolio.long_positions.values())
- short_positions = list(subportfolio.short_positions.values())
-
- closed_count = 0
- for position in long_positions + short_positions:
- if check_stop_loss_profit(context, position):
- closed_count += 1
-
- if closed_count > 0:
- log.info(f"执行了 {closed_count} 次止损止盈")
- # else:
- # log.info("无需止损止盈")
- ############################ 数据处理辅助函数 ###################################
- def check_has_night_session(underlying_symbol):
- """检查品种是否有夜盘"""
- # 有夜盘的品种列表
- night_session_symbols = {
- 'NI', 'CF', 'PF', 'Y', 'M', 'B', 'SN', 'RM', 'RB', 'HC', 'I', 'J', 'JM',
- 'A', 'AG', 'AL', 'AU', 'BU', 'C', 'CU', 'FU', 'L', 'P', 'PB', 'RU',
- 'SC', 'SP', 'SS', 'TA', 'V', 'ZC', 'ZN', 'MA', 'SR', 'OI', 'CF', 'RM',
- 'FG', 'SA', 'UR', 'NR', 'LU', 'BC', 'EC', 'PP', 'EB', 'EG', 'PG'
- }
- return underlying_symbol in night_session_symbols
- def get_today_minute_data(context, future_code):
- """获取今日分钟数据"""
- try:
- # 判断该品种是否有夜盘
- underlying_symbol = future_code.split('.')[0][:-4]
- has_night_session = check_has_night_session(underlying_symbol)
-
- end_time = context.current_dt
-
- # 获取足够的历史分钟数据
- minute_data = attribute_history(future_code,
- count=800, # 获取足够多的数据
- unit='1m',
- fields=['open', 'close', 'high', 'low', 'volume'],
- df=True)
-
- if minute_data is None or len(minute_data) == 0:
- return None
-
- # log.debug(f"原始分钟数据范围: {minute_data.index[0]} 到 {minute_data.index[-1]}")
-
- # 提取所有日期(年月日维度)
- minute_data['date'] = minute_data.index.date
- unique_dates = sorted(minute_data['date'].unique())
- # log.debug(f"数据包含的日期: {unique_dates}")
-
- if has_night_session:
- # 有夜盘的品种:需要找到前一交易日的21:00作为今日开盘起点
- today_date = end_time.date()
-
- # 找到今天之前的最后一个交易日
- previous_trading_dates = [d for d in unique_dates if d < today_date]
- # log.debug(f"夜盘标的 today_date: {today_date}, previous_trading_dates: {previous_trading_dates}")
- if not previous_trading_dates:
- # log.warning(f"找不到{future_code}的前一交易日数据")
- return minute_data
-
- previous_trading_date = max(previous_trading_dates)
- # log.debug(f"前一交易日: {previous_trading_date}")
-
- # 找到前一交易日21:00:00的数据作为开盘起点
- previous_day_data = minute_data[minute_data['date'] == previous_trading_date]
- night_21_data = previous_day_data[previous_day_data.index.hour == 21]
-
- if len(night_21_data) > 0:
- # 从前一交易日21:00开始的所有数据
- start_time = night_21_data.index[0] # 21:00:00的时间点
- filtered_data = minute_data[minute_data.index >= start_time]
- # log.debug(f"夜盘品种,从{start_time}开始,数据量: {len(filtered_data)}")
- return filtered_data.drop(columns=['date'])
- else:
- # log.warning(f"找不到{future_code}前一交易日21:00的数据")
- # 备选方案:使用今天9:00开始的数据
- today_data = minute_data[minute_data['date'] == today_date]
- day_9_data = today_data[today_data.index.hour >= 9]
- if len(day_9_data) > 0:
- return day_9_data.drop(columns=['date'])
- else:
- return minute_data.drop(columns=['date'])
- else:
- # 没有夜盘的品种:从今天9:00:00开始
- today_date = end_time.date()
- today_data = minute_data[minute_data['date'] == today_date]
-
- # 找到今天9:00:00开始的数据
- day_9_data = today_data[today_data.index.hour >= 9]
-
- if len(day_9_data) > 0:
- # log.debug(f"日盘品种,从今天9:00开始,数据量: {len(day_9_data)}")
- return day_9_data.drop(columns=['date'])
- else:
- # log.warning(f"找不到{future_code}今天9:00的数据")
- return today_data.drop(columns=['date']) if len(today_data) > 0 else minute_data.drop(columns=['date'])
-
- except Exception as e:
- log.warning(f"获取{future_code}今日分钟数据时出错: {str(e)}")
-
- return None
- def combine_and_calculate_ma(historical_data, minute_data):
- """合并历史数据和分钟数据,计算均线"""
- try:
- # 将分钟数据聚合为日数据
- today_data = aggregate_minute_to_daily(minute_data)
- if today_data is None:
- return None
-
- # 合并历史数据和今日数据
- combined_data = pd.concat([historical_data, today_data])
-
- # 计算移动平均线
- combined_data['MA5'] = combined_data['close'].rolling(window=5).mean()
- combined_data['MA10'] = combined_data['close'].rolling(window=10).mean()
- combined_data['MA20'] = combined_data['close'].rolling(window=20).mean()
- combined_data['MA30'] = combined_data['close'].rolling(window=30).mean()
-
- return combined_data
-
- except Exception as e:
- log.warning(f"合并数据和计算均线时出错: {str(e)}")
- return None
- def aggregate_minute_to_daily(minute_data):
- """将分钟数据聚合为日数据
- 注意:传入的minute_data已经是经过过滤的今日交易数据
- - 对于有夜盘的品种:数据从前一交易日21:00开始
- - 对于无夜盘的品种:数据从当日9:00开始
- 开盘价(open)是第一个分钟K线的开盘价(今日交易开盘价)
- 收盘价(close)是当前最新的分钟K线收盘价,会随时间更新
- """
- try:
- if minute_data is None or len(minute_data) == 0:
- return None
-
- # 获取今日日期(使用最后一条数据的日期作为今日日期)
- today_date = minute_data.index[-1].date()
- # log.debug(f"聚合数据范围: {minute_data.index[0]} 到 {minute_data.index[-1]}")
- # log.debug(f"开盘价数据: {minute_data['open'].iloc[0]:.2f}")
-
- # 聚合为日数据
- # 开盘价:今日交易开始时的第一个分钟K线的开盘价(固定不变)
- # 收盘价:当前最新分钟K线的收盘价(实时更新)
- # 最高价:所有分钟K线中的最高价
- # 最低价:所有分钟K线中的最低价
- # 成交量:所有分钟K线成交量的总和
- daily_data = pd.DataFrame({
- 'open': [minute_data['open'].iloc[0]], # 今日交易开始时的开盘价
- 'close': [minute_data['close'].iloc[-1]], # 当前收盘价,实时更新
- 'high': [minute_data['high'].max()],
- 'low': [minute_data['low'].min()],
- 'volume': [minute_data['volume'].sum()]
- }, index=[pd.Timestamp(today_date)])
-
- # log.debug(f"聚合后的日数据: 开盘价={daily_data['open'].iloc[0]:.2f}, 收盘价={daily_data['close'].iloc[0]:.2f}")
-
- return daily_data
-
- except Exception as e:
- log.warning(f"聚合分钟数据时出错: {str(e)}")
- return None
- ############################ 原有函数保持不变 ###################################
- def check_latest_multi_ma_cross(data, future_code):
- """检查最新的多均线穿越情况"""
- if len(data) < 2:
- return None
-
- # 获取最新两天的数据
- today = data.iloc[-1]
- yesterday = data.iloc[-2]
- # log.info(f"today: {today}")
- # log.info(f"yesterday: {yesterday}")
-
- # 检查多均线穿越
- cross_result = check_multi_ma_cross_single_day(today)
- if not cross_result:
- return None
-
- # TODO:验证穿越的有效性,暂时感觉没用先注释了
- # 验证穿越的有效性
- # if not validate_ma_cross(today, yesterday):
- # return None
-
- return {
- 'symbol': future_code,
- 'date': today.name,
- 'direction': cross_result['direction'],
- 'open': today['open'],
- 'close': today['close'],
- 'high': today['high'],
- 'low': today['low'],
- 'ma5': today['MA5'],
- 'ma10': today['MA10'],
- 'ma20': today['MA20'],
- 'ma30': today['MA30'],
- 'critical_ma_name': cross_result['critical_ma_name'],
- 'critical_ma_value': cross_result['critical_ma_value'],
- 'crossed_count': cross_result['crossed_count']
- }
- def check_multi_ma_cross_single_day(row):
- """检查单日K线是否穿越了至少3条均线,并返回临界线信息"""
- open_price = row['open']
- close_price = row['close']
- ma_values = [('MA5', row['MA5']), ('MA10', row['MA10']), ('MA20', row['MA20']), ('MA30', row['MA30'])]
- log.debug(f"open_price: {open_price}, close_price: {close_price}, ma_values: {ma_values}")
- # 检查是否有NaN值
- if pd.isna(row['MA5']) or pd.isna(row['MA10']) or pd.isna(row['MA20']) or pd.isna(row['MA30']):
- return None
-
- # 如果开盘价和收盘价相等,不可能有穿越
- if open_price == close_price:
- return None
-
- crossed_mas = []
-
- # 上涨(阳线),检查上穿
- if close_price > open_price:
- for ma_name, ma_value in ma_values:
- if open_price < ma_value and close_price > ma_value:
- crossed_mas.append((ma_name, ma_value))
-
- if len(crossed_mas) >= g.min_cross_mas:
- # 找到最大的穿越线作为临界线
- critical_ma = max(crossed_mas, key=lambda x: x[1])
- return {
- 'direction': 'up',
- 'critical_ma_name': critical_ma[0],
- 'critical_ma_value': critical_ma[1],
- 'crossed_count': len(crossed_mas)
- }
-
- # 下跌(阴线),检查下穿
- elif open_price > close_price:
- for ma_name, ma_value in ma_values:
- if open_price > ma_value and close_price < ma_value:
- crossed_mas.append((ma_name, ma_value))
-
- if len(crossed_mas) >= g.min_cross_mas:
- # 找到最小的穿越线作为临界线
- critical_ma = min(crossed_mas, key=lambda x: x[1])
- return {
- 'direction': 'down',
- 'critical_ma_name': critical_ma[0],
- 'critical_ma_value': critical_ma[1],
- 'crossed_count': len(crossed_mas)
- }
-
- return None
- def validate_ma_cross(today, yesterday):
- """验证均线穿越的有效性"""
- # 检查均线排列是否合理
- ma_today = [today['MA5'], today['MA10'], today['MA20'], today['MA30']]
- ma_yesterday = [yesterday['MA5'], yesterday['MA10'], yesterday['MA20'], yesterday['MA30']]
-
- # 简单的均线排列检查
- # 可以根据需要添加更复杂的验证逻辑
- return True
- def check_sufficient_capital(context, symbol):
- """检查资金是否充足"""
- try:
- # 计算单手保证金
- single_hand_margin = calculate_required_margin(context, symbol)
- # 使用实际可用资金(考虑资金使用比例)
- available_cash = context.portfolio.available_cash * g.usage_percentage
-
- # 检查是否有足够资金开仓至少1手
- return available_cash >= single_hand_margin
- except:
- return False
- def check_price_position(signal):
- """检查价格位置的合理性"""
- close = signal['close']
- critical_ma_value = signal['critical_ma_value']
-
- # 检查收盘价与临界线的偏离度
- deviation = abs(close - critical_ma_value) / critical_ma_value
-
- # 偏离度需要在合理范围内:大于最小偏离度且小于最大偏离度
- if deviation < g.price_deviation_min:
- log.warning(f"价格偏离度过小: {deviation:.3%} < {g.price_deviation_min:.1%}")
- return False
- elif deviation > g.price_deviation_max:
- log.warning(f"价格偏离度过大: {deviation:.3%} > {g.price_deviation_max:.1%}")
- return False
- else:
- log.info(f"价格偏离度合理: {g.price_deviation_min:.1%} <= {deviation:.3%} <= {g.price_deviation_max:.1%}")
- return True
- ############################ 交易执行函数 ###################################
- def open_position(context, security, value, direction, signal):
- """开仓"""
- try:
- # 记录交易前的可用资金
- cash_before = context.portfolio.available_cash
-
- order = order_target_value(security, value, side=direction)
- log.info(f"order: {order}")
-
- if order is not None and order.filled > 0:
- # 记录交易后的可用资金
- cash_after = context.portfolio.available_cash
-
- # 计算实际资金变化
- cash_change = cash_before - cash_after
-
- # 获取订单价格和数量
- order_price = order.avg_cost if order.avg_cost else order.price
- order_amount = order.filled
-
- # 计算实际保证金比例
- underlying_symbol = security.split('.')[0][:-4]
- multiplier = g.multiplier.get(underlying_symbol, 10)
-
- # 单笔保证金 = 资金变化 / 数量
- single_margin = cash_change / order_amount if order_amount > 0 else 0
-
- # 实际保证金比例 = 单笔保证金 / (订单价格 * 合约乘数)
- contract_value = order_price * multiplier
- actual_margin_rate = single_margin / contract_value if contract_value > 0 else 0
-
- # 校准保证金比例(只有变化大于1%时才更新)
- current_rate = g.margin_rates.get(direction, {}).get(underlying_symbol, 0.10)
- rate_change = abs(actual_margin_rate - current_rate) / current_rate if current_rate > 0 else 0
-
- if rate_change > 0.01: # 变化大于1%
- # 记录保证金比例变化历史
- history_key = f"{underlying_symbol}_{direction}"
- if history_key not in g.margin_rate_history:
- g.margin_rate_history[history_key] = []
-
- g.margin_rate_history[history_key].append({
- 'date': context.current_dt.date(),
- 'time': context.current_dt.time(),
- 'old_rate': current_rate,
- 'new_rate': actual_margin_rate,
- 'change_pct': rate_change * 100,
- 'security': security
- })
-
- # 直接更新默认保证金比例
- g.margin_rates[direction][underlying_symbol] = actual_margin_rate
-
- log.info(f"保证金比例校准: {underlying_symbol}_{direction} {current_rate:.4f} -> {actual_margin_rate:.4f} (变化{rate_change*100:.1f}%)")
-
- # 记录当日交易
- g.today_trades.append({
- 'security': security,
- 'underlying_symbol': underlying_symbol,
- 'direction': direction,
- 'order_amount': order_amount,
- 'order_price': order_price,
- 'cash_change': cash_change,
- 'actual_margin_rate': actual_margin_rate,
- 'time': context.current_dt
- })
-
- # 记录交易信息
- g.trade_history[security] = {
- 'entry_price': order_price,
- 'position_value': value,
- 'actual_margin': cash_change,
- 'direction': direction,
- 'entry_time': context.current_dt,
- 'signal_info': signal
- }
-
- log.info(f"开仓成功 - 品种: {underlying_symbol}, 手数: {order_amount}, 订单价格: {order_price:.2f}")
- log.info(f"资金变化: {cash_change:.0f}, 实际保证金比例: {actual_margin_rate:.4f}")
- return True
-
- except Exception as e:
- log.warning(f"开仓失败 {security}: {str(e)}")
-
- return False
- def close_position(context, security, direction):
- """平仓"""
- try:
- order = order_target_value(security, 0, side=direction)
-
- if order is not None and order.filled > 0:
- underlying_symbol = security.split('.')[0][:-4]
-
- # 记录当日交易(平仓)
- g.today_trades.append({
- 'security': security,
- 'underlying_symbol': underlying_symbol,
- 'direction': direction,
- 'order_amount': -order.filled, # 负数表示平仓
- 'order_price': order.avg_cost if order.avg_cost else order.price,
- 'cash_change': 0, # 平仓不计算保证金变化
- 'actual_margin_rate': 0,
- 'time': context.current_dt
- })
-
- log.info(f"平仓成功 - 品种: {underlying_symbol}, 手数: {order.filled}")
-
- # 从交易历史中移除
- if security in g.trade_history:
- del g.trade_history[security]
- return True
-
- except Exception as e:
- log.warning(f"平仓失败 {security}: {str(e)}")
-
- return False
- def check_stop_loss_profit(context, position):
- """检查止损止盈"""
- security = position.security
-
- if security not in g.trade_history:
- return False
-
- trade_info = g.trade_history[security]
- entry_price = trade_info['entry_price']
- current_price = position.price
- direction = trade_info['direction']
-
- # 计算盈亏
- if direction == 'long':
- pnl_ratio = (current_price - entry_price) / entry_price
- else:
- pnl_ratio = (entry_price - current_price) / entry_price
-
- # 止损条件
- stop_loss_ratio = -0.03 # 3%止损
- # 止盈条件
- take_profit_ratio = 0.05 # 5%止盈
-
- if pnl_ratio <= stop_loss_ratio:
- log.info(f"触发止损 {security} 盈亏比例: {pnl_ratio:.2%}")
- close_position(context, security, direction)
- return True
- elif pnl_ratio >= take_profit_ratio:
- log.info(f"触发止盈 {security} 盈亏比例: {pnl_ratio:.2%}")
- close_position(context, security, direction)
- return True
-
- return False
- ############################ 辅助函数 ###################################
- def calculate_order_value(context, security, direction):
- """计算开仓金额"""
- current_price = get_current_data()[security].last_price
- underlying_symbol = security.split('.')[0][:-4]
-
- # 使用保证金比例(已经过校准)
- margin_rate = g.margin_rates.get(direction, {}).get(underlying_symbol, 0.10)
-
- multiplier = g.multiplier.get(underlying_symbol, 10)
-
- # 计算单手保证金
- single_hand_margin = current_price * multiplier * margin_rate
-
- # 还要考虑可用资金限制
- available_cash = context.portfolio.available_cash * g.usage_percentage
- log.info(f"可用资金: {available_cash:.0f}")
-
- # 根据单个标的最大持仓保证金限制计算开仓数量
- max_margin = g.max_margin_per_position
-
- if single_hand_margin <= max_margin:
- # 如果单手保证金不超过最大限制,计算最大可开仓手数
- max_hands = int(max_margin / single_hand_margin)
-
- max_hands_by_cash = int(available_cash / single_hand_margin)
-
- # 取两者较小值
- actual_hands = min(max_hands, max_hands_by_cash)
- # 实际保证金金额
- actual_margin = current_price * multiplier * margin_rate * actual_hands
- # 计算订单金额
- order_value = actual_margin
-
- log.info(f"单手保证金: {single_hand_margin:.0f}, 最大手数(保证金限制): {max_hands}, 最大手数(资金限制): {max_hands_by_cash}, 实际开仓手数: {actual_hands}, 实际保证金: {actual_margin:.0f}")
- else:
- # 如果单手保证金超过最大限制,默认开仓1手
- actual_hands = 1
- actual_margin = current_price * multiplier * margin_rate * actual_hands
- # 计算订单金额
- order_value = actual_margin
-
- log.info(f"单手保证金: {single_hand_margin:.0f} 超过最大限制: {max_margin}, 默认开仓1手, 实际保证金: {actual_margin:.0f}")
-
- log.info(f"计算结果 - 品种: {underlying_symbol}, 开仓手数: {actual_hands}, 订单金额: {order_value:.0f}, 实际保证金: {actual_margin:.0f}")
-
- return order_value
- def calculate_required_margin(context, symbol):
- """计算所需保证金"""
- current_price = get_current_data()[symbol].last_price
- underlying_symbol = symbol.split('.')[0][:-4]
-
- margin_rate = g.margin_rates.get('long', {}).get(underlying_symbol, 0.10)
- multiplier = g.multiplier.get(underlying_symbol, 10)
-
- return current_price * multiplier * margin_rate
- def check_symbol_prefix_match(symbol, hold_symbols):
- """检查是否有相似的持仓品种"""
- symbol_prefix = symbol[:-9]
-
- for hold_symbol in hold_symbols:
- hold_symbol_prefix = hold_symbol[:-9]
- if symbol_prefix == hold_symbol_prefix:
- return True
- return False
- def after_market_close(context):
- """收盘后运行函数"""
- log.info(str('函数运行时间(after_market_close):'+str(context.current_dt.time())))
-
- # 只有当天有交易时才打印统计信息
- if g.today_trades:
- print_daily_trading_summary(context)
- print_margin_rate_changes(context)
-
- # 清空当日交易记录
- g.today_trades = []
-
- log.info('A day ends')
- log.info('##############################################################')
- def print_daily_trading_summary(context):
- """打印当日交易汇总"""
- if not g.today_trades:
- return
-
- log.info("\n=== 当日交易汇总 ===")
- total_margin = 0
-
- for trade in g.today_trades:
- if trade['order_amount'] > 0: # 开仓
- log.info(f"开仓 {trade['underlying_symbol']} {trade['direction']} {trade['order_amount']}手 "
- f"价格:{trade['order_price']:.2f} 保证金:{trade['cash_change']:.0f} "
- f"比例:{trade['actual_margin_rate']:.4f}")
- total_margin += trade['cash_change']
- else: # 平仓
- log.info(f"平仓 {trade['underlying_symbol']} {trade['direction']} {abs(trade['order_amount'])}手 "
- f"价格:{trade['order_price']:.2f}")
-
- log.info(f"当日保证金占用: {total_margin:.0f}")
- log.info("==================\n")
- def print_margin_rate_changes(context):
- """打印保证金比例变化记录"""
- if not g.margin_rate_history:
- return
-
- log.info("\n=== 保证金比例变化记录 ===")
- for key, history in g.margin_rate_history.items():
- log.info(f"{key}:")
- for record in history:
- log.info(f" {record['date']} {record['time']}: {record['old_rate']:.4f} -> {record['new_rate']:.4f} "
- f"(变化{record['change_pct']:.1f}%)")
- log.info("========================\n")
- ########################## 自动移仓换月函数 #################################
- def position_auto_switch(context,pindex=0,switch_func=None, callback=None):
- """
- 期货自动移仓换月。默认使用市价单进行开平仓。
- :param context: 上下文对象
- :param pindex: 子仓对象
- :param switch_func: 用户自定义的移仓换月函数.
- 函数原型必须满足: func(context, pindex, previous_dominant_future_position, current_dominant_future_symbol)
- :param callback: 移仓换月完成后的回调函数。
- 函数原型必须满足: func(context, pindex, previous_dominant_future_position, current_dominant_future_symbol)
- :return: 发生移仓换月的标的。类型为列表。
- """
- import re
- subportfolio = context.subportfolios[pindex]
- symbols = set(subportfolio.long_positions.keys()) | set(subportfolio.short_positions.keys())
- switch_result = []
- for symbol in symbols:
- match = re.match(r"(?P<underlying_symbol>[A-Z]{1,})", symbol)
- if not match:
- # raise ValueError("未知期货标的: {}".format(symbol))
- raise ValueError("Unknow target: {}".format(symbol))
- else:
- dominant = get_dominant_future(match.groupdict()["underlying_symbol"])
- cur = get_current_data()
- symbol_last_price = cur[symbol].last_price
- dominant_last_price = cur[dominant].last_price
- log.info(f'current_hold_symbol: {symbol}, current_main_symbol: {dominant}')
-
- if dominant > symbol:
- for positions_ in (subportfolio.long_positions, subportfolio.short_positions):
- if symbol not in positions_.keys():
- continue
- else :
- p = positions_[symbol]
- if switch_func is not None:
- switch_func(context, pindex, p, dominant)
- else:
- amount = p.total_amount
- # 跌停不能开空和平多,涨停不能开多和平空。
- if p.side == "long":
- symbol_low_limit = cur[symbol].low_limit
- dominant_high_limit = cur[dominant].high_limit
- if symbol_last_price <= symbol_low_limit:
- # log.warning("标的{}跌停,无法平仓。移仓换月取消。".format(symbol))
- log.warning("Can't close {} position due to the limit up. Cancelling the exchange.".format(symbol))
- continue
- elif dominant_last_price >= dominant_high_limit:
- # log.warning("标的{}涨停,无法开仓。移仓换月取消。".format(symbol))
- log.warning("Can't close {} position due to the limit down. Cancelling the exchange.".format(symbol))
- continue
- else:
- # log.info("进行移仓换月: ({0},long) -> ({1},long)".format(symbol, dominant))
- log.info("Start the exchange: ({0},long) -> ({1},long)".format(symbol, dominant))
- order_old = order_target(symbol,0,side='long')
- if order_old != None and order_old.filled > 0:
- order_new = order_target(dominant,amount,side='long')
- if order_new != None and order_new.filled >0:
- switch_result.append({"before": symbol, "after":dominant, "side": "long"})
- # 换月中的买卖都成功了,则增加新的记录去掉旧的记录
- g.trade_history[dominant] = g.trade_history[symbol]
- del g.trade_history[symbol]
- else:
- # log.warning("标的{}交易失败,无法开仓。移仓换月取消。".format(domaint))
- log.warning("Trade of {} failed, no new positions. Cancelling the exchange.".format(dominant))
- # 换月中的买成功了,卖失败了,则在换月记录里增加新的记录,在交易记录里去掉旧的记录
- log.warning(f'换月多头失败{dominant}, {g.trade_history[symbol]}')
- g.change_fail_history[domaint] = g.trade_history[symbol]
- del g.trade_history[symbol]
- if callback:
- callback(context, pindex, p, dominant)
- if p.side == "short":
- symbol_high_limit = cur[symbol].high_limit
- dominant_low_limit = cur[dominant].low_limit
- if symbol_last_price >= symbol_high_limit:
- # log.warning("标的{}涨停,无法平仓。移仓换月取消。".format(symbol))
- log.warning("Can't close {} position due to the limit up. Cancelling the exchange.".format(symbol))
- continue
- elif dominant_last_price <= dominant_low_limit:
- # log.warning("标的{}跌停,无法开仓。移仓换月取消。".format(symbol))
- log.warning("Can't close {} position due to the limit down. Cancelling the exchange.".format(symbol))
- continue
- else:
- # log.info("进行移仓换月: ({0},short) -> ({1},short)".format(symbol, dominant))
- log.info("Start the exchange: ({0},short) -> ({1},short)".format(symbol, dominant))
- order_old = order_target(symbol,0,side='short')
- if order_old != None and order_old.filled > 0:
- log.info(f'换月做空{dominant},数量位{amount}')
- order_new = order_target(dominant,amount,side='short')
- if order_new != None and order_new.filled >0:
- switch_result.append({"before": symbol, "after":dominant, "side": "short"})
- # 换月中的买卖都成功了,则增加新的记录去掉旧的记录
- g.trade_history[dominant] = g.trade_history[symbol]
- del g.trade_history[symbol]
- else:
- # log.warning("标的{}交易失败,无法开仓。移仓换月取消。".format(dominant))
- log.warning("Trade of {} failed, no new positions. Cancelling the exchange.".format(dominant))
- # 换月中的买成功了,卖失败了,则在换月记录里增加新的记录,在交易记录里去掉旧的记录
- log.warning(f'换月空头失败{dominant}, {g.trade_history[symbol]}')
- g.change_fail_history[dominant] = g.trade_history[symbol]
- log.warning(f'失败记录{g.change_fail_history}')
- del g.trade_history[symbol]
- # order_target(symbol,0,side='short')
- # order_target(dominant,amount,side='short')
- # switch_result.append({"before": symbol, "after": dominant, "side": "short"})
- if callback:
- callback(context, pindex, p, dominant)
- return switch_result
- def count_ma_crosses(data, days):
- """
- 判断过去指定天数内4条MA均线的交叉次数
- :param data: 包含MA5, MA10, MA20, MA30的DataFrame
- :param days: 检查的天数
- :return: 总交叉次数
- """
- if len(data) < days + 1:
- return 0
-
- # 获取最近days天的数据
- recent_data = data.iloc[-days-1:]
-
- ma5 = recent_data['MA5'].values
- ma10 = recent_data['MA10'].values
- ma20 = recent_data['MA20'].values
- ma30 = recent_data['MA30'].values
-
- # 检查是否有NaN值
- if np.any(np.isnan([ma5, ma10, ma20, ma30])):
- return 0
-
- # 计算各均线间的交叉次数
- cross_5_10 = sum([1 for i in range(1, len(ma5)) if ((ma5[i] > ma10[i] and ma5[i-1] < ma10[i-1]) or
- (ma5[i] < ma10[i] and ma5[i-1] > ma10[i-1]))])
- cross_5_20 = sum([1 for i in range(1, len(ma5)) if ((ma5[i] > ma20[i] and ma5[i-1] < ma20[i-1]) or
- (ma5[i] < ma20[i] and ma5[i-1] > ma20[i-1]))])
- cross_5_30 = sum([1 for i in range(1, len(ma5)) if ((ma5[i] > ma30[i] and ma5[i-1] < ma30[i-1]) or
- (ma5[i] < ma30[i] and ma5[i-1] > ma30[i-1]))])
- cross_10_20 = sum([1 for i in range(1, len(ma10)) if ((ma10[i] > ma20[i] and ma10[i-1] < ma20[i-1]) or
- (ma10[i] < ma20[i] and ma10[i-1] > ma20[i-1]))])
- cross_10_30 = sum([1 for i in range(1, len(ma10)) if ((ma10[i] > ma30[i] and ma10[i-1] < ma30[i-1]) or
- (ma10[i] < ma30[i] and ma10[i-1] > ma30[i-1]))])
- cross_20_30 = sum([1 for i in range(1, len(ma20)) if ((ma20[i] > ma30[i] and ma20[i-1] < ma30[i-1]) or
- (ma20[i] < ma30[i] and ma20[i-1] > ma30[i-1]))])
-
- total_crosses = cross_5_10 + cross_5_20 + cross_5_30 + cross_10_20 + cross_10_30 + cross_20_30
-
- log.debug(f'总交叉数: {total_crosses}, MA5-MA10: {cross_5_10}, MA5-MA20: {cross_5_20}, MA5-MA30: {cross_5_30}, MA10-MA20: {cross_10_20}, MA10-MA30: {cross_10_30}, MA20-MA30: {cross_20_30}')
-
- return total_crosses
|