Skip to content

Commit

Permalink
V0.9.44 更新一批代码 (waditu#188)
Browse files Browse the repository at this point in the history
* 0.9.44 update

* 0.9.44 新增协整分析

* 0.9.44 rwc 新增 update_last 方法

* 0.9.44 update

* 0.9.44 新增 stats 和 daily_return 属性

* 0.9.44 新增样本内外统计指标对比

* 0.9.44 新增 redis 策略删除和读取函数

* 0.9.44 update

* 0.9.44 新增rolling工具函数

* 0.9.44 update

* 0.9.44 update

* 0.9.44 update

* 0.9.44 update
  • Loading branch information
zengbin93 authored Mar 8, 2024
1 parent 1593279 commit 3e9596b
Show file tree
Hide file tree
Showing 22 changed files with 935 additions and 1,475 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/pythonpackage.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ name: Python package

on:
push:
branches: [ master, V0.9.43 ]
branches: [ master, V0.9.44 ]
pull_request:
branches: [ master ]

Expand Down
9 changes: 7 additions & 2 deletions czsc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@
RedisWeightsClient,
get_strategy_mates,
get_heartbeat_time,
clear_strategy,
get_strategy_weights,

OpensOptimize,
ExitsOptimize,
Expand Down Expand Up @@ -117,6 +119,8 @@
show_ts_rolling_corr,
show_ts_self_corr,
show_stoploss_by_direction,
show_cointegration,
show_out_in_compare,
)

