Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

V0.9.52 更新一批代码 #199

Merged
merged 19 commits into from
Jun 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.51 ]
branches: [ master, V0.9.52 ]
pull_request:
branches: [ master ]

Expand Down
13 changes: 11 additions & 2 deletions czsc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,10 @@
get_trading_dates,
)

from czsc.utils.trade import (
adjust_holding_weights,
)

# streamlit 量化分析组件
from czsc.utils.st_components import (
show_daily_return,
Expand All @@ -140,6 +144,8 @@
show_strategies_symbol,
show_strategies_dailys,
show_holds_backtest,
show_symbols_corr,
show_feature_returns,
)

from czsc.utils.bi_info import (
Expand All @@ -166,6 +172,9 @@
rolling_tanh,
feature_adjust,
normalize_corr,
feature_to_weight,
feature_returns,
feature_sectional_corr,
)


Expand All @@ -177,10 +186,10 @@
)


__version__ = "0.9.51"
__version__ = "0.9.52"
__author__ = "zengbin93"
__email__ = "zeng_bin8888@163.com"
__date__ = "20240512"
__date__ = "20240526"


def welcome():
Expand Down
19 changes: 18 additions & 1 deletion czsc/connectors/research.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
import czsc
import glob
import pandas as pd
from datetime import datetime


# 投研共享数据的本地缓存路径,需要根据实际情况修改
cache_path = os.environ.get("czsc_research_cache", r"D:\CZSC投研数据")
Expand Down Expand Up @@ -65,5 +67,20 @@ def get_raw_bars(symbol, freq, sdt, edt, fq="前复权", **kwargs):
kline = kline[(kline["dt"] >= pd.to_datetime(sdt)) & (kline["dt"] <= pd.to_datetime(edt))]
if kline.empty:
return []
_bars = czsc.resample_bars(kline, freq, raw_bars=raw_bars, base_freq="1分钟")

df = kline.copy()
if symbol in ["SFIC9001", "SFIF9001", "SFIH9001"]:
# 股指:仅保留 09:31 - 11:30, 13:01 - 15:00
# 历史遗留问题,股指有一段时间,收盘时间是 15:15
dt1 = datetime.strptime("09:31:00", "%H:%M:%S")
dt2 = datetime.strptime("11:30:00", "%H:%M:%S")
c1 = (df["dt"].dt.time >= dt1.time()) & (df["dt"].dt.time <= dt2.time())

dt3 = datetime.strptime("13:01:00", "%H:%M:%S")
dt4 = datetime.strptime("15:00:00", "%H:%M:%S")
c2 = (df["dt"].dt.time >= dt3.time()) & (df["dt"].dt.time <= dt4.time())

df = df[c1 | c2].copy().reset_index(drop=True)

_bars = czsc.resample_bars(df, freq, raw_bars=raw_bars, base_freq="1分钟")
return _bars
58 changes: 58 additions & 0 deletions czsc/connectors/tq_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,64 @@
from tqsdk import TqApi, TqAuth, TqSim, TqBacktest, TargetPosTask, BacktestFinished, TqAccount, TqKq # noqa


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


def create_symbol_trader(api: TqApi, symbol, **kwargs):
"""创建一个品种的 CzscTrader, 回测与实盘场景同样适用

:param api: TqApi, 天勤API实例
:param symbol: str, 合约代码,要求符合天勤的规范
:param kwargs: dict, 其他参数

- sdt: str, 开始日期
- files_position: list[str], 策略配置文件路径
- adj_type: str, 复权类型,可选值:'F', 'B', 'N',默认为 'F',前复权

"""
adj_type = kwargs.get("adj_type", "F")
files_position = kwargs.get("files_position")
tactic = czsc.CzscJsonStrategy(symbol=symbol, files_position=files_position)
kline = api.get_kline_serial(symbol, int(tactic.base_freq.strip("分钟")) * 60, data_length=10000, adj_type=adj_type)
quote = api.get_quote(symbol)
raw_bars = format_kline(kline, freq=tactic.base_freq)
if kwargs.get("sdt"):
sdt = pd.to_datetime(kwargs.get("sdt")).date()
else:
sdt = (pd.Timestamp.now() - pd.Timedelta(days=1)).date()
trader = tactic.init_trader(raw_bars, sdt=sdt)
target_pos = TargetPosTask(api, quote.underlying_symbol)

meta = {
"symbol": symbol,
"kline": kline,
"quote": quote,
"trader": trader,
"base_freq": tactic.base_freq,
"target_pos": target_pos,
}
return meta


# https://doc.shinnytech.com/tqsdk/latest/usage/mddatas.html 代码规则
symbols = [
# https://www.jiaoyixingqiu.com/shouxufei/jiaoyisuo/SHFE
Expand Down
Loading
Loading