分享了上一篇的策略,可能有朋友还有点模糊,我把核心的代码跟大家分享下,仅作为学习交流,不构成任何投资建议。
import math
from tqsdk import TqApi, TqAuth, tafunc, TqSim, TqBacktest, TqAccount, TargetPosTask
from datetime import datetime
import pandas as pd
amt = 3000000
order_vol = 1
api = None
auth = TqAuth(username, password)
start_time = datetime(2024, 1, 1, 14, 30)
end_time = datetime(2024, 12, 31, 15, 0)
backtest_acct = TqSim(amt)
api = TqApi(backtest_acct, auth=auth, backtest=TqBacktest(start_dt=start_time,
end_dt=end_time), web_gui=True)
main_symbol = "KQ.m@CFFEX.IM"
quote = api.get_quote(main_symbol)
symbol = quote.underlying_symbol
backtest_acct.set_margin(symbol, 140000)
backtest_acct.set_commission(symbol, 150)
index_code = "SSE.000852"
kline_day = api.get_kline_serial(index_code, 24 * 60 * 60,10)
position = api.get_position(symbol) # 持仓信息
target_pos = TargetPosTask(api, symbol)
current_flag = 0
while True:
api.wait_update()
if api.is_changing(quote):
quote_datetime = tafunc.time_to_datetime(quote.datetime)
if quote_datetime.hour == 14 and quote_datetime.minute == 50:
target_pos.set_target_volume(0)
current_flag = 0
if quote_datetime.hour == 9 and quote_datetime.minute == 45:
# print(tafunc.time_to_datetime(kline_day.iloc[-2].datetime))
if kline_day.iloc[-2].volume != 0:
kline_datetime = tafunc.time_to_datetime(kline_day.iloc[-2].datetime)
if kline_datetime.hour == 0 and kline_datetime.minute == 0:
open = kline_day.iloc[-2].open
close = kline_day.iloc[-2].close
high = kline_day.iloc[-2].high
low = kline_day.iloc[-2].low
five_day_return = sum(kline_day.iloc[-i].close/kline_day.iloc[-i-1].close - 1 for i in range(2,7))
# 计算上涨和下跌天数
up_days = sum(1 for i in range(2,7) if kline_day.iloc[-i].close > kline_day.iloc[-i-1].close)
down_days = 5 - up_days
if down_days < up_days:
if five_day_return < 0: current_flag='1' elif open and high - openopen - low>= 1:
current_flag = 1 # 做多
else:
current_flag = -1 # 做空
else:
if five_day_return >= 0:
current_flag = 1 # 做多
elif close != low and (high - close)/(close - low) >= 1:
current_flag = 1 # 做多
else:
current_flag = -1 # 做空
if current_flag == 1:
if api.get_account().available < 300000:
current_vol = 1
else:
current_vol = api.get_account().available / 300000
if position.pos_long == 0 and position.pos_short == 0:
target_pos.set_target_volume(current_vol)
if current_flag == -1:
if api.get_account().available < 300000:
current_vol = 1
else:
current_vol = api.get_account().available / 300000
if position.pos_long == 0 and position.pos_short == 0:
target_pos.set_target_volume(-current_vol)
api.close
代码是用天勤量化的框架实现的,再次声明下,该策略仅仅是针对像本次牛市的震荡行情有效。
发布者:股市刺客,转载请注明出处:https://www.95sca.cn/archives/987730
站内所有文章皆来自网络转载或读者投稿,请勿用于商业用途。如有侵权、不妥之处,请联系站长并出示版权证明以便删除。敬请谅解!