Spaces:
Sleeping

File size: 8,467 Bytes
c68f3b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
"""
多周期因子工具模块(5分钟单一数据源架构)

底层只存储5分钟K线数据,所有高级别数据动态 resample 合成。
支持A股交易时段感知的重采样(正确处理午休11:30-13:00)。
严格防未来函数:任意时刻T,引用的高级别数据 = 上一个已完成K线。
"""

import re
import logging
from typing import Optional

import numpy as np
import pandas as pd

logger = logging.getLogger(__name__)

# ============ 常量 ============

OHLCV_COLUMNS = ("open", "high", "low", "close", "volume", "amount")

RESAMPLE_AGG = {
    "open": "first",
    "high": "max",
    "low": "min",
    "close": "last",
    "volume": "sum",
    "amount": "sum",
}

# 支持的周期后缀
VALID_SUFFIXES = {"5m", "30m", "60m", "120m", "1d", "1w", "1M"}

# 分钟级周期的 bar 分组数(每组多少根5m bar)
INTRADAY_BARS_PER_GROUP = {
    "30m": 6,     # 6 × 5m = 30m → 8组/天
    "60m": 12,    # 12 × 5m = 60m → 4组/天
    "120m": 24,   # 24 × 5m = 120m → 2组/天(上午/下午各一根)
}

# A股每天48根5m bar
BARS_PER_DAY = 48

# 后缀正则:匹配 close_1d、volume_30m、open_1w 等
_SUFFIX_PATTERN = re.compile(
    r'\b(' + '|'.join(OHLCV_COLUMNS) + r')_(5m|30m|60m|120m|1d|1w|1M)\b'
)


# ============ 后缀检测 ============

def detect_timeframe_suffixes(formula: str) -> set[str]:
    """扫描公式,返回使用的周期后缀集合(如 {"1d", "30m"})"""
    return set(m.group(2) for m in _SUFFIX_PATTERN.finditer(formula))


# ============ A股交易时段感知的 bar 编号(向量化) ============

def _assign_bar_number_vectorized(idx: pd.DatetimeIndex) -> np.ndarray:
    """
    向量化计算每根5m bar在当天的序号(0-47)。

    Baostock 5m bar 时间戳为区间结束时间:
    - 上午: 9:35(bar0), 9:40(bar1), ..., 11:30(bar23)  共24根
    - 下午: 13:05(bar24), 13:10(bar25), ..., 15:00(bar47)  共24根
    """
    minutes = idx.hour * 60 + idx.minute  # 距午夜的总分钟数

    # 上午: 9:35 = 575分, 11:30 = 690分 → bar = (minutes - 575) // 5
    # 下午: 13:05 = 785分, 15:00 = 900分 → bar = 24 + (minutes - 785) // 5
    am_mask = minutes <= 690  # <= 11:30
    bar_nums = np.where(
        am_mask,
        (minutes - 575) // 5,        # 上午: 0..23
        24 + (minutes - 785) // 5,   # 下午: 24..47
    )
    return bar_nums.astype(np.int32)


# ============ 重采样函数 ============

def resample_5m_to_target(df_5m: pd.DataFrame, target_tf: str) -> pd.DataFrame:
    """
    将5分钟OHLCV数据重采样到目标周期。

    - 30m/60m/120m: 按 bar 序号分组(A股时段感知,正确跳过午休)
    - 1d: 按日期分组
    - 1w/1M: 先合成日线,再标准 resample
    """
    if target_tf == "5m":
        return df_5m.copy()

    agg = {col: RESAMPLE_AGG[col] for col in OHLCV_COLUMNS if col in df_5m.columns}

    if target_tf in INTRADAY_BARS_PER_GROUP:
        return _resample_intraday(df_5m, INTRADAY_BARS_PER_GROUP[target_tf], agg)
    elif target_tf == "1d":
        return _resample_daily(df_5m, agg)
    elif target_tf == "1w":
        daily = _resample_daily(df_5m, agg)
        return daily.resample("W").agg(agg).dropna(subset=["close"])
    elif target_tf == "1M":
        daily = _resample_daily(df_5m, agg)
        return daily.resample("ME").agg(agg).dropna(subset=["close"])
    else:
        raise ValueError(f"不支持的目标周期: {target_tf}")


