diff --git a/code/MANIFEST.txt b/code/MANIFEST.txt new file mode 100644 index 0000000..26ff028 --- /dev/null +++ b/code/MANIFEST.txt @@ -0,0 +1,25 @@ +# TradeAC custom-qlib-code snapshot (auto-generated) +# parent repo HEAD : fd5382caa4c4e96417a16d5a22006d9a7d625d00 +# tac-qlib/tac_qlib/contrib +# tac-qlib/tac_qlib/data +# per-file hashes (git hash-object): + 1b6298c4a5652f2e863cbdc385a1014a570fcd59 tac-qlib/tac_qlib/contrib/__init__.py + 2224424d0ff193be4f55d1b791f8fce89439c5d2 tac-qlib/tac_qlib/contrib/backtest/__init__.py + 0bf40dee440ddbded357d7bbb4efc67c62c4b084 tac-qlib/tac_qlib/contrib/backtest/tradeac_exchange.py + c76a9f17f680e74eea766eff27f7624359749ed6 tac-qlib/tac_qlib/contrib/data/__init__.py + 3bba0f1696e4ab4b3deebec3f31f269b2e713899 tac-qlib/tac_qlib/contrib/data/handler.py + b151d139a0dcde87d74b21e7c4b729176ba5c39b tac-qlib/tac_qlib/contrib/model/__init__.py + d3f051f3a8650c42fedc7b367b966f7c74fb5789 tac-qlib/tac_qlib/contrib/model/rank_ensemble.py + d03e6611338918d4aac5eea4adf26f85a3763652 tac-qlib/tac_qlib/contrib/model/rank_gbdt.py + 184f80da8edf944bad3c8fb4d4d3d189bf4f082b tac-qlib/tac_qlib/contrib/strategy/__init__.py + 896ef74ae47bcd1ed388e1e5d9c8d70c28097fe9 tac-qlib/tac_qlib/contrib/strategy/kelly_dropout.py + 9090fc6dfbd339f2f4df4b0c9b87f400ecb5c9d5 tac-qlib/tac_qlib/contrib/strategy/long_short.py + 79aaad9e39fcc740a773f4f63c512ce1086cfde0 tac-qlib/tac_qlib/contrib/strategy/optimal_stop.py + 5b9acfb4340111b204249add7760bd53c6ae03f1 tac-qlib/tac_qlib/contrib/strategy/regime_gate.py + 839abb89ad40cd516eabcfd91fe1be626b9f091f tac-qlib/tac_qlib/contrib/strategy/weekly_rebalance.py + 92e6e90eb0cd0a25142034560f27adb6b705b1a8 tac-qlib/tac_qlib/data/__init__.py + 888c039f251cdf76c793ce7ba78ff60806afd069 tac-qlib/tac_qlib/data/__pycache__/__init__.cpython-312.pyc + 26f27f9607d1a4bff09776fc58ff1c9614480d01 tac-qlib/tac_qlib/data/__pycache__/config.cpython-312.pyc + ada62e1628f7c615cc904f9a96f91c85677e16ed tac-qlib/tac_qlib/data/__pycache__/providers.cpython-312.pyc + 1953fb2a6371525db7f7b0e1c9dfbf3492d82110 tac-qlib/tac_qlib/data/config.py + 8d0644f6f0d1efb94798ed444cc73e63b643459b tac-qlib/tac_qlib/data/providers.py diff --git a/code/tac-qlib/tac_qlib/contrib/__init__.py b/code/tac-qlib/tac_qlib/contrib/__init__.py new file mode 100644 index 0000000..1b6298c --- /dev/null +++ b/code/tac-qlib/tac_qlib/contrib/__init__.py @@ -0,0 +1,11 @@ +from . import data # noqa: F401 (registers tac_qlib.contrib.data) +from . import model, strategy # noqa: F401 +from .data import TACHandler # noqa: F401 +from .model import RankICLGBModel # noqa: F401 +from .strategy import OptimalStopControl # noqa: F401 + +__all__ = [ + "TACHandler", + "RankICLGBModel", + "OptimalStopControl", +] diff --git a/code/tac-qlib/tac_qlib/contrib/backtest/__init__.py b/code/tac-qlib/tac_qlib/contrib/backtest/__init__.py new file mode 100644 index 0000000..2224424 --- /dev/null +++ b/code/tac-qlib/tac_qlib/contrib/backtest/__init__.py @@ -0,0 +1 @@ +from .tradeac_exchange import TradeACExchange diff --git a/code/tac-qlib/tac_qlib/contrib/backtest/tradeac_exchange.py b/code/tac-qlib/tac_qlib/contrib/backtest/tradeac_exchange.py new file mode 100644 index 0000000..0bf40de --- /dev/null +++ b/code/tac-qlib/tac_qlib/contrib/backtest/tradeac_exchange.py @@ -0,0 +1,432 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +""" +TradeACExchange + +A short/borrow enabled Exchange implementation built on top of qlib.backtest.exchange.Exchange. +This exchange adds simple, configurable margin logic (initial/maintenance), borrowing support for +shorts, a borrow fee, and a lightweight SMA (Special Memorandum Account) concept to emulate +behaviors similar to brokers such as IBKR and Alpaca for backtesting purposes. + +Notes / limitations +- This implementation is intentionally lightweight and conservative: it implements the + key behaviors needed for strategy/backtest experiments (allowing short selling, computing + margin requirements, performing margin-call checks, and tracking SMA-like excess equity). +- It makes some simplifying assumptions compared to real brokers (no per-product house margins, + simplified SMA bookkeeping, borrow availability modeled only by a per-symbol boolean/limit). +- The Position class in qlib.backtest.position was not changed. To support shorts we update the + position.position dict directly when necessary. This keeps integration simple but bypasses some + internal Position helpers. Use with care. + +API additions +- allow_short: enable short selling (bool) +- initial_margin_long/short: fraction required to open a position +- maintenance_margin_long/short: fraction required to keep a position +- borrow_fee_rate: periodic borrow fee applied on short value (applied at trade time as additional cost) +- borrowable: dict mapping stock_id -> bool or float (max borrowable shares). Symbols missing from + the dict follow `borrow_default` (default True = unlimited; set False for a strict whitelist) +- get_sma(position): returns SMA-like excess equity available as "buying power credit" +- check_margin_call(position): returns True if position is below maintenance requirement + +""" +from __future__ import annotations + +from typing import Any, Dict, Optional, Tuple + +import numpy as np + +from qlib.backtest.decision import Order +from qlib.backtest.exchange import Exchange +from qlib.backtest.position import BasePosition + + +class TradeACExchange(Exchange): + """An exchange that supports short selling / borrowing and basic margin rules. + + The implementation aims to be compatible with the Exchange API used by Account and + Position classes in qlib.backtest. It overrides only the minimum methods required to + enable short/borrow behavior and margin calculations. + """ + + def __init__( + self, + *args: Any, + allow_short: bool = True, + initial_margin_long: float = 0.5, + initial_margin_short: float = 0.5, + maintenance_margin_long: float = 0.25, + maintenance_margin_short: float = 0.3, + borrow_fee_rate: float = 0.0, + borrowable: Optional[Dict[str, float]] = None, + borrow_default: bool = True, + sma_enabled: bool = True, + **kwargs: Any, + ) -> None: + """Create TradeACExchange. + + Parameters mirror Exchange with additional tradeac-specific options. + """ + super().__init__(*args, **kwargs) + self.allow_short = allow_short + self.initial_margin_long = initial_margin_long + self.initial_margin_short = initial_margin_short + self.maintenance_margin_long = maintenance_margin_long + self.maintenance_margin_short = maintenance_margin_short + self.borrow_fee_rate = borrow_fee_rate + # borrowable can be a dict with per-symbol max borrowable amount, or None (unlimited) + self.borrowable = borrowable or {} + # borrow_default: policy for symbols absent from `borrowable`. + # True -> unlisted symbols are unlimited-borrowable (legacy behavior) + # False -> unlisted symbols are NOT borrowable; only listed ones can be shorted + self.borrow_default = bool(borrow_default) + # sma_enabled: whether to expose lightweight SMA calculation + self.sma_enabled = sma_enabled + + # --------------------------- Helper calculations --------------------------- + def _initial_margin_requirement(self, position: BasePosition) -> float: + """Compute the initial margin requirement (money) for the given position. + + We treat longs and shorts separately and sum their required initial margins. + """ + im_req = 0.0 + for sid in position.get_stock_list(): + amt = position.get_stock_amount(sid) + price = position.get_stock_price(sid) + val = amt * price + if val > 0: + im_req += abs(val) * self.initial_margin_long + elif val < 0: + im_req += abs(val) * self.initial_margin_short + return im_req + + def _maintenance_margin_requirement(self, position: BasePosition) -> float: + """Compute the maintenance margin requirement (money) for the given position.""" + mm_req = 0.0 + for sid in position.get_stock_list(): + amt = position.get_stock_amount(sid) + price = position.get_stock_price(sid) + val = amt * price + if val > 0: + mm_req += abs(val) * self.maintenance_margin_long + elif val < 0: + mm_req += abs(val) * self.maintenance_margin_short + return mm_req + + def get_equity(self, position: BasePosition) -> float: + """Return account equity (position value + cash).""" + return position.calculate_value() + + def get_sma(self, position: BasePosition) -> float: + """Return a simplified SMA: excess equity above initial margin requirement. + + Note: This is a synthetic/Simplified SMA used for strategy/backtest logic. Real-broker + SMA accounting (e.g. credits/debits across days) can be more complex. + """ + if not self.sma_enabled: + return 0.0 + equity = self.get_equity(position) + im_req = self._initial_margin_requirement(position) + return max(0.0, equity - im_req) + + def check_margin_call(self, position: BasePosition) -> bool: + """Return True when the account is under maintenance margin (margin call). + + Margin call condition here is simple: equity < maintenance requirement. + """ + equity = self.get_equity(position) + mm_req = self._maintenance_margin_requirement(position) + return equity < mm_req + + def get_buying_power(self, position: BasePosition) -> float: + """Estimate buying power for new long positions assuming opening margin requirement. + + Simplified: the maximum notional long value = equity / initial_margin_long. + """ + equity = self.get_equity(position) + if self.initial_margin_long <= 0: + return 0.0 + return equity / self.initial_margin_long + + # --------------------------- Order / execution overrides --------------------------- + def _borrow_headroom(self, stock_id: str, current_short: float) -> float: + """Remaining borrowable shares for `stock_id` given an already-open short of `current_short` shares. + + borrowable values: bool (True=unlimited, False=not borrowable) or numeric max shares. + Missing symbols follow `borrow_default` (True = unlimited when allow_short is enabled). + """ + if not self.allow_short: + return 0.0 + v = self.borrowable.get(stock_id, self.borrow_default) + if isinstance(v, bool): + return float("inf") if v else 0.0 + try: + limit = float(v) + except (TypeError, ValueError): + return float("inf") + return max(0.0, limit - max(current_short, 0.0)) + + def _calc_trade_info_by_order( + self, + order: Order, + position: Optional[BasePosition], + dealt_order_amount: Dict[str, float], + ) -> Tuple[float, float, float]: + """Override to allow (optionally) short selling and to apply borrow fees. + + The original Exchange implementation forbids selling more than you own. Here we allow + sell orders to create/expand short positions when allow_short is True. We still rely on + most base logic (price discovery, impact, cost calculation) by calling super(), but we + adjust the sell-side clipping behavior before delegating to the base implementation. + """ + # When selling and shorts are allowed, temporarily relax the clipping logic in the base + # implementation by monkey-patching current position check. Simpler: replicate minimal + # parts of logic from Exchange._calc_trade_info_by_order with the key change. + + # Get basic trade price & volume info using Exchange helpers + trade_price = float(self.get_deal_price(order.stock_id, order.start_time, order.end_time, direction=order.direction)) + total_trade_val = float(self.get_volume(order.stock_id, order.start_time, order.end_time) or 0.0) * trade_price + + order.factor = self.get_factor(order.stock_id, order.start_time, order.end_time) + order.deal_amount = order.amount # attempt full + + # volume clipping (same as base) + self._clip_amount_by_volume(order, dealt_order_amount) + + # approximate adjusted cost ratio based on liquidity + if not total_trade_val or np.isnan(total_trade_val) or total_trade_val <= 0: + adj_cost_ratio = self.impact_cost + else: + trade_val_tmp = order.deal_amount * trade_price + adj_cost_ratio = self.impact_cost * (trade_val_tmp / total_trade_val) ** 2 + + # Differentiate buy / sell + if order.direction == Order.SELL: + cost_ratio = self.close_cost + adj_cost_ratio + current_amount = ( + position.get_stock_amount(order.stock_id) if (position is not None and position.check_stock(order.stock_id)) else 0.0 + ) + long_held = max(current_amount, 0.0) + short_open = max(-current_amount, 0.0) + + if position is not None: + if not self.allow_short: + # clip by current holdings only + if not np.isclose(order.deal_amount, current_amount): + order.deal_amount = self.round_amount_by_trade_unit( + min(long_held, order.deal_amount), order.factor + ) + else: + # allow selling beyond holdings up to the remaining borrow limit; + # later when updating the position we create/expand a short if necessary. + max_sell = long_held + self._borrow_headroom(order.stock_id, short_open) + if order.deal_amount > max_sell and not np.isclose(order.deal_amount, max_sell): + order.deal_amount = self.round_amount_by_trade_unit(max_sell, order.factor) + + elif order.direction == Order.BUY: + cost_ratio = self.open_cost + adj_cost_ratio + if position is not None: + cash = position.get_cash() + trade_val = order.deal_amount * trade_price + if cash < max(trade_val * cost_ratio, self.min_cost): + order.deal_amount = 0 + self.logger.debug(f"Order clipped due to cost higher than cash: {order}") + elif cash < trade_val + max(trade_val * cost_ratio, self.min_cost): + max_buy_amount = self._get_buy_amount_by_cash_limit(trade_price, cash, cost_ratio) + order.deal_amount = self.round_amount_by_trade_unit(min(max_buy_amount, order.deal_amount), order.factor) + self.logger.debug(f"Order clipped due to cash limitation: {order}") + else: + order.deal_amount = self.round_amount_by_trade_unit(order.deal_amount, order.factor) + else: + order.deal_amount = self.round_amount_by_trade_unit(order.deal_amount, order.factor) + else: + raise NotImplementedError("order direction {} error".format(order.direction)) + + # compute final trade_val & trade_cost + trade_val = order.deal_amount * trade_price + # base trade_cost + trade_cost = max(trade_val * cost_ratio, self.min_cost) + # apply borrow fee only on the net-new short portion of the sell + if order.direction == Order.SELL and self.allow_short: + new_short = max(0.0, order.deal_amount - long_held) + trade_cost += new_short * trade_price * self.borrow_fee_rate + + if trade_val <= 1e-5: + trade_cost = 0 + + return trade_price, trade_val, trade_cost + + def deal_order( + self, + order: Order, + trade_account: Optional[Any] = None, + position: Optional[BasePosition] = None, + dealt_order_amount: Dict[str, float] = None, + ) -> Tuple[float, float, float]: + """Deal order and handle short position bookkeeping. + + This method mirrors Exchange.deal_order but when a position is provided and shorts are + allowed it will update the Position.position dict directly to support negative amounts. + """ + if dealt_order_amount is None: + dealt_order_amount = {} + + if not self.check_order(order): + order.deal_amount = 0.0 + self.logger.debug(f"Order failed due to trading limitation: {order}") + return 0.0, 0.0, np.nan + + if trade_account is not None and position is not None: + raise ValueError("trade_account and position can only choose one") + + pos = position or (trade_account.current_position if trade_account is not None else None) + trade_price, trade_val, trade_cost = self._calc_trade_info_by_order(order, pos, dealt_order_amount) + + if trade_val > 1e-5: + if trade_account is not None: + cp = trade_account.current_position + if not cp.skip_update(): + held = cp.check_stock(order.stock_id) + # Account-level bookkeeping (turnover/cost/returns). Mirrors + # Account._update_state_from_order except for fresh short sales, + # where no prior price exists to compute order profit from. + if order.direction == Order.SELL and not held: + trade_account.accum_info.add_turnover(trade_val) + trade_account.accum_info.add_cost(trade_cost) + trade_account.accum_info.add_return_value(0.0) + if order.direction == Order.SELL: + # sell: update account state first (stock entry may be deleted) + if held: + trade_account._update_state_from_order(order, trade_val, trade_cost, trade_price) + self._position_sell(cp, order, trade_val, trade_cost, trade_price) + else: + # buy: update position first (entry may be created), then account state + # A buy that covers a short to exactly flat deletes the entry inside + # _position_buy; re-seed a transient zero-amount stub so the + # account's order-profit lookup still finds the trade price, + # then drop it (_update_state_from_order never mutates entries). + sid = order.stock_id + had_entry = isinstance(cp.position.get(sid), dict) + self._position_buy(cp, order, trade_val, trade_cost, trade_price) + covered_to_flat = had_entry and not isinstance(cp.position.get(sid), dict) + if covered_to_flat: + cp.position[sid] = {"amount": 0.0, "price": trade_price, "weight": 0} + trade_account._update_state_from_order(order, trade_val, trade_cost, trade_price) + if covered_to_flat: + cp.position.pop(sid, None) + elif position is not None: + if order.direction == Order.BUY: + self._position_buy(position, order, trade_val, trade_cost, trade_price) + else: + self._position_sell(position, order, trade_val, trade_cost, trade_price) + return trade_val, trade_cost, trade_price + + # --------------------------- Position mutation helpers --------------------------- + def _position_buy(self, position: BasePosition, order: Order, trade_val: float, cost: float, trade_price: float) -> None: + """Handle buy order bookkeeping against a BasePosition while supporting shorts. + + Rules implemented (simplified): + - If there is an existing short (amount < 0), the buy will first cover the short. + - If covering closes the short completely, the remaining buy becomes a long + - Cash updates mimic Position._buy_stock/_sell_stock (cash decreases by trade_val+cost for buys) + """ + trade_amount = trade_val / trade_price + sid = order.stock_id + current_amount = position.get_stock_amount(sid) if position.check_stock(sid) else 0.0 + + # covering existing short + if current_amount < -1e-12: + # amount is negative -> we are short. Buying reduces the short. + new_amount = current_amount + trade_amount + if abs(new_amount) <= 1e-8: + # short fully covered exactly -> remove entry + if sid in position.position: + del position.position[sid] + elif new_amount > 0: + # short fully covered with leftover buy amount -> leftover becomes a long position + position.position[sid] = {"amount": new_amount, "price": trade_price, "weight": 0} + else: + # partially cover + position.position[sid]["amount"] = new_amount + position.position[sid]["price"] = trade_price + else: + # normal or increasing long + if sid not in position.position or not isinstance(position.position[sid], dict): + # initialize stock + position.position[sid] = {"amount": trade_amount, "price": trade_price, "weight": 0} + else: + position.position[sid]["amount"] = position.position[sid].get("amount", 0.0) + trade_amount + position.position[sid]["price"] = trade_price + + # cash effect same as Position._buy_stock + position.position["cash"] -= trade_val + cost + + def _position_sell(self, position: BasePosition, order: Order, trade_val: float, cost: float, trade_price: float) -> None: + """Handle sell order bookkeeping against a BasePosition while supporting shorts. + + Rules implemented (simplified): + - If holding enough long shares, sell will reduce/close the long position normally. + - If not holding enough long shares and shorts are allowed, the remaining sold amount will create/expand a short position. + - Cash update for sells follows Position._sell_stock logic (cash increases by trade_val - cost) + """ + trade_amount = trade_val / trade_price + sid = order.stock_id + current_amount = position.get_stock_amount(sid) if position.check_stock(sid) else 0.0 + + if current_amount > 1e-12: + # we have long shares; sell from them first + if trade_amount >= current_amount - 1e-8: + # selling all or more than holdings + # remove long position + if sid in position.position: + del position.position[sid] + # remaining sold amount becomes short if allowed + remain = trade_amount - current_amount + if remain > 1e-8: + if not self.allow_short: + # should not happen due to clipping earlier, but guard anyway + raise ValueError(f"Attempt to short {sid} while shorting disabled") + # create short entry + position.position[sid] = {"amount": -remain, "price": trade_price, "weight": 0} + else: + # partial sell + position.position[sid]["amount"] = current_amount - trade_amount + position.position[sid]["price"] = trade_price + else: + # currently flat or already short + if not self.allow_short: + raise ValueError(f"Attempt to short {sid} while shorting disabled") + # expand short + new_amount = current_amount - trade_amount + if sid not in position.position or not isinstance(position.position[sid], dict): + position.position[sid] = {"amount": new_amount, "price": trade_price, "weight": 0} + else: + position.position[sid]["amount"] = new_amount + position.position[sid]["price"] = trade_price + + # cash effect same as Position._sell_stock + new_cash = trade_val - cost + if getattr(position, "_settle_type", None) == position.ST_CASH: + position.position["cash_delay"] = position.position.get("cash_delay", 0.0) + new_cash + else: + position.position["cash"] = position.position.get("cash", 0.0) + new_cash + + # --------------------------- Borrow availability helpers --------------------------- + def is_borrowable(self, stock_id: str, amount: float) -> bool: + """Check whether the requested amount is borrowable for the given stock. + + If a borrowable dict is provided, it may contain either booleans or numeric limits (maximum borrowable shares). + Symbols absent from the dict follow `borrow_default`. + """ + if not self.allow_short: + return False + if stock_id not in self.borrowable: + return self.borrow_default + v = self.borrowable[stock_id] + if isinstance(v, bool): + return v + try: + limit = float(v) + return amount <= limit + except Exception: + return True + diff --git a/code/tac-qlib/tac_qlib/contrib/data/__init__.py b/code/tac-qlib/tac_qlib/contrib/data/__init__.py new file mode 100644 index 0000000..c76a9f1 --- /dev/null +++ b/code/tac-qlib/tac_qlib/contrib/data/__init__.py @@ -0,0 +1,3 @@ +from .handler import TACHandler + +__all__ = ["TACHandler"] diff --git a/code/tac-qlib/tac_qlib/contrib/data/handler.py b/code/tac-qlib/tac_qlib/contrib/data/handler.py new file mode 100644 index 0000000..3bba0f1 --- /dev/null +++ b/code/tac-qlib/tac_qlib/contrib/data/handler.py @@ -0,0 +1,428 @@ +"""TACHandler: a qlib DataHandlerLP that builds datasets from the TradeAC lake. + +This is the "custom DataHandler" entry point (Option B): the handler is referenced from the +workflow yaml's ``dataset.handler`` and reads OHLCV + pre-computed ta-lib features straight +from the lake parquet files through ``QLibDataLoader`` + the tac_qlib feature provider. + +The standard qlib processor pipeline (``infer_processors`` / ``learn_processors``) still runs +on top, so existing recipes such as ``DropnaLabel``, ``CSZScoreNorm`` or ``RobustZScoreNorm`` +keep working unchanged. +""" + +from __future__ import annotations + +import os +from inspect import getfullargspec +from typing import List, Optional, Tuple, Union + +import numpy as np +import pandas as pd + +from qlib.data.dataset import processor as processor_module +from qlib.data.dataset.handler import DataHandlerLP +from qlib.utils import get_callable_kwargs + +from ...data.config import ( + LakeConfig, + timeframe_for_freq, + FEATURE_FAMILIES, + NON_FEATURE_COLUMNS, +) + +DEFAULT_INFER_PROCESSORS = [ + {"class": "DropAllNaN", "kwargs": {}}, + {"class": "ProcessInf", "kwargs": {}}, + {"class": "ZScoreNorm", "kwargs": {}}, + {"class": "Fillna", "kwargs": {}}, +] +DEFAULT_LEARN_PROCESSORS = [ + {"class": "DropnaLabel"}, + {"class": "CSZScoreNorm", "kwargs": {"fields_group": "label"}}, +] + +#: always include raw OHLCV; ta-lib columns are discovered from the lake and appended. +RAW_FEATURE_FIELDS = ("$open", "$high", "$low", "$close", "$vwap", "$volume") + +DEFAULT_LABEL = "Ref($close,-2)/Ref($close,-1)-1" + + +def check_transform_proc(proc_l, fit_start_time, fit_end_time): + """Port of ``qlib.contrib.data.handler.check_transform_proc`` (inject fit window into procs).""" + new_l = [] + for p in proc_l: + if not isinstance(p, processor_module.Processor): + klass, pkwargs = get_callable_kwargs(p, processor_module) + args = getfullargspec(klass).args + if "fit_start_time" in args and "fit_end_time" in args: + assert fit_start_time is not None and fit_end_time is not None, ( + "Make sure `fit_start_time` and `fit_end_time` are not None." + ) + pkwargs.update({"fit_start_time": fit_start_time, "fit_end_time": fit_end_time}) + proc_config = {"class": klass.__name__, "kwargs": pkwargs} + if isinstance(p, dict) and "module_path" in p: + proc_config["module_path"] = p["module_path"] + new_l.append(proc_config) + else: + new_l.append(p) + return new_l + + +def get_common_feature_fields(lake_root=None, market="US", timeframe="1d") -> List[str]: + """Discover feature columns present in *every* feature file of the lake. + + Walks the `family=ta|sp` partition layout (plus any legacy flat files). + TA and SP columns are disjoint by construction, so the common set is + computed per family (columns shared by all symbol files of that family), + then the per-family results are unioned. Returns sorted field names + (without the ``$`` prefix). Empty if no features are persisted. + """ + cfg = LakeConfig(lake_root, market) + feat_dir = cfg.features_dir(timeframe) + if not feat_dir.exists(): + return [] + import pyarrow.parquet as pq + + def _family_common(fam_dir: Path) -> set: + common = None + for p in sorted(fam_dir.glob("symbol=*.parquet")): + try: + cols = set(pq.read_schema(p).names) - set(NON_FEATURE_COLUMNS) + except Exception: # pragma: no cover - skip unreadable files + continue + common = cols if common is None else (common & cols) + if not common: + break + return common or set() + + common: set = set() + # family tier: features/market=*/timeframe=*/family=*/symbol=*.parquet + for fam in FEATURE_FAMILIES: + fam_dir = feat_dir / f"family={fam}" + if fam_dir.is_dir(): + common |= _family_common(fam_dir) + # legacy flat: features/market=*/timeframe=*/symbol=*.parquet + if (feat_dir / "family=ta").exists() or (feat_dir / "family=sp").exists(): + pass # family layout already covered + else: + common |= _family_common(feat_dir) + return sorted(common) + + +class DropAllNaN(processor_module.Processor): + """Drop feature columns that are all-NaN over the fit window. + + The lake can hold fully-empty indicator columns (e.g. a ta-lib output that was NaN + from the start). Such columns carry no learnable signal and make ``ZScoreNorm.fit`` + warn on empty slices, so we drop them before any other processor runs. The drop set + is fixed on the fit window once (during ``fit``), then applied consistently to every + segment so train/valid/test keep identical feature columns. + """ + + def __init__(self, fit_start_time=None, fit_end_time=None): + self.fit_start_time = fit_start_time + self.fit_end_time = fit_end_time + self.cols_to_drop = [] + + def fit(self, df=None): + if df is None or len(df) == 0: + return self + window = df + if self.fit_start_time is not None and self.fit_end_time is not None: + try: + from qlib.data.dataset.utils import fetch_df_by_index + + window = fetch_df_by_index( + df, slice(self.fit_start_time, self.fit_end_time), level="datetime" + ) + except Exception: # pragma: no cover - defensive + window = df + if len(window) == 0: + return self + self.cols_to_drop = [c for c in window.columns if window[c].isna().all()] + return self + + def __call__(self, df): + if self.cols_to_drop: + return df.drop(columns=self.cols_to_drop, errors="ignore") + return df + + +class BenchResidual(processor_module.Processor): + """Subtract a benchmark instrument's forward return from the label, per datetime. + + Turns the training target from an absolute-return rank into a *residual* rank: + ``r_i - r_bench`` is ranked cross-sectionally by the downstream ``CSRankNorm`` / + ``CSZScoreNorm`` processors instead of ``r_i`` alone. Must be inserted BEFORE any + per-date normalization so the ranking itself is computed on residual returns + (ordering flips exactly where the benchmark trends). + + Stateless: ``fit`` is a no-op and the benchmark forward return is recomputed from + the lake parquet on first ``__call__``. Rows whose benchmark value is missing are + left untouched. Accepts ``fit_start_time``/``fit_end_time`` (ignored) so + ``check_transform_proc`` can inject the fit window uniformly. + + NOTE: under any cross-sectional normalization downstream (``CSRankNorm`` / + ``CSZScoreNorm``) this processor is a mathematical no-op: subtracting the same + per-date constant preserves ranks, and z-scoring absorbs constant shifts. Use + ``BenchBetaResidual`` for a target that actually reorders. + """ + + def __init__( + self, + benchmark="SPY", + fields_group="label", + lake_root=None, + market="US", + timeframe=None, + freq="day", + fit_start_time=None, + fit_end_time=None, + ): + self.benchmark = benchmark + self.fields_group = fields_group + self.lake_root = lake_root + self.market = market + self.timeframe = timeframe or timeframe_for_freq(freq) + self.fit_start_time = fit_start_time + self.fit_end_time = fit_end_time + self._bench_label = None + + def _load_bench_label(self): + if self._bench_label is not None: + return self._bench_label + cfg = LakeConfig(self.lake_root, self.market) + p = cfg.bar_path(self.timeframe, self.benchmark) + if not p.exists(): + raise FileNotFoundError(f"BenchResidual: benchmark bar file not found: {p}") + df = pd.read_parquet(p) + s = pd.Series(df["c"].astype(float).values, index=pd.to_datetime(df["t"])).sort_index() + s.index = s.index.normalize() + # mirror Ref($close,-6)/Ref($close,-1)-1 on the benchmark's own calendar + bench_label = s.shift(-6) / s.shift(-1) - 1 + self._bench_label = bench_label[~bench_label.index.duplicated(keep="last")] + return self._bench_label + + def fit(self, df=None): + return self + + def __call__(self, df): + bl = self._load_bench_label() + cols = processor_module.get_group_columns(df, self.fields_group) + dt = df.index.get_level_values("datetime") + aligned = bl.reindex(pd.DatetimeIndex(dt.unique())).reindex(dt) + mask = aligned.notna().values + out = df.copy() + for c in cols: + vals = df[c].values + res = vals.copy() + res[mask] = np.asarray(vals[mask], dtype=float) - aligned[mask].values + out[c] = res + return out + + +class BenchBetaResidual(processor_module.Processor): + """Residualize the label against a beta-scaled benchmark move: ``r_i - b_i * r_bench``. + + Unlike a plain constant subtraction (see ``BenchResidual``), the name-specific rolling + beta ``b_i`` makes this survive cross-sectional normalization: in up-weeks high-beta + names lose rank, in down-weeks they gain — exactly the relative structure an absolute- + return ranking hides. + + Beta is estimated from *past* data only (rolling ``window`` trading days of daily close + returns of each instrument vs the benchmark, both read up to and including ``t``), so + no lookahead enters the target. The benchmark leg uses the same horizon as the label + expression (``Ref($close,-6)/Ref($close,-1)-1`` by default via ``horizon``/``base``, + matching the yaml's 6-day label). Rows with missing beta or benchmark values keep + their raw label. + + Requires ``$close`` to be present in the feature group (it always is for TACHandler). + Stateless; accepts ``fit_start_time``/``fit_end_time`` (ignored) for uniform kwargs + injection. Must be inserted BEFORE any per-date normalization processor. + """ + + def __init__( + self, + benchmark="SPY", + fields_group="label", + lake_root=None, + market="US", + timeframe=None, + freq="day", + window=63, + horizon=6, + base=1, + feature_field="$close", + fit_start_time=None, + fit_end_time=None, + ): + self.benchmark = benchmark + self.fields_group = fields_group + self.lake_root = lake_root + self.market = market + self.timeframe = timeframe or timeframe_for_freq(freq) + self.window = int(window) + self.horizon = int(horizon) + self.base = int(base) + self.feature_field = feature_field + self.fit_start_time = fit_start_time + self.fit_end_time = fit_end_time + self._bench = None + + def _load_bench_close(self): + if self._bench is not None: + return self._bench + cfg = LakeConfig(self.lake_root, self.market) + p = cfg.bar_path(self.timeframe, self.benchmark) + if not p.exists(): + raise FileNotFoundError(f"BenchBetaResidual: benchmark bar file not found: {p}") + df = pd.read_parquet(p) + s = pd.Series(df["c"].astype(float).values, index=pd.to_datetime(df["t"])).sort_index() + s.index = s.index.normalize() + self._bench = s[~s.index.duplicated(keep="last")] + return self._bench + + def fit(self, df=None): + return self + + def __call__(self, df): + bench = self._load_bench_close() + + # benchmark forward return over the same horizon as the label expression + fwd = bench.shift(-(self.base + self.horizon - 1)) / bench.shift(-self.base) - 1 + + px_col = ("feature", self.feature_field) + if px_col not in df.columns: + raise KeyError(f"BenchBetaResidual: {self.feature_field} not found in features") + px = df[px_col].unstack("instrument").sort_index() + rets = px / px.shift(1) - 1 + bret = bench.reindex(px.index).pct_change() + + # rolling beta per instrument using data <= t (no lookahead) + cov = rets.rolling(self.window, min_periods=max(10, self.window // 2)).cov(bret) + var = bret.rolling(self.window, min_periods=max(10, self.window // 2)).var() + beta = cov.div(var, axis=0) + + contrib = beta.mul(fwd.reindex(px.index), axis=0) + cols = list(processor_module.get_group_columns(df, self.fields_group)) + out = df.copy() + for c in cols: + lab = df[c].unstack("instrument").reindex(px.index) + resid = lab - contrib.where(contrib.notna() & lab.notna(), 0.0) + new_vals = resid.stack() + new_vals.index.names = df.index.names + # residual where available, raw label otherwise (e.g. beta warm-up rows) + out[c] = new_vals.reindex(out.index).fillna(df[c]) + return out + + +class TACHandler(DataHandlerLP): + """DataHandlerLP backed by the TradeAC parquet lake. + + Parameters mirror ``Alpha158``: ``instruments``/``start_time``/``end_time``/``freq`` define + the queried window; ``feature_fields`` selects the features (default: raw OHLCV + all common + ta-lib columns found in the lake); ``label`` is a qlib expression for the target. + """ + + def __init__( + self, + instruments="all", + start_time=None, + end_time=None, + freq="day", + infer_processors=DEFAULT_INFER_PROCESSORS, + learn_processors=DEFAULT_LEARN_PROCESSORS, + fit_start_time=None, + fit_end_time=None, + process_type=DataHandlerLP.PTYPE_A, + filter_pipe=None, + feature_fields=None, + label=DEFAULT_LABEL, + lake_root=None, + market="US", + **kwargs, + ): + # default the processor fit window to the queried window (like Alpha158 without a split) + if fit_start_time is None: + fit_start_time = start_time + if fit_end_time is None: + fit_end_time = end_time + + infer_processors = check_transform_proc(infer_processors, fit_start_time, fit_end_time) + learn_processors = check_transform_proc(learn_processors, fit_start_time, fit_end_time) + + feature_fields = self._normalize_feature_fields(feature_fields, freq, lake_root, market) + if not feature_fields: + raise ValueError( + "no feature fields available for the lake; set `feature_fields` explicitly " + "(e.g. ['$close', '$rsi_14', '$sma_20'])" + ) + + label_expr, label_names = self._normalize_label(label) + + data_loader = { + "class": "QlibDataLoader", + "kwargs": { + "config": { + "feature": (feature_fields, feature_fields), + "label": (label_expr, label_names), + }, + "filter_pipe": filter_pipe, + "freq": freq, + }, + } + super().__init__( + instruments=instruments, + start_time=start_time, + end_time=end_time, + data_loader=data_loader, + infer_processors=infer_processors, + learn_processors=learn_processors, + process_type=process_type, + **kwargs, + ) + + # ------------------------------------------------------------------ config + @staticmethod + def _normalize_feature_fields(feature_fields, freq, lake_root, market) -> List[str]: + if feature_fields is None: + common = get_common_feature_fields(lake_root, market, timeframe_for_freq(freq)) + feature_fields = list(RAW_FEATURE_FIELDS) + ["$" + f for f in common if "$" + f not in RAW_FEATURE_FIELDS] + elif isinstance(feature_fields, str): + feature_fields = [f.strip() for f in feature_fields.split(",") if f.strip()] + fields = [f if f.startswith("$") else "$" + f for f in feature_fields] + # de-dup while preserving order + seen, out = set(), [] + for f in fields: + if f not in seen: + seen.add(f) + out.append(f) + return out + + @staticmethod + def _normalize_label(label) -> Tuple[List[str], List[str]]: + if isinstance(label, str): + return [label], ["LABEL0"] + if isinstance(label, (list, tuple)): + if len(label) == 2 and isinstance(label[0], str): + return [label[0]], list(label[1]) if isinstance(label[1], (list, tuple)) else [label[1]] + return list(label), ["LABEL%d" % i for i in range(len(label))] + raise TypeError(f"unsupported label config: {label!r}") + + # ------------------------------------------------------------------ utils + def get_label_config(self): + return DEFAULT_LABEL + + @staticmethod + def discover_feature_fields(lake_root=None, market="US", freq="day") -> List[str]: + return get_common_feature_fields(lake_root, market, timeframe_for_freq(freq)) + + +__all__ = ["TACHandler", "DropAllNaN", "BenchResidual", "BenchBetaResidual", "get_common_feature_fields"] + + +# Make `DropAllNaN`/`BenchResidual`/`BenchBetaResidual` resolvable by bare name from processor +# configs (e.g. the default ``infer_processors`` and workflow yamls that reference them without a +# ``module_path``), mirroring how qlib registers its own processors in ``qlib.data.dataset.processor``. +processor_module.DropAllNaN = DropAllNaN +processor_module.BenchResidual = BenchResidual +processor_module.BenchBetaResidual = BenchBetaResidual diff --git a/code/tac-qlib/tac_qlib/contrib/model/__init__.py b/code/tac-qlib/tac_qlib/contrib/model/__init__.py new file mode 100644 index 0000000..b151d13 --- /dev/null +++ b/code/tac-qlib/tac_qlib/contrib/model/__init__.py @@ -0,0 +1,4 @@ +from .rank_ensemble import RankICEnsembleLGBModel # noqa: F401 +from .rank_gbdt import RankICLGBModel, rankic_feval # noqa: F401 + +__all__ = ["RankICLGBModel", "rankic_feval", "RankICEnsembleLGBModel"] diff --git a/code/tac-qlib/tac_qlib/contrib/model/rank_ensemble.py b/code/tac-qlib/tac_qlib/contrib/model/rank_ensemble.py new file mode 100644 index 0000000..d3f051f --- /dev/null +++ b/code/tac-qlib/tac_qlib/contrib/model/rank_ensemble.py @@ -0,0 +1,189 @@ +"""Seed-ensembled LightGBM that early-stops on cross-sectional RankIC. + +``RankICEnsembleLGBModel`` wraps ``RankICLGBModel`` (per-day RankIC feval + +``metric='None'`` + ``first_metric_only`` early stopping) over a seed ensemble: +one sub-model is trained per seed with identical hyper-parameters, and +predictions are averaged across seeds. This is the model class the +``tac-rd-rank-ensemble-isolated`` reference run wires into its workflow +(``module_path: tac_qlib.contrib.model.rank_ensemble``). + +The ensemble inherits the RankIC early-stopping behaviour of the single-seed +model (valid RankIC drives the stopping iteration) while the seed averaging +stabilizes the prediction against any single seed's early-stopping path. + +Training is parallelized: the seed sub-models train in a thread pool — +``lgb.train`` is C++ and releases the GIL, so concurrent seeds do not block on +the GIL (5 seeds ~40min/5 on this box). Measured on a 6-physical-core / 12 SMT +host: the seeds scale ~2x, not linearly — the runs are memory-bandwidth bound +and each Booster caps its threads at ``cores // workers`` so 5 concurrent +boosters don't oversubscribe; larger-core hosts scale better. The qlib data +pipeline is warmed once on the calling thread (fills the handler cache), and +each worker then prepares its **own** ``lgb.Dataset`` (independent handle, so +no concurrent ``construct()`` on a shared handle — LightGBM's ``Dataset`` is +not thread-safe to build). qlib's ``R`` recorder is also not thread-safe, so +the per-seed evaluation curves are logged on the calling thread after the pool +finishes. + +Wired into a workflow yaml like: + + model: + class: RankICEnsembleLGBModel + module_path: tac_qlib.contrib.model.rank_ensemble + kwargs: + loss: mse + learning_rate: 0.02 + num_leaves: 31 + n_estimators: 3000 + num_boost_round: 3000 + early_stopping_rounds: 200 + min_data_in_leaf: 20 + lambda_l2: 0.5 + colsample_bytree: 0.8 + subsample: 0.8 + subsample_freq: 1 + reg_alpha: 0.1 + reg_lambda: 1.0 + seeds: "42,7,2026,99,123" + parallel: 5 + +Any ``**kwargs`` other than ``seeds``/``parallel`` are forwarded unchanged to +every ``RankICLGBModel`` sub-model (same params, different ``seed``). +""" + +from __future__ import annotations + +import os +from concurrent.futures import ThreadPoolExecutor +from typing import List, Optional + +import pandas as pd + +from qlib.data.dataset import DatasetH +from qlib.data.dataset.handler import DataHandlerLP + +from tac_qlib.contrib.model.rank_gbdt import RankICLGBModel + +__all__ = ["RankICEnsembleLGBModel"] + + +class RankICEnsembleLGBModel(RankICLGBModel): + """Seed ensemble of RankIC-early-stopping LightGBM models. + + Parameters + ---------- + seeds : comma-separated integers, one sub-model per seed. + parallel : number of seeds to train concurrently. ``0`` (default) = auto + (all seeds, bounded by the available cores); ``1`` = sequential. + **kwargs : forwarded to every ``RankICLGBModel`` sub-model (model + hyper-parameters). ``seeds``/``parallel`` are consumed here and not + forwarded. + """ + + def __init__(self, seeds: str = "42", parallel: int = 0, **kwargs): + self.seeds = [int(s.strip()) for s in str(seeds).split(",") if s.strip()] + if not self.seeds: + raise ValueError("seeds must contain at least one integer") + self.parallel = int(parallel) + # drop seed/parallel handling from the base kwargs, keep everything else + self._model_kwargs = dict(kwargs) + super().__init__(**self._model_kwargs) + self._models: List[RankICLGBModel] = [] + + # --------------------------------------------------------------- helpers + @staticmethod + def _cores() -> int: + try: + return max(1, len(os.sched_getaffinity(0))) + except AttributeError: + return max(1, os.cpu_count() or 1) + + def _worker_count(self) -> int: + if self.parallel > 0: + return min(len(self.seeds), self.parallel) + return min(len(self.seeds), self._cores()) + + # ------------------------------------------------------------------ fit + def fit( + self, + dataset: DatasetH, + num_boost_round: Optional[int] = None, + early_stopping_rounds: Optional[int] = None, + verbose_eval: int = 20, + evals_result=None, + reweighter=None, + **kwargs, + ): + """Train one RankICLGBModel per seed and keep them for prediction. + + The qlib data pipeline is warmed once on this thread (handler cache), + then each seed sub-model trains in a parallel worker thread on its own + ``lgb.Dataset`` (LightGBM releases the GIL in ``lgb.train``). Evals + are logged on this thread after the pool (qlib's ``R`` is not + thread-safe). + """ + n_round = num_boost_round or self.num_boost_round + n_es = early_stopping_rounds or self.early_stopping_rounds + + if len(self.seeds) == 1: + m = RankICLGBModel(seed=self.seeds[0], **self._model_kwargs) + m.fit( + dataset, + num_boost_round=n_round, + early_stopping_rounds=n_es, + verbose_eval=verbose_eval, + evals_result=evals_result, + reweighter=reweighter, + **kwargs, + ) + self._models = [m] + return + + # Warm the qlib handler cache once on this thread so the workers' + # concurrent prepare() calls only hit cached frames (no first-write race). + proto = RankICLGBModel(seed=self.seeds[0], **self._model_kwargs) + proto._prepare_data(dataset, reweighter) + + workers = self._worker_count() + # Cap per-Booster threads so concurrent seeds don't oversubscribe + # (LightGBM's num_threads=0 uses ALL cores per Booster). + per_booster = max(1, self._cores() // workers) + + def fit_seed(seed): + m = RankICLGBModel(seed=seed, **self._model_kwargs) + if workers > 1 and "num_threads" not in m.params: + m.params["num_threads"] = per_booster + ds_l = m._prepare_data(dataset, reweighter) + booster, evals, names = m._train_from_datasets( + ds_l, + num_boost_round=n_round, + early_stopping_rounds=n_es, + verbose_eval=verbose_eval, + **kwargs, + ) + m.model = booster + return m, evals, names + + with ThreadPoolExecutor(max_workers=workers) as ex: + results = list(ex.map(fit_seed, self.seeds)) + + self._models = [m for m, _, _ in results] + + # Merge + log evals on the main thread (qlib's R is not thread-safe). + if evals_result is not None: + for m, evals, names in results: + for k in names: + for key, val in evals.get(k, {}).items(): + evals_result.setdefault(f"{k}.seed{m.params['seed']}", {})[key] = val + for m, evals, names in results: + self._log_evals(evals, names, prefix=f"seed{m.params['seed']}.") + + # -------------------------------------------------------------- predict + def predict(self, dataset: DatasetH, segment="test") -> pd.Series: + """Average the per-seed predictions over the given segment.""" + if not self._models: + raise ValueError("model is not fitted yet!") + preds = [m.predict(dataset, segment=segment) for m in self._models] + if len(preds) == 1: + return preds[0] + frame = pd.concat(preds, axis=1) + return frame.mean(axis=1) diff --git a/code/tac-qlib/tac_qlib/contrib/model/rank_gbdt.py b/code/tac-qlib/tac_qlib/contrib/model/rank_gbdt.py new file mode 100644 index 0000000..d03e661 --- /dev/null +++ b/code/tac-qlib/tac_qlib/contrib/model/rank_gbdt.py @@ -0,0 +1,238 @@ +"""LGBModel variant that early-stops on cross-sectional RankIC instead of l2. + +Standard qlib ``LGBModel`` early-stops on the regression loss (mse). For +cross-sectional alpha signals the quantity we actually care about is the per-day +rank correlation (Rank IC), which mse early-stopping does not optimize for. +Experiments on the 50-ETF lake (SP-5d 55-feature panel) show that early-stopping +on a custom RankIC feval lifts RankIC 0.047 -> 0.075 vs. the mse-stopped model. + +This class reuses ``LGBModel``'s data preparation but: + + - tags each ``lgb.Dataset`` with per-day query ``group`` sizes so a ranking + metric can be computed per trading day; + - injects a custom ``feval`` (mean per-day Spearman of pred vs label) into + ``lgb.train``; early stopping then selects the iteration that maximizes + RankIC on the valid set; + - forces ``metric='None'`` + ``first_metric_only=True`` so early-stopping + tracks RankIC only (not the regression loss). + +Wired into a workflow yaml like: + + model: + class: RankICLGBModel + module_path: tac_qlib.contrib.model.rank_gbdt + kwargs: + loss: mse + learning_rate: 0.03 + num_leaves: 31 + n_estimators: 500 + ... + +The rank feval is used for early-stopping selection only; the objective stays +the configured loss (default mse). Set ``rank_eval=False`` to fall back to the +plain LGBModel behaviour (early-stop on the loss). + +Generic: works for any cross-sectional panel whose qlib dataset index has a +``datetime`` level (each level value = one query group). The per-day groups are +derived automatically, so no universe-specific configuration is needed. +""" + +from __future__ import annotations + +from typing import List, Optional, Tuple + +import numpy as np +import pandas as pd +import lightgbm as lgb + +from qlib.data.dataset import DatasetH +from qlib.data.dataset.handler import DataHandlerLP +from qlib.contrib.model.gbdt import LGBModel +from qlib.workflow import R + +__all__ = ["RankICLGBModel", "rankic_feval"] + + +def _group_averaged_rank(values: np.ndarray, gid: np.ndarray, offs: np.ndarray) -> np.ndarray: + """Averaged (tie-corrected) rank of ``values`` within each group, vectorized. + + ``gid`` maps each row to its group id; ``offs`` holds the cumulative row + offsets so that group ``i`` occupies rows ``[offs[i], offs[i+1])``. Returns + the same result as ``pandas.Series.rank(method='average')`` applied per + group, but in one pass (``np.lexsort`` is the only non-linear step). + """ + n = len(values) + order = np.lexsort((values, gid)) + ord_rank = np.empty(n, dtype=np.float64) + ord_rank[order] = np.arange(n, dtype=np.float64) - offs[gid[order]] + 1.0 + sg = gid[order] + sv = values[order] + newblock = np.empty(n, dtype=bool) + newblock[0] = True + newblock[1:] = (sg[1:] != sg[:-1]) | (sv[1:] != sv[:-1]) + blockid = np.cumsum(newblock) - 1 + block_mean = np.bincount(blockid, weights=ord_rank[order]) / np.bincount(blockid) + out = np.empty(n) + out[order] = block_mean[blockid] + return out + + +def _per_day_spearman(preds: np.ndarray, labels: np.ndarray, group: np.ndarray) -> float: + """Mean per-day Spearman rank correlation of preds vs labels. + + ``group`` holds the number of rows of each trading day (query group), in + order. Days with <3 valid rows or a constant pred/label are skipped. + + Vectorized: per-day Spearman == Pearson of the per-day rank transforms, + and the Pearson moments (``sum``, ``sum`` of products/squares) aggregate + over each day with ``np.bincount``. Runs ~10x faster than the per-day + ``pd.Series.rank()`` loop that preceded it — this feval is invoked on the + train and valid panels every boosting round, per seed. + """ + if group is None or len(group) == 0: + return 0.0 + offs = np.concatenate([[0], np.cumsum(group.astype(int))]) + gid = np.repeat(np.arange(len(group)), group.astype(int)) + rp = _group_averaged_rank(preds, gid, offs) + rl = _group_averaged_rank(labels, gid, offs) + n_g = group.astype(float) + s_p = np.bincount(gid, weights=rp) + s_l = np.bincount(gid, weights=rl) + s_pl = np.bincount(gid, weights=rp * rl) + s_pp = np.bincount(gid, weights=rp * rp) + s_ll = np.bincount(gid, weights=rl * rl) + cov = n_g * s_pl - s_p * s_l + var_p = n_g * s_pp - s_p ** 2 + var_l = n_g * s_ll - s_l ** 2 + denom = np.sqrt(var_p * var_l) + valid = (n_g >= 3) & (denom > 0) + corr = np.where(valid, cov / np.where(denom == 0, 1, denom), 0.0) + return float(corr[valid].mean()) if valid.any() else 0.0 + + +def rankic_feval(preds, dataset): + """LightGBM feval: mean RankIC (higher is better in lgb convention).""" + labels = dataset.get_label() + group = dataset.get_group() + ric = _per_day_spearman(preds, labels, group) + return "rankic", ric, True # (name, value, higher_is_better) + + +class RankICLGBModel(LGBModel): + """LGBModel that early-stops on per-day RankIC via a custom feval.""" + + def __init__(self, rank_eval: bool = True, **kwargs): + super().__init__(**kwargs) + self.rank_eval = rank_eval + + def _prepare_data(self, dataset: DatasetH, reweighter=None) -> List[Tuple[lgb.Dataset, str]]: + ds_l = [] + assert "train" in dataset.segments + for key in ["train", "valid"]: + if key in dataset.segments: + df = dataset.prepare(key, col_set=["feature", "label"], data_key=DataHandlerLP.DK_L) + if df.empty: + raise ValueError("Empty data from dataset, please check your dataset config.") + x, y = df["feature"], df["label"] + if y.values.ndim == 2 and y.values.shape[1] == 1: + y = np.squeeze(y.values) + else: + raise ValueError("LightGBM doesn't support multi-label training") + + if reweighter is None: + w = None + elif hasattr(reweighter, "reweight"): + w = reweighter.reweight(df) + else: + raise ValueError("Unsupported reweighter type.") + + # per-day query groups: each trading day is one group + if self.rank_eval and isinstance(df.index, pd.MultiIndex) and "datetime" in df.index.names: + group = df.groupby(level="datetime").size().to_numpy(dtype=np.int32) + else: + group = None + + d = lgb.Dataset(x.values, label=y, weight=w, group=group, free_raw_data=False) + ds_l.append((d, key)) + return ds_l + + def _train_from_datasets( + self, + ds_l: List[Tuple[lgb.Dataset, str]], + num_boost_round: Optional[int] = None, + early_stopping_rounds: Optional[int] = None, + verbose_eval: int = 20, + evals_result=None, + **kwargs, + ) -> Tuple[lgb.Booster, dict, List[str]]: + """Train a Booster from already-prepared ``lgb.Dataset`` objects. + + Pure training — no ``R.log_metrics`` — so it can be called from worker + threads (qlib's ``R`` recorder is not thread-safe; the caller decides + when/where to log). Returns ``(booster, evals_result, segment_names)``. + """ + if evals_result is None: + evals_result = {} + ds, names = list(zip(*ds_l)) + + callbacks = [ + lgb.early_stopping( + self.early_stopping_rounds if early_stopping_rounds is None else early_stopping_rounds + ), + lgb.log_evaluation(period=verbose_eval), + lgb.record_evaluation(evals_result), + ] + if self.rank_eval: + # early-stopping must be driven ONLY by the RankIC feval, not l2. + # metric='None' suppresses the default l2 metric; first_metric_only + # makes early_stopping track the single remaining (rankic) metric. + self.params["metric"] = "None" + self.params["first_metric_only"] = True + feval = rankic_feval + else: + self.params.pop("metric", None) + self.params.pop("first_metric_only", None) + feval = None + + booster = lgb.train( + self.params, + ds[0], + num_boost_round=self.num_boost_round if num_boost_round is None else num_boost_round, + valid_sets=ds, + valid_names=names, + feval=feval, + callbacks=callbacks, + **kwargs, + ) + return booster, evals_result, list(names) + + def _log_evals(self, evals_result, names: List[str], prefix: str = "") -> None: + """Log recorded evaluation curves to qlib's active recorder.""" + for k in names: + for key, val in evals_result.get(k, {}).items(): + name = f"{prefix}{key}.{k}" + for epoch, m in enumerate(val): + R.log_metrics(**{name.replace("@", "_"): m}, step=epoch) + + def fit( + self, + dataset: DatasetH, + num_boost_round: Optional[int] = None, + early_stopping_rounds: Optional[int] = None, + verbose_eval: int = 20, + evals_result=None, + reweighter=None, + **kwargs, + ): + if evals_result is None: + evals_result = {} + ds_l = self._prepare_data(dataset, reweighter) + self.model, evals_result, names = self._train_from_datasets( + ds_l, + num_boost_round=num_boost_round, + early_stopping_rounds=early_stopping_rounds, + verbose_eval=verbose_eval, + evals_result=evals_result, + **kwargs, + ) + self._log_evals(evals_result, names) diff --git a/code/tac-qlib/tac_qlib/contrib/strategy/__init__.py b/code/tac-qlib/tac_qlib/contrib/strategy/__init__.py new file mode 100644 index 0000000..184f80d --- /dev/null +++ b/code/tac-qlib/tac_qlib/contrib/strategy/__init__.py @@ -0,0 +1,4 @@ +from .optimal_stop import OptimalStopControl # noqa: F401 +from .long_short import LongShortTopkStrategy # noqa: F401 + +__all__ = ["OptimalStopControl", "LongShortTopkStrategy"] diff --git a/code/tac-qlib/tac_qlib/contrib/strategy/kelly_dropout.py b/code/tac-qlib/tac_qlib/contrib/strategy/kelly_dropout.py new file mode 100644 index 0000000..896ef74 --- /dev/null +++ b/code/tac-qlib/tac_qlib/contrib/strategy/kelly_dropout.py @@ -0,0 +1,201 @@ +"""Fractional-Kelly dropout strategy for cross-sectional signals. + +Sizing rule variant of ``qlib.contrib.strategy.signal_strategy.TopkDropoutStrategy``: +the topk/n_drop SELECTION is identical to the reference, but the buy size is +proportional to the score MAGNITUDE (edge) instead of equal-weight, capped at a +fraction ``cap_frac`` of the equal-weight notional so a single name cannot +over-concentrate the book. + +``cap_frac`` is the fraction of the equal-weight per-name notional that a top +signal can deploy at most (e.g. 0.5 = at most half the equal-weight size). +Names whose score is below the median of the buy set get a proportionally +smaller slice; the residual stays in cash (that is the point of the rule: +throw away less edge per name, deploy less capital when conviction is low). +""" + +from __future__ import annotations + +from typing import List + +import numpy as np +import pandas as pd + +from qlib.backtest import Order +from qlib.backtest.decision import OrderDir, TradeDecisionWO +from qlib.contrib.strategy.signal_strategy import TopkDropoutStrategy + +__all__ = ["FractionalKellyDropoutStrategy"] + +DEFAULT_CAP_FRAC = 0.5 + + +class FractionalKellyDropoutStrategy(TopkDropoutStrategy): + """TopkDropout selection with score-magnitude (fractional-Kelly) sizing. + + Parameters + ---------- + topk, n_drop, method_sell, method_buy, hold_thresh, only_tradable, + forbid_all_trade_at_limit : same as ``TopkDropoutStrategy``. + cap_frac : max buy notional as a fraction of the equal-weight notional. + """ + + def __init__(self, *, topk, n_drop, cap_frac: float = DEFAULT_CAP_FRAC, **kwargs): + super().__init__(topk=topk, n_drop=n_drop, **kwargs) + self.cap_frac = cap_frac + + def generate_trade_decision(self, execute_result=None): + import copy + + trade_step = self.trade_calendar.get_trade_step() + trade_start_time, trade_end_time = self.trade_calendar.get_step_time(trade_step) + pred_start_time, pred_end_time = self.trade_calendar.get_step_time(trade_step, shift=1) + pred_score = self.signal.get_signal(start_time=pred_start_time, end_time=pred_end_time) + if isinstance(pred_score, pd.DataFrame): + pred_score = pred_score.iloc[:, 0] + if pred_score is None: + return TradeDecisionWO([], self) + + if self.only_tradable: + + def get_first_n(li, n, reverse=False): + cur_n = 0 + res = [] + for si in reversed(li) if reverse else li: + if self.trade_exchange.is_stock_tradable( + stock_id=si, start_time=trade_start_time, end_time=trade_end_time + ): + res.append(si) + cur_n += 1 + if cur_n >= n: + break + return res[::-1] if reverse else res + + def get_last_n(li, n): + return get_first_n(li, n, reverse=True) + + def filter_stock(li): + return [ + si + for si in li + if self.trade_exchange.is_stock_tradable( + stock_id=si, start_time=trade_start_time, end_time=trade_end_time + ) + ] + + else: + + def get_first_n(li, n): + return list(li)[:n] + + def get_last_n(li, n): + return list(li)[-n:] + + def filter_stock(li): + return li + + current_temp: "object" = copy.deepcopy(self.trade_position) + sell_order_list: List[Order] = [] + buy_order_list: List[Order] = [] + cash = current_temp.get_cash() + current_stock_list = current_temp.get_stock_list() + last = pred_score.reindex(current_stock_list).sort_values(ascending=False).index + + if self.method_buy == "top": + today = get_first_n( + pred_score[~pred_score.index.isin(last)].sort_values(ascending=False).index, + self.n_drop + self.topk - len(last), + ) + elif self.method_buy == "random": + topk_candi = get_first_n(pred_score.sort_values(ascending=False).index, self.topk) + candi = list(filter(lambda x: x not in last, topk_candi)) + n = self.n_drop + self.topk - len(last) + try: + today = np.random.choice(candi, n, replace=False) + except ValueError: + today = candi + else: + raise NotImplementedError(f"This type of input is not supported") + + comb = pred_score.reindex(last.union(pd.Index(today))).sort_values(ascending=False).index + + if self.method_sell == "bottom": + sell = last[last.isin(get_last_n(comb, self.n_drop))] + elif self.method_sell == "random": + candi = filter_stock(last) + try: + sell = pd.Index(np.random.choice(candi, self.n_drop, replace=False) if len(last) else []) + except ValueError: + sell = candi + else: + raise NotImplementedError(f"This type of input is not supported") + + buy = today[: len(sell) + self.topk - len(last)] + for code in current_stock_list: + if not self.trade_exchange.is_stock_tradable( + stock_id=code, + start_time=trade_start_time, + end_time=trade_end_time, + direction=None if self.forbid_all_trade_at_limit else OrderDir.SELL, + ): + continue + if code in sell: + time_per_step = self.trade_calendar.get_freq() + if current_temp.get_stock_count(code, bar=time_per_step) < self.hold_thresh: + continue + sell_amount = current_temp.get_stock_amount(code=code) + sell_order = Order( + stock_id=code, + amount=sell_amount, + start_time=trade_start_time, + end_time=trade_end_time, + direction=Order.SELL, + ) + if self.trade_exchange.check_order(sell_order): + sell_order_list.append(sell_order) + trade_val, trade_cost, trade_price = self.trade_exchange.deal_order( + sell_order, position=current_temp + ) + cash += trade_val - trade_cost + + if len(buy) == 0: + return TradeDecisionWO(sell_order_list, self) + + # ---- fractional-Kelly sizing -------------------------------------- + # equal-weight notional (reference baseline) + eq_notional = cash * self.risk_degree / len(buy) + buy_scores = pred_score.reindex(buy).astype(float) + lo, hi = buy_scores.min(), buy_scores.max() + if hi == lo: + w = pd.Series(1.0, index=buy_scores.index) + else: + w = (buy_scores - lo) / (hi - lo) # [0,1] edge magnitude + w = w.clip(lower=0.0) + w_max = w.max() + w = w / w_max if w_max > 0 else w # max == 1.0 + for code in buy: + if not self.trade_exchange.is_stock_tradable( + stock_id=code, + start_time=trade_start_time, + end_time=trade_end_time, + direction=None if self.forbid_all_trade_at_limit else OrderDir.BUY, + ): + continue + buy_price = self.trade_exchange.get_deal_price( + stock_id=code, start_time=trade_start_time, end_time=trade_end_time, direction=OrderDir.BUY + ) + notional = eq_notional * min(self.cap_frac, float(w.get(code, 0.0))) + buy_amount = notional / buy_price + factor = self.trade_exchange.get_factor( + stock_id=code, start_time=trade_start_time, end_time=trade_end_time + ) + buy_amount = self.trade_exchange.round_amount_by_trade_unit(buy_amount, factor) + buy_order = Order( + stock_id=code, + amount=buy_amount, + start_time=trade_start_time, + end_time=trade_end_time, + direction=Order.BUY, + ) + buy_order_list.append(buy_order) + + return TradeDecisionWO(sell_order_list + buy_order_list, self) \ No newline at end of file diff --git a/code/tac-qlib/tac_qlib/contrib/strategy/long_short.py b/code/tac-qlib/tac_qlib/contrib/strategy/long_short.py new file mode 100644 index 0000000..9090fc6 --- /dev/null +++ b/code/tac-qlib/tac_qlib/contrib/strategy/long_short.py @@ -0,0 +1,361 @@ +"""Long-short Top-K strategy for cross-sectional signals. + +Each day the strategy ranks the cross-section by prediction score and rebalances +to an equal-weight two-sided book: the ``topk`` highest-ranked names go long and +the ``k_short`` lowest-ranked names go short. Net-new shorts are opened by +selling beyond current holdings, which requires a short-aware exchange such as +``tac_qlib.contrib.backtest.tradeac_exchange.TradeACExchange`` with +``allow_short=True`` (borrow limits, margin requirements and borrow fees are +enforced there, not here). + +Sizing deploys ``equity * risk_degree`` as gross notional split evenly across +all long and short legs, so the book is approximately market neutral. +``allow_short=False`` disables the short side entirely (long-only ``topk``). + +Short eligibility can be restricted further, with static or dynamic gates: +``short_whitelist`` limits shorts to an explicit symbol set; ``short_vol_top_pct`` +requires a candidate's trailing realized volatility to rank in the top fraction +of that day's cross-section; ``short_max_mom`` (falling-knife filter) only +allows shorting names whose own trailing momentum is at/below a threshold; +``short_regime_sma`` disables shorts entirely while the benchmark trades above +its moving average (risk-on). Borrow availability itself is enforced by the +exchange (``borrowable`` whitelist / per-symbol caps via ``TradeACExchange``). + +Wired into qrun workflows like any ``BaseStrategy`` (see ``PortAnaRecord`` +config). Mirrors the API usage of qlib's ``TopkDropoutStrategy``: ``Order`` / +``OrderDir`` from ``qlib.backtest.decision``, ``trade_calendar`` / +``trade_exchange`` / ``trade_position`` injected by the backtest executor. +""" + +from __future__ import annotations + +import copy +from typing import Dict, List, Optional + +import pandas as pd + +from qlib.backtest import Order +from qlib.backtest.decision import OrderDir, TradeDecisionWO +from qlib.contrib.strategy.signal_strategy import BaseSignalStrategy +from qlib.log import get_module_logger + +__all__ = ["LongShortTopkStrategy"] + + +class LongShortTopkStrategy(BaseSignalStrategy): + """Equal-weight long-short Top-K strategy over a cross-sectional signal. + + Parameters + ---------- + topk : number of long legs (highest-ranked names). + k_short : number of short legs (lowest-ranked names). + hold_thresh : minimum holding days before a leg may be closed/reduced. + only_tradable : only select candidates tradable on the trade date. + rebalance_tol : skip rebalances smaller than this fraction of a leg's + target notional (turnover control). + allow_short : enable/disable the short side. With ``False`` the bottom-ranked + legs are dropped and the book is long-only ``topk``; pair with + ``allow_short=False`` on the exchange for a fully borrow-free run. + Legacy alias ``enable_short`` is accepted. + short_whitelist : optional list of symbols eligible for shorting; candidates + outside the list are skipped (``None`` = all names eligible). + short_vol_window : trailing window (trading days) for realized-vol estimation. + short_vol_top_pct : if set, a short candidate's trailing realized volatility + must rank at or above this percentile of that day's cross-section + (e.g. ``0.5`` = only the more volatile half may be shorted). Candidates + without measurable vol are never shorted. + short_mom_window : trailing window (trading days) for the candidate momentum + used by the falling-knife gate. + short_max_mom : if set, a candidate's trailing ``short_mom_window``-day return + must be <= this value to be shortable (e.g. ``0.0`` = only short names + that are actually falling). Candidates without measurable momentum are + never shorted. + short_regime_symbol : benchmark symbol for the regime gate (default SPY). + short_regime_sma : if set, shorts are only allowed on days where the regime + symbol's last close (strictly before the execution bar) is BELOW its + ``short_regime_sma``-day moving average — i.e. shorts are disabled in + risk-on regimes and enabled in drawdowns. + """ + + def __init__( + self, + *, + signal=None, + topk: int = 4, + k_short: int = 2, + hold_thresh: int = 1, + only_tradable: bool = True, + rebalance_tol: float = 0.05, + allow_short: Optional[bool] = None, + enable_short: Optional[bool] = None, + short_whitelist: Optional[List[str]] = None, + short_vol_window: int = 20, + short_vol_top_pct: Optional[float] = None, + short_mom_window: int = 20, + short_max_mom: Optional[float] = None, + short_regime_symbol: str = "SPY", + short_regime_sma: Optional[int] = None, + risk_degree: float = 0.95, + trade_exchange=None, + level_infra=None, + common_infra=None, + **kwargs, + ): + super().__init__( + signal=signal, + risk_degree=risk_degree, + trade_exchange=trade_exchange, + level_infra=level_infra, + common_infra=common_infra, + **kwargs, + ) + if allow_short is None: + allow_short = True if enable_short is None else bool(enable_short) + self.allow_short = bool(allow_short) + self.topk = topk + self.k_short = k_short + self.hold_thresh = hold_thresh + self.only_tradable = only_tradable + self.rebalance_tol = rebalance_tol + self.short_whitelist = set(short_whitelist) if short_whitelist is not None else None + if not 0 < float(short_vol_window) <= 1000: + raise ValueError(f"short_vol_window must be in (0, 1000], got {short_vol_window}") + self.short_vol_window = int(short_vol_window) + if short_vol_top_pct is not None and not 0.0 < float(short_vol_top_pct) <= 1.0: + raise ValueError(f"short_vol_top_pct must be in (0, 1], got {short_vol_top_pct}") + self.short_vol_top_pct = None if short_vol_top_pct is None else float(short_vol_top_pct) + if not 0 < float(short_mom_window) <= 1000: + raise ValueError(f"short_mom_window must be in (0, 1000], got {short_mom_window}") + self.short_mom_window = int(short_mom_window) + self.short_max_mom = None if short_max_mom is None else float(short_max_mom) + self.short_regime_symbol = str(short_regime_symbol) + if short_regime_sma is not None and not 1 < int(short_regime_sma) <= 1000: + raise ValueError(f"short_regime_sma must be in (1, 1000], got {short_regime_sma}") + self.short_regime_sma = None if short_regime_sma is None else int(short_regime_sma) + # per-day caches (keyed by trade date) + self._vol_cache_key: Optional[str] = None + self._vol_cache_val: Dict[str, Dict[str, float]] = {} + self._regime_cache: Dict[str, bool] = {} + + # ------------------------------------------------------------------ utils + def _is_tradable(self, code, start, end) -> bool: + if not self.only_tradable: + return True + try: + return self.trade_exchange.is_stock_tradable(stock_id=code, start_time=start, end_time=end) + except TypeError: + return True + + def _mark_price(self, code, start, end) -> Optional[float]: + try: + px = self.trade_exchange.get_deal_price( + stock_id=code, start_time=start, end_time=end, direction=OrderDir.BUY + ) + except (KeyError, ValueError): + return None + if px is None or px != px or px <= 0: + return None + return float(px) + + def _day_stats(self, codes: List[str], trade_start) -> Dict[str, Dict[str, float]]: + """Per-day cross-sectional stats used by the dynamic short gates. + + For each code, returns ``{"vol_rank": r}`` (percentile of trailing + realized vol over ``short_vol_window`` bars across that day's + cross-section) when the vol gate is on, and ``{"mom": m}`` (trailing + ``short_mom_window``-bar return) when the falling-knife gate is on. + All series end on the last bar strictly BEFORE the execution bar (no + lookahead). Codes without measurable data are simply absent — such + candidates are never shorted (fail-closed). + """ + if self.short_vol_top_pct is None and self.short_max_mom is None: + return {} + key = str(pd.Timestamp(trade_start)) + if self._vol_cache_key == key: + return self._vol_cache_val + out: Dict[str, Dict[str, float]] = {} + try: + from qlib.data import D + + end = pd.Timestamp(trade_start) + buf = max(self.short_vol_window, self.short_mom_window) * 3 + 30 + df = D.features( + sorted(codes), + ["$close"], + start_time=end - pd.Timedelta(days=buf), + end_time=end - pd.Timedelta(days=1), + ) + close = df["$close"].unstack(level="instrument") if isinstance(df.index, pd.MultiIndex) else df["$close"] + if self.short_vol_top_pct is not None: + vol = close.pct_change().rolling(self.short_vol_window).std().iloc[-1] + for code, rank in vol.rank(pct=True).dropna().items(): + out.setdefault(str(code), {})["vol_rank"] = float(rank) + if self.short_max_mom is not None: + w = min(self.short_mom_window, len(close) - 1) + mom = close.iloc[-1] / close.iloc[-(w + 1)] - 1 + for code, m in mom.items(): + if m == m: + out.setdefault(str(code), {})["mom"] = float(m) + except Exception as e: # noqa: BLE001 - degrade to fail-closed (no shorts) + get_module_logger(self.__class__.__name__).warning( + f"short gates unavailable ({type(e).__name__}: {e}); no shorts this step" + ) + self._vol_cache_key, self._vol_cache_val = key, out + return out + + def _regime_ok(self, trade_start) -> bool: + """True when shorting is allowed by the benchmark-regime gate. + + With ``short_regime_sma`` set, shorts are permitted only while the + regime symbol's last close strictly before the execution bar sits below + its moving average (risk-off). Data failure fails closed (no shorts). + """ + if self.short_regime_sma is None: + return True + key = str(pd.Timestamp(trade_start)) + cached = self._regime_cache.get(key) + if cached is not None: + return cached + ok = False + try: + from qlib.data import D + + end = pd.Timestamp(trade_start) + df = D.features( + [self.short_regime_symbol], + ["$close"], + start_time=end - pd.Timedelta(days=int(self.short_regime_sma * 3 + 30)), + end_time=end - pd.Timedelta(days=1), + ) + s = df["$close"] + if isinstance(s.index, pd.MultiIndex): + s = s.droplevel("instrument") + sma = s.rolling(self.short_regime_sma).mean().iloc[-1] + px = s.iloc[-1] + ok = bool(px < sma) + except Exception as e: # noqa: BLE001 - degrade to fail-closed (no shorts) + get_module_logger(self.__class__.__name__).warning( + f"regime gate unavailable ({type(e).__name__}: {e}); no shorts this step" + ) + self._regime_cache[key] = ok + return ok + + # ------------------------------------------------------------- decision + def generate_trade_decision(self, execute_result=None): + trade_step = self.trade_calendar.get_trade_step() + trade_start, trade_end = self.trade_calendar.get_step_time(trade_step) + pred_start, pred_end = self.trade_calendar.get_step_time(trade_step, shift=1) + pred_score = self.signal.get_signal(start_time=pred_start, end_time=pred_end) + if isinstance(pred_score, pd.DataFrame): + pred_score = pred_score.iloc[:, 0] + if pred_score is None or len(pred_score) == 0: + return TradeDecisionWO([], self) + pred_score = pred_score.dropna() + if pred_score.empty: + return TradeDecisionWO([], self) + + time_per_step = self.trade_calendar.get_freq() + current_temp = copy.deepcopy(self.trade_position) + + # ---- signed current holdings --------------------------------------- + cur_amount: Dict[str, float] = {} + for code in current_temp.get_stock_list(): + amt = float(current_temp.get_stock_amount(code)) + if abs(amt) > 1e-6: + cur_amount[code] = amt + + # ---- targets: top-k long, bottom-k_short short ---------------------- + ranked = list(pred_score.sort_values(ascending=False).index) + longs: List[str] = [] + for code in ranked: + if len(longs) >= self.topk: + break + if self._is_tradable(code, trade_start, trade_end): + longs.append(code) + shorts: List[str] = [] + if self.allow_short and self._regime_ok(trade_start): + stats = self._day_stats(list(ranked), trade_start) + for code in reversed(ranked): + if len(shorts) >= self.k_short: + break + if code in longs: + continue + if not self._is_tradable(code, trade_start, trade_end): + continue + if self.short_whitelist is not None and code not in self.short_whitelist: + continue + st = stats.get(code) + if self.short_vol_top_pct is not None: + rank = None if st is None else st.get("vol_rank") + if rank is None or rank < self.short_vol_top_pct: + continue + if self.short_max_mom is not None: + mom = None if st is None else st.get("mom") + if mom is None or mom > self.short_max_mom: + continue + shorts.append(code) + + # ---- marks & equity -------------------------------------------------- + marks: Dict[str, float] = {} + for code in set(cur_amount) | set(longs) | set(shorts): + px = self._mark_price(code, trade_start, trade_end) + if px is not None: + marks[code] = px + + equity = current_temp.get_cash() + for code, amt in cur_amount.items(): + if code in marks: + equity += amt * marks[code] + if equity <= 0: + return TradeDecisionWO([], self) + + n_legs = len([c for c in longs if c in marks]) + len([c for c in shorts if c in marks]) + if n_legs == 0: + return TradeDecisionWO([], self) + per_leg = equity * self.risk_degree / n_legs + + target_signed: Dict[str, float] = {} + for code in longs: + if code in marks: + target_signed[code] = per_leg / marks[code] + for code in shorts: + if code in marks: + target_signed[code] = -(per_leg / marks[code]) + + # ---- order generation ------------------------------------------------- + sell_orders: List[Order] = [] + buy_orders: List[Order] = [] + + def submit(code: str, amount: float, direction: int) -> None: + factor = self.trade_exchange.get_factor(stock_id=code, start_time=trade_start, end_time=trade_end) + amount = self.trade_exchange.round_amount_by_trade_unit(amount, factor) + if amount <= 1e-6: + return + o = Order(stock_id=code, amount=amount, start_time=trade_start, end_time=trade_end, direction=direction) + if self.trade_exchange.check_order(o): + (buy_orders if direction == Order.BUY else sell_orders).append(o) + + # close holdings that are no longer targeted (frees cash / unwinds shorts) + for code, amt in cur_amount.items(): + if code in target_signed: + continue + if marks.get(code) is None: + continue + if current_temp.get_stock_count(code, bar=time_per_step) < self.hold_thresh: + continue + submit(code, abs(amt), Order.SELL if amt > 0 else Order.BUY) + + # rebalance targeted legs toward their signed target quantity + for code, tgt in target_signed.items(): + cur = cur_amount.get(code, 0.0) + delta = tgt - cur + if abs(delta * marks[code]) < max(self.rebalance_tol * per_leg, 1.0): + continue + if delta > 0: + submit(code, delta, Order.BUY) + else: + if cur > 0 and current_temp.get_stock_count(code, bar=time_per_step) < self.hold_thresh: + continue + submit(code, -delta, Order.SELL) + + return TradeDecisionWO(sell_orders + buy_orders, self) diff --git a/code/tac-qlib/tac_qlib/contrib/strategy/optimal_stop.py b/code/tac-qlib/tac_qlib/contrib/strategy/optimal_stop.py new file mode 100644 index 0000000..79aaad9 --- /dev/null +++ b/code/tac-qlib/tac_qlib/contrib/strategy/optimal_stop.py @@ -0,0 +1,217 @@ +"""Optimal-stopping / stochastic-control strategy for cross-sectional signals. + +Entry is a control policy: a symbol opens a position only when its cross-sectional +signal percentile is at or above ``entry_pct`` (i.e. it is one of the top-ranked +names) and the portfolio has fewer than ``topk`` open positions. + +Exit is an optimal-stopping rule: a held position is stopped (closed) when its +signal percentile falls below ``exit_pct`` (the continuation value of holding is +no longer worth the risk), OR after ``max_hold_days`` (time stop / finite +horizon), OR when the position P&L breaches ``sl`` (loss control) and the +position has been held at least ``min_hold_days``. + +Sizing is fixed ``notional`` per position (equal-weight control), unlike the +TopkDropout cash-allocation heuristic. + +Wired into qrun workflows like any ``BaseStrategy`` (see ``PortAnaRecord`` +config). Mirrors the API usage of qlib's ``TopkDropoutStrategy``: ``Order``/ +``OrderDir`` from ``qlib.backtest.decision``, ``trade_calendar`` / +``trade_exchange`` / ``trade_position`` injected by the backtest executor. +""" + +from __future__ import annotations + +from typing import List + +import pandas as pd + +from qlib.backtest import Order +from qlib.backtest.decision import OrderDir, TradeDecisionWO +from qlib.contrib.strategy.signal_strategy import BaseSignalStrategy + +__all__ = ["OptimalStopControl"] + +DEFAULT_NOTIONAL = 20_000.0 +DEFAULT_ENTRY_PCT = 0.80 +DEFAULT_EXIT_PCT = 0.50 +DEFAULT_MAX_HOLD_DAYS = 10 +DEFAULT_MIN_HOLD_DAYS = 2 +DEFAULT_SL = -0.06 + + +class OptimalStopControl(BaseSignalStrategy): + """Optimal-stopping long-only strategy over a cross-sectional signal. + + Parameters + ---------- + topk : max number of concurrent positions. + entry_pct : min cross-sectional score percentile required to OPEN (0..1). + exit_pct : held positions are stopped when score percentile < exit_pct. + max_hold_days : hard time stop (finite-horizon close). + min_hold_days : minimum holding days before stop-loss is evaluated. + notional : $ per position (equal-weight control). + sl : stop-loss threshold as fraction of entry price (<= 0), disabled if 0. + """ + + def __init__( + self, + *, + signal=None, + topk: int = 10, + entry_pct: float = DEFAULT_ENTRY_PCT, + exit_pct: float = DEFAULT_EXIT_PCT, + max_hold_days: int = DEFAULT_MAX_HOLD_DAYS, + min_hold_days: int = DEFAULT_MIN_HOLD_DAYS, + notional: float = DEFAULT_NOTIONAL, + sl: float = DEFAULT_SL, + risk_degree: float = 0.95, + trade_exchange=None, + level_infra=None, + common_infra=None, + **kwargs, + ): + super().__init__( + signal=signal, + trade_exchange=trade_exchange, + level_infra=level_infra, + common_infra=common_infra, + **kwargs, + ) + self.topk = topk + self.entry_pct = entry_pct + self.exit_pct = exit_pct + self.max_hold_days = max_hold_days + self.min_hold_days = min_hold_days + self.notional = notional + self.sl = sl + + # ------------------------------------------------------------------ utils + @staticmethod + def _pct_rank(score: pd.Series) -> pd.Series: + return score.rank(pct=True) + + def _entry_price(self, pos) -> float: + # Position stores avg entry price under key "price" (see Position.position) + price = pos.position.get("price") + if price is None: + price = pos.get_stock_amount("price") + return float(price) + + def _pnl_pct(self, pos, mark: float) -> float: + entry = self._entry_price(pos) + if not entry or entry != entry: + return 0.0 + return mark / entry - 1.0 + + def _is_tradable(self, code, start, end, direction) -> bool: + try: + return self.trade_exchange.is_stock_tradable( + stock_id=code, start_time=start, end_time=end, direction=direction + ) + except TypeError: # some exchanges take no direction kwarg + return self.trade_exchange.is_stock_tradable(stock_id=code, start_time=start, end_time=end) + + # ------------------------------------------------------------ decision + def generate_trade_decision(self, execute_result=None): + trade_step = self.trade_calendar.get_trade_step() + trade_start, trade_end = self.trade_calendar.get_step_time(trade_step) + pred_start, pred_end = self.trade_calendar.get_step_time(trade_step, shift=1) + pred_score = self.signal.get_signal(start_time=pred_start, end_time=pred_end) + if isinstance(pred_score, pd.DataFrame): + pred_score = pred_score.iloc[:, 0] + if pred_score is None or len(pred_score) == 0: + return TradeDecisionWO([], self) + + pct = self._pct_rank(pred_score) + time_per_step = self.trade_calendar.get_freq() + current_temp = __import__("copy").deepcopy(self.trade_position) + + holdings = {} + for code in current_temp.get_stock_list(): + if abs(current_temp.get_stock_amount(code)) > 1e-6: + holdings[code] = current_temp + + # ---- optimal stopping: close held positions ----------------------- + sell_orders: List[Order] = [] + closed_today = set() + kept = {} + for code, pos in holdings.items(): + held = current_temp.get_stock_count(code, bar=time_per_step) + mark = self.trade_exchange.get_deal_price( + stock_id=code, start_time=trade_start, end_time=trade_end, direction=Order.SELL + ) + if mark is None or mark != mark: + continue + rank = pct.get(code, 0.0) + stop_pnl = held >= self.min_hold_days and self.sl < 0 and self._pnl_pct(pos, mark) <= self.sl + if held >= self.max_hold_days or rank < self.exit_pct or stop_pnl: + amt = abs(current_temp.get_stock_amount(code)) + o = Order(stock_id=code, amount=amt, start_time=trade_start, + end_time=trade_end, direction=Order.SELL) + if self.trade_exchange.check_order(o): + sell_orders.append(o) + self.trade_exchange.deal_order(o, position=current_temp) + closed_today.add(code) + else: + kept[code] = mark + + # ---- equal-weight control: target notional per name ----------------- + # candidate opens: top-ranked names whose signal pct >= entry_pct + rank_desc = pred_score.sort_values(ascending=False) + held_codes = set(kept) + opens = [] + for sym in rank_desc.index: + if len(opens) >= self.topk: + break + if sym in held_codes: + continue + if pct.get(sym, 0.0) < self.entry_pct: + continue + if not self._is_tradable(sym, trade_start, trade_end, OrderDir.BUY): + continue + opens.append(sym) + + targets = held_codes | set(opens) + if not targets: + return TradeDecisionWO(sell_orders, self) + + # total value (cash + marked positions) -> per-target notional + total_value = current_temp.get_cash() + for code, mark in kept.items(): + total_value += abs(current_temp.get_stock_amount(code)) * mark + + target_notional = total_value * self.risk_degree / max(1, len(targets)) + + # ---- rebalance kept positions toward target weight ------------------ + buy_orders: List[Order] = [] + for code, mark in kept.items(): + cur = abs(current_temp.get_stock_amount(code)) * mark + diff_notional = target_notional - cur + if abs(diff_notional) / target_notional < 0.02: + continue # skip tiny rebalances + amount_delta = diff_notional / mark + direction = Order.BUY if amount_delta > 0 else Order.SELL + o = Order(stock_id=code, amount=abs(amount_delta), start_time=trade_start, + end_time=trade_end, direction=direction) + if self.trade_exchange.check_order(o): + (buy_orders if direction == Order.BUY else sell_orders).append(o) + self.trade_exchange.deal_order(o, position=current_temp) + + # ---- open new positions at target weight ---------------------------- + for sym in opens: + px = self.trade_exchange.get_deal_price( + stock_id=sym, start_time=trade_start, end_time=trade_end, direction=OrderDir.BUY + ) + if px is None or px != px or px <= 0: + continue + amount = target_notional / px + factor = self.trade_exchange.get_factor( + stock_id=sym, start_time=trade_start, end_time=trade_end + ) + amount = self.trade_exchange.round_amount_by_trade_unit(amount, factor) + o = Order(stock_id=sym, amount=amount, start_time=trade_start, + end_time=trade_end, direction=Order.BUY) + if self.trade_exchange.check_order(o): + buy_orders.append(o) + + return TradeDecisionWO(sell_orders + buy_orders, self) diff --git a/code/tac-qlib/tac_qlib/contrib/strategy/regime_gate.py b/code/tac-qlib/tac_qlib/contrib/strategy/regime_gate.py new file mode 100644 index 0000000..5b9acfb --- /dev/null +++ b/code/tac-qlib/tac_qlib/contrib/strategy/regime_gate.py @@ -0,0 +1,231 @@ +"""HMM-regime overlay TopkDropout strategy. + +Regime-gate overlay on ``qlib.contrib.strategy.signal_strategy.TopkDropoutStrategy``: +selection and sizing are identical to the reference, but a name is only BOUGHT +(entry gate) when its per-symbol HMM regime posterior ``sp_hmm_p_regime1`` on +the signal date is >= ``regime_threshold``; otherwise it is held in cash instead +of being opened. + +The regime posterior is read from the lake feature provider on the fly via +``qlib.data.D.features`` (field ``$sp_hmm_p_regime1``) for the signal window, so +no regime column needs to enter the model's ``feature_fields`` — the gate is a +pure overlay (book ch.01: regime flags regressed as model features, survived +only as an overlay). The HMM itself was fit with ``fit_end=`` when +the lake features were backfilled, so there is no lookahead. + +Names already held are NOT force-sold when the regime turns unfavourable +(entry gate only, matching the queue-10 design). +""" + +from __future__ import annotations + +from typing import List + +import numpy as np +import pandas as pd + +from qlib.backtest import Order +from qlib.backtest.decision import OrderDir, TradeDecisionWO +from qlib.contrib.strategy.signal_strategy import TopkDropoutStrategy + +try: + from qlib.data import D +except ImportError: # pragma: no cover - qlib always present in this stack + D = None + +__all__ = ["RegimeGateDropoutStrategy"] + +DEFAULT_REGIME_THRESHOLD = 0.5 +REGIME_FIELD = "$sp_hmm_p_regime1" + + +class RegimeGateDropoutStrategy(TopkDropoutStrategy): + """TopkDropout with an HMM-regime entry gate on buy candidates. + + Parameters + ---------- + topk, n_drop, method_sell, method_buy, hold_thresh, only_tradable, + forbid_all_trade_at_limit : same as ``TopkDropoutStrategy``. + regime_threshold : minimum ``sp_hmm_p_regime1`` posterior required to open a + new position (default 0.5). + """ + + def __init__(self, *, topk, n_drop, regime_threshold: float = DEFAULT_REGIME_THRESHOLD, **kwargs): + super().__init__(topk=topk, n_drop=n_drop, **kwargs) + self.regime_threshold = regime_threshold + + def _regime_for(self, codes, pred_start, pred_end) -> pd.Series: + """Return {code: sp_hmm_p_regime1} for the signal window (last day).""" + if D is None: + return pd.Series(dtype=float) + try: + df = D.features(list(codes), [REGIME_FIELD], start_time=pred_start, end_time=pred_end, freq="day") + except Exception: # noqa: BLE001 - a regime read failure should gate open, not crash + return pd.Series(dtype=float) + if df is None or len(df) == 0: + return pd.Series(dtype=float) + # df index is MultiIndex (datetime, instrument); take the last day's values + df = df.reset_index() + ts_col = "datetime" if "datetime" in df.columns else df.columns[0] + sym_col = "instrument" if "instrument" in df.columns else df.columns[1] + last_ts = df[ts_col].max() + last = df[df[ts_col] == last_ts] + out = {} + for _, row in last.iterrows(): + sym = str(row[sym_col]).split("/")[-1].upper() + val = row.iloc[-1] + out[sym] = float(val) if val == val else np.nan + return pd.Series(out) + + def generate_trade_decision(self, execute_result=None): + import copy + + trade_step = self.trade_calendar.get_trade_step() + trade_start_time, trade_end_time = self.trade_calendar.get_step_time(trade_step) + pred_start_time, pred_end_time = self.trade_calendar.get_step_time(trade_step, shift=1) + pred_score = self.signal.get_signal(start_time=pred_start_time, end_time=pred_end_time) + if isinstance(pred_score, pd.DataFrame): + pred_score = pred_score.iloc[:, 0] + if pred_score is None: + return TradeDecisionWO([], self) + + if self.only_tradable: + + def get_first_n(li, n, reverse=False): + cur_n = 0 + res = [] + for si in reversed(li) if reverse else li: + if self.trade_exchange.is_stock_tradable( + stock_id=si, start_time=trade_start_time, end_time=trade_end_time + ): + res.append(si) + cur_n += 1 + if cur_n >= n: + break + return res[::-1] if reverse else res + + def get_last_n(li, n): + return get_first_n(li, n, reverse=True) + + def filter_stock(li): + return [ + si + for si in li + if self.trade_exchange.is_stock_tradable( + stock_id=si, start_time=trade_start_time, end_time=trade_end_time + ) + ] + + else: + + def get_first_n(li, n): + return list(li)[:n] + + def get_last_n(li, n): + return list(li)[-n:] + + def filter_stock(li): + return li + + current_temp: "object" = copy.deepcopy(self.trade_position) + sell_order_list: List[Order] = [] + buy_order_list: List[Order] = [] + cash = current_temp.get_cash() + current_stock_list = current_temp.get_stock_list() + last = pred_score.reindex(current_stock_list).sort_values(ascending=False).index + + if self.method_buy == "top": + today = get_first_n( + pred_score[~pred_score.index.isin(last)].sort_values(ascending=False).index, + self.n_drop + self.topk - len(last), + ) + elif self.method_buy == "random": + topk_candi = get_first_n(pred_score.sort_values(ascending=False).index, self.topk) + candi = list(filter(lambda x: x not in last, topk_candi)) + n = self.n_drop + self.topk - len(last) + try: + today = np.random.choice(candi, n, replace=False) + except ValueError: + today = candi + else: + raise NotImplementedError(f"This type of input is not supported") + + comb = pred_score.reindex(last.union(pd.Index(today))).sort_values(ascending=False).index + + if self.method_sell == "bottom": + sell = last[last.isin(get_last_n(comb, self.n_drop))] + elif self.method_sell == "random": + candi = filter_stock(last) + try: + sell = pd.Index(np.random.choice(candi, self.n_drop, replace=False) if len(last) else []) + except ValueError: + sell = candi + else: + raise NotImplementedError(f"This type of input is not supported") + + buy = today[: len(sell) + self.topk - len(last)] + + # ---- regime gate ----------------------------------------------------- + if buy: + regime = self._regime_for(buy, pred_start_time, pred_end_time) + gated = [c for c in buy if regime.get(c, np.nan) >= self.regime_threshold] + else: + gated = [] + + for code in current_stock_list: + if not self.trade_exchange.is_stock_tradable( + stock_id=code, + start_time=trade_start_time, + end_time=trade_end_time, + direction=None if self.forbid_all_trade_at_limit else OrderDir.SELL, + ): + continue + if code in sell: + time_per_step = self.trade_calendar.get_freq() + if current_temp.get_stock_count(code, bar=time_per_step) < self.hold_thresh: + continue + sell_amount = current_temp.get_stock_amount(code=code) + sell_order = Order( + stock_id=code, + amount=sell_amount, + start_time=trade_start_time, + end_time=trade_end_time, + direction=Order.SELL, + ) + if self.trade_exchange.check_order(sell_order): + sell_order_list.append(sell_order) + trade_val, trade_cost, trade_price = self.trade_exchange.deal_order( + sell_order, position=current_temp + ) + cash += trade_val - trade_cost + + if len(gated) == 0: + return TradeDecisionWO(sell_order_list, self) + + value = cash * self.risk_degree / len(gated) + for code in gated: + if not self.trade_exchange.is_stock_tradable( + stock_id=code, + start_time=trade_start_time, + end_time=trade_end_time, + direction=None if self.forbid_all_trade_at_limit else OrderDir.BUY, + ): + continue + buy_price = self.trade_exchange.get_deal_price( + stock_id=code, start_time=trade_start_time, end_time=trade_end_time, direction=OrderDir.BUY + ) + buy_amount = value / buy_price + factor = self.trade_exchange.get_factor( + stock_id=code, start_time=trade_start_time, end_time=trade_end_time + ) + buy_amount = self.trade_exchange.round_amount_by_trade_unit(buy_amount, factor) + buy_order = Order( + stock_id=code, + amount=buy_amount, + start_time=trade_start_time, + end_time=trade_end_time, + direction=Order.BUY, + ) + buy_order_list.append(buy_order) + + return TradeDecisionWO(sell_order_list + buy_order_list, self) \ No newline at end of file diff --git a/code/tac-qlib/tac_qlib/contrib/strategy/weekly_rebalance.py b/code/tac-qlib/tac_qlib/contrib/strategy/weekly_rebalance.py new file mode 100644 index 0000000..839abb8 --- /dev/null +++ b/code/tac-qlib/tac_qlib/contrib/strategy/weekly_rebalance.py @@ -0,0 +1,223 @@ +"""Weekly-rebalance TopkDropout strategy. + +Turnover-reduction variant of ``qlib.contrib.strategy.signal_strategy.TopkDropoutStrategy``: +the topk/n_drop selection and sizing are identical to the reference, but the +target book is recomputed only on the first trading day of each ISO week; on the +other days the strategy issues NO orders (holds the book untouched). + +The weekly cadence is derived from the qlib trade calendar: a rebalance happens +when the current trade step's date belongs to a different ISO ``(year, week)`` +than the previous trade step. ``hold_band_pct`` (default 0) optionally skips +tiny rebalances: when a name's existing position differs from the new target by +less than this fraction, no order is generated for it. +""" + +from __future__ import annotations + +from typing import List + +import numpy as np +import pandas as pd + +from qlib.backtest import Order +from qlib.backtest.decision import OrderDir, TradeDecisionWO +from qlib.contrib.strategy.signal_strategy import TopkDropoutStrategy + +__all__ = ["WeeklyRebalanceDropoutStrategy"] + +DEFAULT_HOLD_BAND_PCT = 0.0 + + +class WeeklyRebalanceDropoutStrategy(TopkDropoutStrategy): + """TopkDropout rebalanced once per ISO week; holds otherwise. + + Parameters + ---------- + topk, n_drop, method_sell, method_buy, hold_thresh, only_tradable, + forbid_all_trade_at_limit : same as ``TopkDropoutStrategy``. + hold_band_pct : skip order for a name whose deviation from target weight is + below this fraction of the target (no-trade buffer band). + rebalance_every_n_weeks : rebalance every N ISO weeks instead of every week + (default 1 = weekly; 2 = biweekly). Ignored when + ``rebalance_every_n_days`` is set. + rebalance_every_n_days : rebalance every N trading days (daily when N=1). + When set, overrides the weekly gating logic entirely. + """ + + def __init__(self, *, topk, n_drop, hold_band_pct: float = DEFAULT_HOLD_BAND_PCT, + rebalance_every_n_weeks: int = 1, + rebalance_every_n_days: int = 0, **kwargs): + super().__init__(topk=topk, n_drop=n_drop, **kwargs) + self.hold_band_pct = hold_band_pct + self.rebalance_every_n_weeks = rebalance_every_n_weeks + self.rebalance_every_n_days = rebalance_every_n_days + + @staticmethod + def _iso_week(ts) -> tuple: + return (ts.year, ts.week) + + def generate_trade_decision(self, execute_result=None): + import copy + + trade_step = self.trade_calendar.get_trade_step() + trade_start_time, trade_end_time = self.trade_calendar.get_step_time(trade_step) + + if self.rebalance_every_n_days > 0: + # daily gating: count trading steps since last rebalance + step_num = trade_step + if hasattr(self, "_last_rebal_step"): + if (step_num - self._last_rebal_step) < self.rebalance_every_n_days: + return TradeDecisionWO([], self) + self._last_rebal_step = step_num + else: + cur_week = self._iso_week(trade_start_time) + prev_week = getattr(self, "_last_week", None) + self._last_week = cur_week + + if prev_week is not None and prev_week == cur_week: + return TradeDecisionWO([], self) + + if self.rebalance_every_n_weeks > 1: + week_num = cur_week[1] + if prev_week is not None and (week_num % self.rebalance_every_n_weeks) != 1: + return TradeDecisionWO([], self) + + pred_start_time, pred_end_time = self.trade_calendar.get_step_time(trade_step, shift=1) + pred_score = self.signal.get_signal(start_time=pred_start_time, end_time=pred_end_time) + if isinstance(pred_score, pd.DataFrame): + pred_score = pred_score.iloc[:, 0] + if pred_score is None: + return TradeDecisionWO([], self) + + if self.only_tradable: + + def get_first_n(li, n, reverse=False): + cur_n = 0 + res = [] + for si in reversed(li) if reverse else li: + if self.trade_exchange.is_stock_tradable( + stock_id=si, start_time=trade_start_time, end_time=trade_end_time + ): + res.append(si) + cur_n += 1 + if cur_n >= n: + break + return res[::-1] if reverse else res + + def get_last_n(li, n): + return get_first_n(li, n, reverse=True) + + def filter_stock(li): + return [ + si + for si in li + if self.trade_exchange.is_stock_tradable( + stock_id=si, start_time=trade_start_time, end_time=trade_end_time + ) + ] + + else: + + def get_first_n(li, n): + return list(li)[:n] + + def get_last_n(li, n): + return list(li)[-n:] + + def filter_stock(li): + return li + + current_temp: "object" = copy.deepcopy(self.trade_position) + sell_order_list: List[Order] = [] + buy_order_list: List[Order] = [] + cash = current_temp.get_cash() + current_stock_list = current_temp.get_stock_list() + last = pred_score.reindex(current_stock_list).sort_values(ascending=False).index + + if self.method_buy == "top": + today = get_first_n( + pred_score[~pred_score.index.isin(last)].sort_values(ascending=False).index, + self.n_drop + self.topk - len(last), + ) + elif self.method_buy == "random": + topk_candi = get_first_n(pred_score.sort_values(ascending=False).index, self.topk) + candi = list(filter(lambda x: x not in last, topk_candi)) + n = self.n_drop + self.topk - len(last) + try: + today = np.random.choice(candi, n, replace=False) + except ValueError: + today = candi + else: + raise NotImplementedError(f"This type of input is not supported") + + comb = pred_score.reindex(last.union(pd.Index(today))).sort_values(ascending=False).index + + if self.method_sell == "bottom": + sell = last[last.isin(get_last_n(comb, self.n_drop))] + elif self.method_sell == "random": + candi = filter_stock(last) + try: + sell = pd.Index(np.random.choice(candi, self.n_drop, replace=False) if len(last) else []) + except ValueError: + sell = candi + else: + raise NotImplementedError(f"This type of input is not supported") + + buy = today[: len(sell) + self.topk - len(last)] + for code in current_stock_list: + if not self.trade_exchange.is_stock_tradable( + stock_id=code, + start_time=trade_start_time, + end_time=trade_end_time, + direction=None if self.forbid_all_trade_at_limit else OrderDir.SELL, + ): + continue + if code in sell: + time_per_step = self.trade_calendar.get_freq() + if current_temp.get_stock_count(code, bar=time_per_step) < self.hold_thresh: + continue + sell_amount = current_temp.get_stock_amount(code=code) + sell_order = Order( + stock_id=code, + amount=sell_amount, + start_time=trade_start_time, + end_time=trade_end_time, + direction=Order.SELL, + ) + if self.trade_exchange.check_order(sell_order): + sell_order_list.append(sell_order) + trade_val, trade_cost, trade_price = self.trade_exchange.deal_order( + sell_order, position=current_temp + ) + cash += trade_val - trade_cost + + if len(buy) == 0: + return TradeDecisionWO(sell_order_list, self) + + value = cash * self.risk_degree / len(buy) + for code in buy: + if not self.trade_exchange.is_stock_tradable( + stock_id=code, + start_time=trade_start_time, + end_time=trade_end_time, + direction=None if self.forbid_all_trade_at_limit else OrderDir.BUY, + ): + continue + buy_price = self.trade_exchange.get_deal_price( + stock_id=code, start_time=trade_start_time, end_time=trade_end_time, direction=OrderDir.BUY + ) + buy_amount = value / buy_price + factor = self.trade_exchange.get_factor( + stock_id=code, start_time=trade_start_time, end_time=trade_end_time + ) + buy_amount = self.trade_exchange.round_amount_by_trade_unit(buy_amount, factor) + buy_order = Order( + stock_id=code, + amount=buy_amount, + start_time=trade_start_time, + end_time=trade_end_time, + direction=Order.BUY, + ) + buy_order_list.append(buy_order) + + return TradeDecisionWO(sell_order_list + buy_order_list, self) \ No newline at end of file diff --git a/code/tac-qlib/tac_qlib/data/__init__.py b/code/tac-qlib/tac_qlib/data/__init__.py new file mode 100644 index 0000000..92e6e90 --- /dev/null +++ b/code/tac-qlib/tac_qlib/data/__init__.py @@ -0,0 +1,25 @@ +from .config import ( + LakeConfig, + BAR_FIELD_MAP, + FREQ_TO_TIMEFRAME, + UNKNOWN_FIELD_NAMES, + timeframe_for_freq, + resolve_lake_root, +) +from .providers import ( + LakeCalendarProvider, + LakeInstrumentProvider, + LakeFeatureProvider, +) + +__all__ = [ + "LakeConfig", + "BAR_FIELD_MAP", + "FREQ_TO_TIMEFRAME", + "UNKNOWN_FIELD_NAMES", + "timeframe_for_freq", + "resolve_lake_root", + "LakeCalendarProvider", + "LakeInstrumentProvider", + "LakeFeatureProvider", +] diff --git a/code/tac-qlib/tac_qlib/data/__pycache__/__init__.cpython-312.pyc b/code/tac-qlib/tac_qlib/data/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000..888c039 Binary files /dev/null and b/code/tac-qlib/tac_qlib/data/__pycache__/__init__.cpython-312.pyc differ diff --git a/code/tac-qlib/tac_qlib/data/__pycache__/config.cpython-312.pyc b/code/tac-qlib/tac_qlib/data/__pycache__/config.cpython-312.pyc new file mode 100644 index 0000000..26f27f9 Binary files /dev/null and b/code/tac-qlib/tac_qlib/data/__pycache__/config.cpython-312.pyc differ diff --git a/code/tac-qlib/tac_qlib/data/__pycache__/providers.cpython-312.pyc b/code/tac-qlib/tac_qlib/data/__pycache__/providers.cpython-312.pyc new file mode 100644 index 0000000..ada62e1 Binary files /dev/null and b/code/tac-qlib/tac_qlib/data/__pycache__/providers.cpython-312.pyc differ diff --git a/code/tac-qlib/tac_qlib/data/config.py b/code/tac-qlib/tac_qlib/data/config.py new file mode 100644 index 0000000..1953fb2 --- /dev/null +++ b/code/tac-qlib/tac_qlib/data/config.py @@ -0,0 +1,207 @@ +"""TradeAC lake configuration helpers. + +The lake is a hive-partitioned parquet store (see ``tac-engine/skills/tradeac-lake``): + + $TAC_LAKE_DIR/ + ├── market=US/ + │ └── timeframe=1d/ + │ └── symbol=AAPL.parquet # OHLCV bars: t, date, o, h, l, c, v, n, vw + ├── features/ # indicators, wide format, family tier + │ └── market=US/ + │ └── timeframe=1d/ + │ ├── family=ta/symbol=AAPL.parquet # t, sma_5, sma_20, rsi_14, ... + │ └── family=sp/symbol=AAPL.parquet # t, sp_ou_*, sp_hmm_*, ... + ├── calendar.parquet # trading days per market + ├── coverage.parquet # per (market,timeframe,symbol) loaded windows + └── symbols.parquet # asset master +""" + +from __future__ import annotations + +import os +from pathlib import Path +from typing import Dict, List, Optional + +import pandas as pd + +#: qlib freq string (Freq.__str__) -> lake timeframe partition name +FREQ_TO_TIMEFRAME: Dict[str, str] = { + "day": "1d", + "1d": "1d", + "min": "1m", + "1min": "1m", + "5min": "5m", + "10min": "10m", + "15min": "15m", + "30min": "30m", + "hour": "1h", + "1hour": "1h", + "2hour": "2h", + "4hour": "4h", + "week": "1w", + "1week": "1w", + "month": "1M", + "1month": "1M", +} + +#: bar-field map: qlib field name (without the leading ``$``) -> lake bar column +BAR_FIELD_MAP: Dict[str, str] = { + "open": "o", + "high": "h", + "low": "l", + "close": "c", + "volume": "v", + "vwap": "vw", + "avg_amount": "vw", # amount / volume +} + +#: fields that qlib core/backtest queries but the lake does not store -> all-NaN +UNKNOWN_FIELD_NAMES = ("factor", "change", "trade_unit", "suspend_flag") + +#: columns in the parquet files that are not features +NON_FEATURE_COLUMNS = ("t", "date", "market", "timeframe", "symbol") + +#: Feature-family partitions merged by ``LakeConfig.load_features`` and scanned +#: by the handler's field discovery. ``macro`` holds broadcast market-state +#: columns (see skills/tac-qlib-custom/examples/persist_macro_broadcast.py). +FEATURE_FAMILIES = ("ta", "sp", "macro") + + +def timeframe_for_freq(freq: str) -> str: + """Map a qlib frequency (e.g. ``day``, ``1min``) to a lake timeframe (e.g. ``1d``).""" + f = str(freq).lower() + if f not in FREQ_TO_TIMEFRAME: + raise ValueError( + f"unsupported qlib freq {freq!r}; supported freqs: {sorted(set(FREQ_TO_TIMEFRAME))}" + ) + return FREQ_TO_TIMEFRAME[f] + + +def resolve_lake_root(lake_root: Optional[str] = None) -> Path: + """Resolve the lake root: explicit arg > ``TAC_LAKE_DIR`` (no fallback). + + ``TAC_LAKE_DIR`` is **mandatory** — there is deliberately no default + A missing/empty value raises so a + misconfigured environment never silently points at a wrong directory. + """ + if lake_root is None: + lake_root = os.environ.get("TAC_LAKE_DIR") + if not lake_root: + raise RuntimeError( + "TAC_LAKE_DIR is not set. Point it at the TradeAC lake root, e.g. " + "export TAC_LAKE_DIR=/home/data/lake (docker) or set an absolute " + "path in your local .env." + ) + return Path(str(lake_root)).expanduser().resolve() + + +class LakeConfig: + """Path helpers + cached readers for a (lake_root, market) combination.""" + + def __init__(self, lake_root: Optional[str] = None, market: str = "US"): + self.lake_root: Path = resolve_lake_root(lake_root) + self.market: str = (market or "US").upper() + + # ---- paths -------------------------------------------------------------- + def bar_dir(self, timeframe: str) -> Path: + return self.lake_root / f"market={self.market}" / f"timeframe={timeframe}" + + def bar_path(self, timeframe: str, symbol: str) -> Path: + return self.bar_dir(timeframe) / f"symbol={str(symbol).upper()}.parquet" + + def features_dir(self, timeframe: str) -> Path: + return self.lake_root / "features" / f"market={self.market}" / f"timeframe={timeframe}" + + def features_path(self, timeframe: str, symbol: str) -> Path: + # Legacy flat path (no family tier). Prefer `load_features` which + # resolves the family=ta|sp partition layout. + return self.features_dir(timeframe) / f"symbol={str(symbol).upper()}.parquet" + + def load_features(self, timeframe: str, symbol: str) -> pd.DataFrame: + """All feature columns for a symbol, merging the `family=ta|sp|macro` + partitions by timestamp. Returns an empty frame when no + feature files exist (legacy flat layout falls back transparently).""" + sym = str(symbol).upper() + frames = [] + for family in FEATURE_FAMILIES: + p = self.features_dir(timeframe) / f"family={family}" / f"symbol={sym}.parquet" + if p.exists(): + frames.append(pd.read_parquet(p)) + if not frames: + flat = self.features_dir(timeframe) / f"symbol={sym}.parquet" + if flat.exists(): + return pd.read_parquet(flat) + return pd.DataFrame() + if len(frames) == 1: + return frames[0] + merged = frames[0] + for extra in frames[1:]: + merged = merged.merge(extra, on="t", how="outer", suffixes=("", "_dup")) + for c in [c for c in merged.columns if c.endswith("_dup")]: + merged = merged.drop(columns=c) + return merged + + def calendar_path(self) -> Path: + return self.lake_root / "calendar.parquet" + + def symbols_path(self) -> Path: + return self.lake_root / "symbols.parquet" + + def coverage_path(self) -> Path: + return self.lake_root / "coverage.parquet" + + # ---- metadata readers ---------------------------------------------------- + def load_symbols(self) -> List[str]: + """All symbols known to the lake (from ``symbols.parquet``).""" + p = self.symbols_path() + if not p.exists(): + return [] + df = pd.read_parquet(p) + if "symbol" not in df.columns: + return [] + return sorted(df["symbol"].astype(str).str.upper().tolist()) + + def symbol_spans(self, symbol: str, timeframe: str) -> List[tuple]: + """Listing span(s) ``[(start_iso, end_iso)]`` for a symbol from coverage.parquet.""" + p = self.coverage_path() + if p.exists(): + try: + df = pd.read_parquet(p) + except Exception: # pragma: no cover - defensive + df = pd.DataFrame() + if len(df): + df = df[ + (df.get("market") == self.market) + & (df.get("timeframe") == timeframe) + & (df.get("symbol") == str(symbol).upper()) + ] + if len(df): + row = df.iloc[0] + first = pd.Timestamp(row["first_t"]).date() + last = pd.Timestamp(row["last_t"]).date() + return [(first.isoformat(), last.isoformat())] + # fallback: derive from the bar file itself + p = self.bar_path(timeframe, symbol) + if p.exists(): + import pyarrow.parquet as pq + + tbl = pq.read_table(p, columns=["t"]) + first = pd.Timestamp(tbl.column("t")[0].as_py()).date() + last = pd.Timestamp(tbl.column("t")[-1].as_py()).date() + return [(first.isoformat(), last.isoformat())] + return [("1970-01-01", "2099-12-31")] + + def load_calendar_dates(self) -> List[pd.Timestamp]: + """Trading days (midnight timestamps) for the market, from ``calendar.parquet``.""" + p = self.calendar_path() + if p.exists(): + df = pd.read_parquet(p) + if "date" in df.columns: + if "market" in df.columns: + df = df[df["market"] == self.market] + dates = pd.to_datetime(df["date"]).dt.normalize().sort_values().unique() + return [pd.Timestamp(x) for x in dates] + return [] + + def __repr__(self) -> str: # pragma: no cover + return f"LakeConfig(lake_root={self.lake_root}, market={self.market})" diff --git a/code/tac-qlib/tac_qlib/data/providers.py b/code/tac-qlib/tac_qlib/data/providers.py new file mode 100644 index 0000000..8d0644f --- /dev/null +++ b/code/tac-qlib/tac_qlib/data/providers.py @@ -0,0 +1,230 @@ +"""qlib data providers backed by the TradeAC parquet lake. + +These providers plug into the standard qlib mechanism: ``qlib.init(calendar_provider=..., +instrument_provider=..., feature_provider=...)`` instantiates them and binds them to the +``Cal`` / ``Inst`` / ``FeatureD`` wrappers (see ``qlib.data.data.register_all_wrappers``). +The rest of qlib (``LocalDatasetProvider`` expression engine, backtest ``Exchange``) keeps +working unchanged because the interface contract is identical to the file-based providers: + +- ``feature()`` returns a ``pd.Series`` indexed by the **calendar position** range + ``[start_index, end_index]`` (matching ``FileFeatureStorage.__getitem__`` semantics). +- ``list_instruments()`` returns ``{symbol: [(start, end), ...]}``. +- ``load_calendar()`` returns a list of ``pd.Timestamp`` trading days. +""" + +from __future__ import annotations + +import bisect +from typing import Dict, List, Optional, Union + +import numpy as np +import pandas as pd + +from qlib.data.data import CalendarProvider, FeatureProvider, InstrumentProvider +from qlib.log import get_module_logger + +from .config import ( + BAR_FIELD_MAP, + LakeConfig, + UNKNOWN_FIELD_NAMES, + timeframe_for_freq, +) + +logger = get_module_logger("tac_qlib.data.providers") + + +def _day_freq(freq: str) -> bool: + return str(freq).lower() in ("day", "1d") + + +def _calendar_keys(cal: List[pd.Timestamp], freq: str) -> pd.Index: + """Convert calendar timestamps into the same key space as the lake parquet.""" + if _day_freq(freq): + return pd.Index([pd.Timestamp(x).date() for x in cal]) + return pd.Index([pd.Timestamp(x) for x in cal]) + + +class LakeCalendarProvider(CalendarProvider): + """Trading calendar read from ``/calendar.parquet`` (fallback: derived from bars).""" + + def __init__(self, lake_root: Optional[str] = None, market: str = "US"): + super().__init__() + self.cfg = LakeConfig(lake_root, market) + + def load_calendar(self, freq, future): + timeframe = timeframe_for_freq(freq) + if not _day_freq(freq): + raise NotImplementedError( + f"freq={freq!r} (timeframe={timeframe}) is not supported yet: the lake calendar " + f"only covers daily sessions; add a minute-level calendar to `calendar.parquet`" + ) + + dates = self.cfg.load_calendar_dates() + if not dates: + # Fallback: derive the trading-day set from the persisted bar files. + bar_dir = self.cfg.bar_dir(timeframe) + if bar_dir.exists(): + import pyarrow.parquet as pq + + cal: Dict[pd.Timestamp, None] = {} + for p in sorted(bar_dir.glob("symbol=*.parquet")): + tbl = pq.read_table(p, columns=["t"]) + for v in tbl.column("t"): + cal[pd.Timestamp(v.as_py()).normalize()] = None + dates = sorted(cal.keys()) + if not dates: + return [] + + if future: + # append the next calendar day so that "today" is a valid trade date + last = dates[-1] + dates = dates + [pd.Timestamp(last) + pd.Timedelta(days=1)] + return dates + + +class LakeInstrumentProvider(InstrumentProvider): + """Instruments from ``/symbols.parquet`` with listing spans from ``coverage.parquet``.""" + + def __init__( + self, + lake_root: Optional[str] = None, + market: str = "US", + markets: Optional[Dict[str, list]] = None, + ): + super().__init__() + self.cfg = LakeConfig(lake_root, market) + #: optional named pools, e.g. ``{"sp500": ["AAPL", "MSFT"], "etf": ["SPY"]}``. + #: ``all`` / any unregistered name resolves to every symbol in the lake. + self.markets: Dict[str, list] = markets or {} + + def _resolve_symbols(self, market: Union[str, list]) -> List[str]: + if isinstance(market, (list, tuple, pd.Index, np.ndarray)): + return [str(s).upper() for s in market] + if isinstance(market, str) and "," in market: + return [s.strip().upper() for s in market.split(",") if s.strip()] + if market in self.markets: + return [str(s).upper() for s in self.markets[market]] + return self.cfg.load_symbols() + + def list_instruments(self, instruments, start_time=None, end_time=None, freq="day", as_list=False): + market = instruments["market"] + timeframe = timeframe_for_freq(freq) + + symbols = self._resolve_symbols(market) + if not symbols: + if as_list: + return [] + return {} + + # clip listing spans to the queried window (mirror of LocalInstrumentProvider) + from qlib.data.data import Cal # pylint: disable=C0415 + + cal = Cal.calendar(freq=freq) + start_time = pd.Timestamp(start_time or cal[0]) + end_time = pd.Timestamp(end_time or cal[-1]) + + out: Dict[str, list] = {} + for symbol in symbols: + spans = [] + for begin, end in self.cfg.symbol_spans(symbol, timeframe): + lo = max(start_time, pd.Timestamp(begin)) + hi = min(end_time, pd.Timestamp(end)) + if lo <= hi: + spans.append((lo, hi)) + if spans: + out[symbol] = spans + + filter_pipe = instruments.get("filter_pipe") or [] + for filter_config in filter_pipe: + from qlib.data import filter as F # pylint: disable=C0415 + + filter_t = getattr(F, filter_config["filter_type"]).from_config(filter_config) + out = filter_t(out, start_time, end_time, freq) + + if as_list: + return list(out) + return out + + +class LakeFeatureProvider(FeatureProvider): + """Feature data from the lake parquet (OHLCV bars + pre-computed ta-lib features). + + Field routing: + - ``$open/$high/$low/$close/$volume/$vwap`` -> bar parquet columns + - ``$amount`` (= v*vw), ``$avg_amount`` (= vw) -> derived from bar parquet + - ``$factor/$change/...`` -> all-NaN (not stored) + - anything else -> a ta-lib column in the features parquet + """ + + def __init__(self, lake_root: Optional[str] = None, market: str = "US"): + super().__init__() + self.cfg = LakeConfig(lake_root, market) + self._bar_cache: Dict[tuple, pd.DataFrame] = {} + self._feature_cache: Dict[tuple, pd.DataFrame] = {} + + # ------------------------------------------------------------------ caches + def _load_bar_df(self, instrument: str, timeframe: str) -> pd.DataFrame: + key = (instrument, timeframe) + if key not in self._bar_cache: + p = self.cfg.bar_path(timeframe, instrument) + self._bar_cache[key] = pd.read_parquet(p) if p.exists() else pd.DataFrame() + return self._bar_cache[key] + + def _load_feature_df(self, instrument: str, timeframe: str) -> pd.DataFrame: + key = (instrument, timeframe) + if key not in self._feature_cache: + self._feature_cache[key] = self.cfg.load_features(timeframe, instrument) + return self._feature_cache[key] + + @staticmethod + def _keys(df: pd.DataFrame, freq: str) -> pd.Index: + ts = pd.to_datetime(df["t"]) + return ts.dt.date if _day_freq(freq) else ts + + # ------------------------------------------------------------------ fields + def _extract(self, instrument: str, field: str, timeframe: str, freq: str) -> Optional[pd.Series]: + """Return the field as a Series keyed by date/timestamp (None if not present in the lake).""" + bar = self._load_bar_df(instrument, timeframe) + + if field in BAR_FIELD_MAP: + col = BAR_FIELD_MAP[field] + if col in bar.columns: + return bar[col].astype(float).set_axis(self._keys(bar, freq)) + return None + if field == "amount": + if "v" in bar.columns and "vw" in bar.columns: + return (bar["v"] * bar["vw"]).astype(float).set_axis(self._keys(bar, freq)) + return None + if field in UNKNOWN_FIELD_NAMES: + return None + + feat = self._load_feature_df(instrument, timeframe) + if field in feat.columns: + return feat[field].astype(float).set_axis(self._keys(feat, freq)) + return None + + # ------------------------------------------------------------------ api + def _get_calendar(self, freq: str) -> List[pd.Timestamp]: + from qlib.data.data import Cal # pylint: disable=C0415 + + cal = Cal.calendar(freq=freq) + return list(cal) + + def feature(self, instrument, field, start_index, end_index, freq): + field = str(field)[1:] + timeframe = timeframe_for_freq(freq) + + cal = self._get_calendar(freq) + n = len(cal) + lo = max(0, int(start_index)) + hi = min(n - 1, int(end_index)) + if lo > hi: + return pd.Series(dtype=np.float32) + + keys = _calendar_keys(cal[lo : hi + 1], freq) + ser = self._extract(str(instrument).upper(), field, timeframe, freq) + if ser is None: + vals = np.full(len(keys), np.nan, dtype=np.float64) + else: + vals = ser.reindex(keys).to_numpy(dtype=np.float64) + return pd.Series(vals, index=pd.RangeIndex(lo, hi + 1))