from czsc.utils.bi_info import (
Expand All @@ -137,12 +141,13 @@

from czsc.features.utils import (
is_event_feature,
rolling_corr,
)

__version__ = "0.9.43"
__version__ = "0.9.44"
__author__ = "zengbin93"
__email__ = "[email protected]"
__date__ = "20240222"
__date__ = "20240302"


def welcome():
Expand Down
5 changes: 3 additions & 2 deletions czsc/connectors/cooperation.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ def get_raw_bars(symbol, freq, sdt, edt, fq='前复权', **kwargs):
:return:
"""
freq = czsc.Freq(freq)
raw_bars = kwargs.get('raw_bars', True)

if "SH" in symbol or "SZ" in symbol:
fq_map = {"前复权": "qfq", "后复权": "hfq", "不复权": None}
Expand All @@ -137,7 +138,7 @@ def get_raw_bars(symbol, freq, sdt, edt, fq='前复权', **kwargs):

df.rename(columns={'code': 'symbol'}, inplace=True)
df['dt'] = pd.to_datetime(df['dt'])
return czsc.resample_bars(df, target_freq=freq)
return czsc.resample_bars(df, target_freq=freq, raw_bars=raw_bars)

if symbol.endswith("9001"):
# https://s0cqcxuy3p.feishu.cn/wiki/WLGQwJLWQiWPCZkPV7Xc3L1engg
Expand All @@ -154,7 +155,7 @@ def get_raw_bars(symbol, freq, sdt, edt, fq='前复权', **kwargs):
df['amount'] = df['vol'] * df['close']
df = df[['symbol', 'dt', 'open', 'close', 'high', 'low', 'vol', 'amount']].copy().reset_index(drop=True)
df['dt'] = pd.to_datetime(df['dt'])
return czsc.resample_bars(df, target_freq=freq)
return czsc.resample_bars(df, target_freq=freq, raw_bars=raw_bars)

if symbol.endswith(".NH"):
if freq != Freq.D:
Expand Down
228 changes: 228 additions & 0 deletions czsc/connectors/tq_connector.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
# -*- coding: utf-8 -*-
"""
author: zengbin93
email: [email protected]
create_dt: 2024/3/7 18:49
describe: 对接天勤量化
1. [使用 tqsdk 进行期货交易](https://s0cqcxuy3p.feishu.cn/wiki/wikcn41lQIAJ1f8v41Dj5eAmrub)
2. [使用 tqsdk 查看期货实时行情](https://s0cqcxuy3p.feishu.cn/wiki/SH3mwOU6piPqnGkRRiocQrhAnrh)
"""
import czsc
import pandas as pd
from loguru import logger
from typing import List, Union, Optional
from datetime import date, datetime, timedelta
from czsc import Freq, RawBar
from tqsdk import ( # noqa
TqApi, TqAuth, TqSim, TqBacktest, TargetPosTask, BacktestFinished, TqAccount, TqKq
)


def format_kline(df, freq=Freq.F1):
"""对分钟K线进行格式化"""
freq = Freq(freq)
rows = df.to_dict('records')
raw_bars = []
for i, row in enumerate(rows):
bar = RawBar(symbol=row['symbol'], id=i, freq=freq,
dt=datetime.fromtimestamp(row["datetime"] / 1e9) + timedelta(minutes=1),
open=row['open'], close=row['close'], high=row['high'],
low=row['low'], vol=row['volume'], amount=row['volume'] * row['close'])
raw_bars.append(bar)
return raw_bars


# https://doc.shinnytech.com/tqsdk/latest/usage/mddatas.html 代码规则
symbols = [
# https://www.jiaoyixingqiu.com/shouxufei/jiaoyisuo/SHFE
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
# https://www.jiaoyixingqiu.com/shouxufei/jiaoyisuo/CZCE
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
# https://www.jiaoyixingqiu.com/shouxufei/jiaoyisuo/DCE
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
# https://www.jiaoyixingqiu.com/shouxufei/jiaoyisuo/GFEX
"[email protected]",
# https://www.jiaoyixingqiu.com/shouxufei/jiaoyisuo/INE
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
# https://www.jiaoyixingqiu.com/shouxufei/jiaoyisuo/CFFEX
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
]


future_name_map = {
'PG': 'LPG',
'EB': '苯乙烯',
'CS': '玉米淀粉',
'C': '玉米',
'V': 'PVC',
'J': '焦炭',
'BB': '胶合板',
'M': '豆粕',
'A': '豆一',
'PP': '聚丙烯',
'P': '棕榈油',
'FB': '纤维板',
'B': '豆二',
'JD': '鸡蛋',
'JM': '焦煤',
'L': '塑料',
'I': '铁矿石',
'Y': '豆油',
'RR': '粳米',
'EG': '乙二醇',
'LH': '生猪',
'CJ': '红枣',
'UR': '尿素',
'TA': 'PTA',
'OI': '菜油',
'MA': '甲醇',
'RS': '菜籽',
'ZC': '动力煤',
'LR': '晚籼稻',
'PM': '普麦',
'SR': '白糖',
'RI': '早籼稻',
'SF': '硅铁',
'WH': '强麦',
'JR': '粳稻',
'SM': '锰硅',
'FG': '玻璃',
'CF': '棉花',
'RM': '菜粕',
'PF': '短纤',
'AP': '苹果',
'CY': '棉纱',
'ER': '早籼稻',
'ME': '甲醇',
'RO': '菜油',
'TC': '动力煤',
'WS': '强麦',
'WT': '硬麦',
'SA': '纯碱',
'PK': '花生',
'SS': '不锈钢',
'AL': '沪铝',
'CU': '沪铜',
'ZN': '沪锌',
'AG': '白银',
'RB': '螺纹钢',
'SN': '沪锡',
'NI': '沪镍',
'WR': '线材',
'FU': '燃油',
'AU': '黄金',
'PB': '沪铅',
'RU': '橡胶',
'HC': '热轧卷板',
'BU': '沥青',
'SP': '纸浆',
'NR': '20号胶',
'SC': '原油',
'LU': '低硫燃料油',
'BC': '国际铜',
'SCTAS': '原油TAS指令',
'SI': '工业硅',
}


def is_trade_time(trade_time: Optional[str] = None):
"""判断当前是否是交易时间"""
if trade_time is None:
trade_time = datetime.now().strftime("%H:%M:%S")

if trade_time > "09:00:00" and trade_time < "11:30:00":
return True

if trade_time > "13:00:00" and trade_time < "15:00:00":
return True

if trade_time > "21:00:00" and trade_time < "02:30:00":
return True

return False


def get_daily_backup(api: TqApi, **kwargs):
"""获取每日账户中需要备份的信息"""
orders = api.get_order()
trades = api.get_trade()
position = api.get_position()
account = api.get_account()

order_ids = [x for x in list(orders.__dict__.keys()) if x not in ["_data", "_path", "_listener"]]
orders = pd.DataFrame([orders.__dict__[x] for x in order_ids])

trade_ids = [x for x in list(trades.__dict__.keys()) if x not in ["_data", "_path", "_listener"]]
trades = pd.DataFrame([trades.__dict__[x] for x in trade_ids])

position_ids = [x for x in list(position.__dict__.keys()) if x not in ["_data", "_path", "_listener"]]
positions = pd.DataFrame([position.__dict__[x] for x in position_ids])

account_ids = [x for x in list(account.__dict__.keys()) if x not in ["_data", "_path", "_listener", '_api']]
account = {x: account.__dict__[x] for x in account_ids}

backup = {
"orders": orders,
"trades": trades,
"positions": positions,
"account": account,
}
return backup
Loading

0 comments on commit 3e9596b

Please sign in to comment.