def _resample_intraday(
    df_5m: pd.DataFrame,
    bars_per_group: int,
    agg: dict,
) -> pd.DataFrame:
    """
    分钟级重采样:按 bar 序号分组,避免跨午休合成错误K线。

    例如30m (bars_per_group=6):
      group 0: bar 0-5   → 9:35~10:00  → 时间戳取10:00
      group 1: bar 6-11  → 10:05~10:30 → 时间戳取10:30
      ...
      group 3: bar 18-23 → 11:05~11:30 → 时间戳取11:30(上午最后一组)
      group 4: bar 24-29 → 13:05~13:30 → 时间戳取13:30(下午第一组)
    """
    bar_nums = _assign_bar_number_vectorized(df_5m.index)
    dates = df_5m.index.date
    group_ids = np.char.add(
        np.char.add(dates.astype(str), "_"),
        (bar_nums // bars_per_group).astype(str),
    )

    grouped = df_5m.groupby(group_ids)
    resampled = grouped.agg(agg)

    # 每组的时间戳 = 组内最后一根bar的时间(即该K线的结束时间)
    last_ts = grouped.apply(lambda x: x.index[-1])
    resampled.index = pd.DatetimeIndex(last_ts.values)
    resampled.sort_index(inplace=True)

    return resampled


def _resample_daily(df_5m: pd.DataFrame, agg: dict) -> pd.DataFrame:
    """5m → 日线:按日期分组"""
    dates = df_5m.index.date
    resampled = df_5m.groupby(dates).agg(agg)
    resampled.index = pd.DatetimeIndex(resampled.index)
    resampled.sort_index(inplace=True)
    return resampled


# ============ 防未来函数对齐 ============

def align_higher_tf_to_base(
    df_higher: pd.DataFrame,
    base_index: pd.DatetimeIndex,
) -> pd.DataFrame:
    """
    将高级别数据对齐到基准 index,严格防未来函数。

    策略: shift(1) → reindex(ffill)
    - shift(1): 每行的值变成「上一根已完成K线」的值
    - ffill: 在基准 index 上前向填充

    示例(_1d 对齐到日线 base):
      日线 shift(1) 后: 1月3日的值 = 1月2日的收盘数据

    示例(_30m 对齐到5m base):
      30m shift(1) 后: 10:30那根的值 = 10:00那根(上一个完成的30m)
      ffill到5m: 10:05~10:30的每根5m bar 都看到10:00那根的30m数据
    """
    shifted = df_higher.shift(1)
    aligned = shifted.reindex(base_index, method="ffill")
    return aligned


# ============ 多周期变量准备(主入口) ============

def prepare_multi_tf_variables(
    stock_code: str,
    df_5m: pd.DataFrame,
    suffixes: set[str],
    ic_timeframe: str = "1d",
    start_date: Optional[str] = None,
    end_date: Optional[str] = None,
) -> tuple[pd.DataFrame, dict[str, pd.Series]]:
    """
    为单只股票准备基准数据和多周期变量。

    Args:
        stock_code: 股票代码(用于日志)
        df_5m: 该股票的5分钟原始DataFrame
        suffixes: 公式中使用的周期后缀集合(如 {"1d", "30m"})
        ic_timeframe: IC计算/收益率的基准周期(决定 base_df 的粒度)
        start_date, end_date: 时间过滤

    Returns:
        (base_df, extra_variables)
        - base_df: ic_timeframe 级别的 DataFrame(提供无后缀的 close/open/... 变量)
        - extra_variables: {变量名: Series},如 {"close_1d": ..., "volume_30m": ...}
          所有 Series 对齐到 base_df 的 index
    """
    # 时间过滤(在5m粒度上)
    data = df_5m
    if start_date:
        data = data[data.index >= pd.Timestamp(start_date)]
    if end_date:
        data = data[data.index <= pd.Timestamp(end_date + " 23:59:59")]

    if len(data) < BARS_PER_DAY * 30:  # 至少30个交易日
        return pd.DataFrame(), {}

    # 重采样缓存(避免同一周期重复计算)
    _cache: dict[str, pd.DataFrame] = {"5m": data}

    def get_resampled(tf: str) -> pd.DataFrame:
        if tf not in _cache:
            _cache[tf] = resample_5m_to_target(data, tf)
        return _cache[tf]

    # 生成基准 DataFrame(ic_timeframe 级别)
    base_df = get_resampled(ic_timeframe)
    if len(base_df) < 30:
        return pd.DataFrame(), {}

    base_index = base_df.index
    extra_variables: dict[str, pd.Series] = {}

    # 为每个后缀生成对齐后的变量
    for suffix in suffixes:
        if suffix not in VALID_SUFFIXES:
            logger.warning(f"{stock_code}: 不支持的周期后缀 {suffix}")
            continue

        resampled = get_resampled(suffix)

        if suffix == ic_timeframe:
            # 同级别:shift(1) 防未来函数
            aligned = align_higher_tf_to_base(resampled, base_index)
        elif suffix == "5m" and ic_timeframe != "5m":
            # 5m 数据对齐到更粗的 base(取每组最后一根5m的shift(1)值)
            aligned = align_higher_tf_to_base(resampled, base_index)
        else:
            # 不同级别:resample + shift(1) + ffill
            aligned = align_higher_tf_to_base(resampled, base_index)

        for col in OHLCV_COLUMNS:
            if col in aligned.columns:
                extra_variables[f"{col}_{suffix}"] = aligned[col]

    return base_df, extra_variables