Skip to content

Commit 2018d56

Browse files
committed
Localize QQQ tech diagnostics and compare TQQQ entry gates
1 parent 042f72f commit 2018d56

6 files changed

Lines changed: 418 additions & 0 deletions

application/rebalance_service.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,17 @@
2424
("feature_snapshot_config_name_mismatch", "快照配置名不匹配"),
2525
("feature_snapshot_config_path_mismatch", "快照配置路径不匹配"),
2626
("feature_snapshot_contract_version_mismatch", "快照契约版本不匹配"),
27+
("regime=hard_defense", "市场阶段=强防御"),
28+
("regime=soft_defense", "市场阶段=软防御"),
29+
("regime=risk_on", "市场阶段=进攻"),
30+
("benchmark_trend=down", "基准趋势=向下"),
31+
("benchmark_trend=up", "基准趋势=向上"),
32+
("breadth=", "市场宽度="),
33+
("target_stock=", "目标股票仓位="),
34+
("realized_stock=", "实际股票仓位="),
35+
("selected=", "入选标的数="),
36+
("top=", "前排标的="),
37+
("no_selection", "无入选标的"),
2738
("outside_execution_window", "当前不在执行窗口"),
2839
("pending_orders_detected", "检测到未完成订单"),
2940
("same_day_execution_locked", "当日执行锁已存在"),
Lines changed: 281 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,281 @@
1+
#!/usr/bin/env python3
2+
"""Compare current ATR entry gate vs direct MA200 entry for tqqq_growth_income."""
3+
4+
from __future__ import annotations
5+
6+
import argparse
7+
import json
8+
import sys
9+
from pathlib import Path
10+
11+
import pandas as pd
12+
13+
CURRENT_DIR = Path(__file__).resolve().parent
14+
if str(CURRENT_DIR) not in sys.path:
15+
sys.path.insert(0, str(CURRENT_DIR))
16+
17+
import backtest_stock_alpha_suite as suite # noqa: E402
18+
import backtest_tqqq_growth_indicator_variants as base # noqa: E402
19+
20+
DEFAULT_RESULTS_DIR = Path(__file__).resolve().parent / "results"
21+
DEFAULT_START = "2018-01-01"
22+
DEFAULT_COSTS_BPS = (5.0,)
23+
24+
BASELINE_ENTRY_PARAMS = {
25+
"atr_entry_scale": 2.5,
26+
"entry_line_floor": 1.02,
27+
"entry_line_cap": 1.08,
28+
}
29+
MA200_ENTRY_PARAMS = {
30+
"atr_entry_scale": 0.0,
31+
"entry_line_floor": 1.0,
32+
"entry_line_cap": 1.0,
33+
}
34+
COMMON_TQQQ_PARAMS = {
35+
"starting_equity": base.RUNTIME_FULL_STARTING_EQUITY,
36+
"income_threshold_usd": 100_000.0,
37+
"qqqi_income_ratio": 0.50,
38+
"cash_reserve_ratio": 0.05,
39+
"rebalance_threshold_ratio": 0.01,
40+
"alloc_tier1_breakpoints": (0, 15_000, 30_000, 70_000),
41+
"alloc_tier1_values": (1.0, 0.95, 0.85, 0.70),
42+
"alloc_tier2_breakpoints": (70_000, 140_000),
43+
"alloc_tier2_values": (0.70, 0.50),
44+
"risk_leverage_factor": 3.0,
45+
"risk_agg_cap": 0.50,
46+
"risk_numerator": 0.30,
47+
"atr_exit_scale": 2.0,
48+
"exit_line_floor": 0.92,
49+
"exit_line_cap": 0.98,
50+
}
51+
52+
53+
def parse_args() -> argparse.Namespace:
54+
parser = argparse.ArgumentParser(description=__doc__)
55+
parser.add_argument("--results-dir", default=str(DEFAULT_RESULTS_DIR))
56+
parser.add_argument("--start", default=DEFAULT_START)
57+
parser.add_argument("--end", default=None)
58+
parser.add_argument("--cost-bps", nargs="*", type=float, default=list(DEFAULT_COSTS_BPS))
59+
return parser.parse_args()
60+
61+
62+
def load_market_data(*, start: str, end: str | None):
63+
etf_frames = suite.download_etf_ohlcv(("QQQ", "TQQQ", "BOXX", "SPYI", "QQQI"), start=start, end=end)
64+
qqq_ohlc = pd.DataFrame(
65+
{
66+
"open": etf_frames["open"]["QQQ"],
67+
"high": etf_frames["high"]["QQQ"],
68+
"low": etf_frames["low"]["QQQ"],
69+
"close": etf_frames["close"]["QQQ"],
70+
}
71+
).dropna()
72+
master_index = qqq_ohlc.index
73+
rows = suite.build_extra_etf_price_history(etf_frames, symbols=("QQQ", "TQQQ", "BOXX", "SPYI", "QQQI"))
74+
_close_matrix, returns_matrix = suite.build_asset_return_matrix(
75+
rows,
76+
master_index=master_index,
77+
required_symbols=("QQQ", "TQQQ", "BOXX", "SPYI", "QQQI"),
78+
)
79+
returns_matrix[base.CASH_SYMBOL] = 0.0
80+
indicators = base.build_indicator_frame(qqq_ohlc, etf_frames["volume"]["QQQ"].reindex(master_index).fillna(0.0))
81+
return qqq_ohlc, returns_matrix, indicators
82+
83+
84+
def build_runtime_variant(qqq_ohlc: pd.DataFrame, returns_matrix: pd.DataFrame, *, name: str, description: str, params: dict[str, float]) -> base.StrategyRun:
85+
gross_returns, weights_history, turnover_history = suite.run_tqqq_growth_income_backtest(
86+
qqq_ohlc,
87+
returns_matrix,
88+
**COMMON_TQQQ_PARAMS,
89+
**params,
90+
)
91+
index = gross_returns.index
92+
return base.StrategyRun(
93+
strategy_name=f"tqqq_growth_income::{name}",
94+
display_name=f"tqqq_growth_income::{name}",
95+
gross_returns=gross_returns,
96+
weights_history=weights_history.reindex(index).fillna(0.0),
97+
turnover_history=turnover_history.reindex(index).fillna(0.0),
98+
metadata={
99+
"family": "tqqq_growth_entry_gate_followup",
100+
"overlay": name,
101+
"overlay_description": description,
102+
"idle_asset": base.SAFE_HAVEN,
103+
"entry_confirm_days": 0,
104+
"exit_confirm_days": 0,
105+
"income_mode": "runtime_full",
106+
},
107+
raw_gate=pd.Series(True, index=index),
108+
active_gate=pd.Series(True, index=index),
109+
)
110+
111+
112+
def build_attack_only_variant(qqq_ohlc: pd.DataFrame, returns_matrix: pd.DataFrame, indicators: pd.DataFrame, *, name: str, description: str, params: dict[str, float]) -> base.StrategyRun:
113+
overlay = base.OverlayConfig(name="baseline", description="Current MA200 + ATR baseline with no extra daily gate.")
114+
run = base.run_attack_only_variant_backtest(
115+
qqq_ohlc,
116+
returns_matrix,
117+
indicators,
118+
config=base.BacktestConfig(overlay=overlay, idle_asset=base.SAFE_HAVEN, income_mode="attack_only"),
119+
**params,
120+
)
121+
run.strategy_name = f"tqqq_attack_only::{name}"
122+
run.display_name = f"tqqq_attack_only::{name}"
123+
run.metadata = {
124+
**run.metadata,
125+
"family": "tqqq_growth_entry_gate_followup",
126+
"overlay": name,
127+
"overlay_description": description,
128+
}
129+
return run
130+
131+
132+
def choose_recommendation(summary: pd.DataFrame) -> dict[str, object]:
133+
focus = summary.loc[(summary["period"] == "2023+") & (summary["cost_bps_one_way"] == 5.0)].copy()
134+
pivot = focus.pivot(index="income_mode", columns="overlay", values=["CAGR", "Max Drawdown", "Information Ratio vs QQQ", "Turnover/Year"])
135+
runtime = focus.loc[focus["income_mode"] == "runtime_full"].set_index("overlay")
136+
attack = focus.loc[focus["income_mode"] == "attack_only"].set_index("overlay")
137+
stress = summary.loc[(summary["period"] == "2022") & (summary["cost_bps_one_way"] == 5.0)].copy()
138+
runtime_stress = stress.loc[stress["income_mode"] == "runtime_full"].set_index("overlay")
139+
attack_stress = stress.loc[stress["income_mode"] == "attack_only"].set_index("overlay")
140+
141+
def delta(frame: pd.DataFrame, metric: str) -> float:
142+
return float(frame.loc["ma200_entry", metric] - frame.loc["current_atr_entry", metric])
143+
144+
recommendation = {
145+
"runtime_full_deltas_ma200_minus_current_2023_plus_5bps": {
146+
"cagr": delta(runtime, "CAGR"),
147+
"max_drawdown": delta(runtime, "Max Drawdown"),
148+
"ir_vs_qqq": delta(runtime, "Information Ratio vs QQQ"),
149+
"turnover_per_year": delta(runtime, "Turnover/Year"),
150+
},
151+
"attack_only_deltas_ma200_minus_current_2023_plus_5bps": {
152+
"cagr": delta(attack, "CAGR"),
153+
"max_drawdown": delta(attack, "Max Drawdown"),
154+
"ir_vs_qqq": delta(attack, "Information Ratio vs QQQ"),
155+
"turnover_per_year": delta(attack, "Turnover/Year"),
156+
},
157+
"runtime_full_deltas_ma200_minus_current_2022_5bps": {
158+
"total_return": delta(runtime_stress, "Total Return"),
159+
"max_drawdown": delta(runtime_stress, "Max Drawdown"),
160+
"turnover_per_year": delta(runtime_stress, "Turnover/Year"),
161+
},
162+
"attack_only_deltas_ma200_minus_current_2022_5bps": {
163+
"total_return": delta(attack_stress, "Total Return"),
164+
"max_drawdown": delta(attack_stress, "Max Drawdown"),
165+
"turnover_per_year": delta(attack_stress, "Turnover/Year"),
166+
},
167+
}
168+
ma200_wins_oos = recommendation["runtime_full_deltas_ma200_minus_current_2023_plus_5bps"]["cagr"] > 0
169+
ma200_hurts_stress = recommendation["runtime_full_deltas_ma200_minus_current_2022_5bps"]["total_return"] < -0.03
170+
recommendation["verdict"] = (
171+
"MA200 direct entry improves the 2023+ rebound but materially worsens the 2022 stress period; do not switch production directly without an extra risk guard."
172+
if ma200_wins_oos and ma200_hurts_stress
173+
else "Keep the current ATR entry gate for production until a stronger variant clears the risk tradeoff."
174+
)
175+
recommendation["pivot_2023_plus_5bps"] = {
176+
f"{metric}::{overlay}": {str(mode): float(value) for mode, value in values.items()}
177+
for (metric, overlay), values in pivot.to_dict().items()
178+
}
179+
return recommendation
180+
181+
182+
def build_markdown(summary: pd.DataFrame, recommendation: dict[str, object]) -> str:
183+
focus = summary.loc[(summary["period"] == "2023+") & (summary["cost_bps_one_way"] == 5.0)].copy()
184+
focus = focus.sort_values(["income_mode", "overlay"])
185+
risk_2022 = summary.loc[(summary["period"] == "2022") & (summary["cost_bps_one_way"] == 5.0)].copy()
186+
risk_2022 = risk_2022.sort_values(["income_mode", "overlay"])
187+
188+
lines = [
189+
"# TQQQ entry-gate follow-up",
190+
"",
191+
"## Setup",
192+
"- Current baseline: flat entry waits for the ATR-adjusted entry line above MA200 (`entry_line_floor=1.02`, `atr_entry_scale=2.5`, cap `1.08`).",
193+
"- Test variant: when flat, enter as soon as QQQ is above MA200 (`entry_line_floor=1.00`, `atr_entry_scale=0.0`, cap `1.00`).",
194+
"- Exit and reduce rules are unchanged.",
195+
"- Both runtime-full and attack-only BOXX variants are included; numbers below use 5 bps one-way turnover cost.",
196+
"",
197+
"## OOS 2023+ (5 bps)",
198+
base.frame_to_markdown_table(
199+
focus[[
200+
"income_mode",
201+
"overlay",
202+
"CAGR",
203+
"Max Drawdown",
204+
"Information Ratio vs QQQ",
205+
"Turnover/Year",
206+
"Average TQQQ Weight",
207+
"TQQQ Days Share",
208+
]]
209+
),
210+
"",
211+
"## 2022 stress period (5 bps)",
212+
base.frame_to_markdown_table(
213+
risk_2022[[
214+
"income_mode",
215+
"overlay",
216+
"Total Return",
217+
"Max Drawdown",
218+
"Turnover/Year",
219+
"Average TQQQ Weight",
220+
"TQQQ Days Share",
221+
]]
222+
),
223+
"",
224+
"## Recommendation",
225+
f"- {recommendation['verdict']}",
226+
]
227+
return "\n".join(lines) + "\n"
228+
229+
230+
def main() -> None:
231+
args = parse_args()
232+
results_dir = Path(args.results_dir).expanduser().resolve()
233+
results_dir.mkdir(parents=True, exist_ok=True)
234+
qqq_ohlc, returns_matrix, indicators = load_market_data(start=args.start, end=args.end)
235+
236+
runs = [
237+
build_runtime_variant(
238+
qqq_ohlc,
239+
returns_matrix,
240+
name="current_atr_entry",
241+
description="Current ATR-adjusted entry line above MA200.",
242+
params=BASELINE_ENTRY_PARAMS,
243+
),
244+
build_runtime_variant(
245+
qqq_ohlc,
246+
returns_matrix,
247+
name="ma200_entry",
248+
description="Enter immediately above MA200 when flat; exits unchanged.",
249+
params=MA200_ENTRY_PARAMS,
250+
),
251+
build_attack_only_variant(
252+
qqq_ohlc,
253+
returns_matrix,
254+
indicators,
255+
name="current_atr_entry",
256+
description="Current ATR-adjusted entry line above MA200.",
257+
params=BASELINE_ENTRY_PARAMS,
258+
),
259+
build_attack_only_variant(
260+
qqq_ohlc,
261+
returns_matrix,
262+
indicators,
263+
name="ma200_entry",
264+
description="Enter immediately above MA200 when flat; exits unchanged.",
265+
params=MA200_ENTRY_PARAMS,
266+
),
267+
]
268+
summary = base.build_summary_rows(runs, returns_matrix["QQQ"], args.cost_bps)
269+
recommendation = choose_recommendation(summary)
270+
271+
comparison_path = results_dir / "tqqq_hybrid_entry_gate_followup_comparison.csv"
272+
summary_path = results_dir / "tqqq_hybrid_entry_gate_followup_summary.md"
273+
recommendation_path = results_dir / "tqqq_hybrid_entry_gate_followup_recommendation.json"
274+
summary.to_csv(comparison_path, index=False)
275+
summary_path.write_text(build_markdown(summary, recommendation), encoding="utf-8")
276+
recommendation_path.write_text(json.dumps(recommendation, indent=2, ensure_ascii=False), encoding="utf-8")
277+
print(json.dumps({"comparison": str(comparison_path), "summary": str(summary_path), "recommendation": str(recommendation_path)}, ensure_ascii=False, indent=2))
278+
279+
280+
if __name__ == "__main__":
281+
main()

0 commit comments

Comments
 (0)