同步本地回测与tqsdk回测
This commit is contained in:
@@ -1,18 +1,19 @@
|
||||
from tqsdk import TqApi, TqAuth
|
||||
from datetime import date
|
||||
from tqsdk import TqApi, TqAuth, TqBacktest, TargetPosTask
|
||||
|
||||
api = TqApi(auth=TqAuth("emanresu", "dfgvfgdfgg"))
|
||||
'''
|
||||
如果当前价格大于5分钟K线的MA15则开多仓
|
||||
如果小于则平仓
|
||||
回测从 2018-05-01 到 2018-10-01
|
||||
'''
|
||||
# 在创建 api 实例时传入 TqBacktest 就会进入回测模式
|
||||
api = TqApi(backtest=TqBacktest(start_dt=date(2018, 5, 1), end_dt=date(2018, 10, 1)), auth=TqAuth("emanresu", "dfgvfgdfgg"))
|
||||
# 获得 m1901 5分钟K线的引用
|
||||
klines = api.get_kline_serial("DCE.m1901", 60 * 60, data_length=15)
|
||||
# 创建 m1901 的目标持仓 task,该 task 负责调整 m1901 的仓位到指定的目标仓位
|
||||
target_pos = TargetPosTask(api, "DCE.m1901")
|
||||
|
||||
# au 品种指数合约
|
||||
ls = api.query_quotes(ins_class="INDEX", product_id="au")
|
||||
print(ls)
|
||||
|
||||
# au 品种主连合约
|
||||
ls = api.query_quotes(ins_class="CONT", product_id="au")
|
||||
print(ls)
|
||||
|
||||
quote = api.get_quote("KQ.m@SHFE.rb")
|
||||
# 打印现在螺纹钢主连的标的合约
|
||||
print(quote.underlying_symbol)
|
||||
|
||||
# 关闭api,释放相应资源
|
||||
api.close()
|
||||
while True:
|
||||
api.wait_update()
|
||||
if api.is_changing(klines) and len(klines) > 2:
|
||||
target_pos.set_target_volume(5)
|
||||
@@ -109,6 +109,7 @@ def collect_and_save_tqsdk_data_stream(
|
||||
)
|
||||
|
||||
last_kline_datetime = None # 用于跟踪上一根已完成K线的时间
|
||||
swap_month_dt = None
|
||||
|
||||
while api.wait_update():
|
||||
if underlying_symbol is None:
|
||||
@@ -117,7 +118,11 @@ def collect_and_save_tqsdk_data_stream(
|
||||
# 检查是否有新的完整K线生成,或者当前K线是最后一次更新 (在回测结束时)
|
||||
# TqSdk会在K线完成时发送最后一次更新,或者在回测结束时强制更新
|
||||
if api.is_changing(quote, "underlying_symbol"):
|
||||
underlying_symbol = quote.underlying_symbol
|
||||
swap_month_dt = pd.to_datetime(
|
||||
quote.datetime, unit="ns", utc=True
|
||||
)
|
||||
|
||||
|
||||
if api.is_changing(klines):
|
||||
# 只有当K线序列发生变化时才处理
|
||||
# 关注最新一根 K 线(即 klines.iloc[-1])
|
||||
@@ -141,10 +146,15 @@ def collect_and_save_tqsdk_data_stream(
|
||||
|
||||
kline_dt = pd.to_datetime(
|
||||
current_kline["datetime"], unit="ns", utc=True
|
||||
)
|
||||
kline_dt = kline_dt.tz_convert(BEIJING_TZ).strftime(
|
||||
).tz_convert(BEIJING_TZ)
|
||||
|
||||
if swap_month_dt is not None and kline_dt.hour == swap_month_dt.hour:
|
||||
underlying_symbol = quote.underlying_symbol
|
||||
|
||||
kline_dt = kline_dt.strftime(
|
||||
"%Y-%m-%d %H:%M:%S"
|
||||
)
|
||||
|
||||
kline_data_to_save = {
|
||||
"datetime": kline_dt,
|
||||
"open": current_kline["open"],
|
||||
|
||||
Reference in New Issue
Block a user