stock-analysis-plugin 0.2.7 → 0.2.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -11
- package/package.json +9 -5
- package/pi/index.ts +268 -6
- package/scripts/setup-python.mjs +11 -4
- package/scripts/venv-python.mjs +7 -0
- package/skills/bull-trend/SKILL.md +11 -1
- package/skills/bull-trend/references/monthly-trend-strategy.md +47 -0
- package/skills/bull-trend/references/trend-horizons.md +43 -0
- package/skills/bull-trend/references/trend-temperature.md +57 -0
- package/skills/bull-trend/scripts/market_trend.py +78 -0
- package/skills/event-driven/SKILL.md +2 -0
- package/skills/market-review/SKILL.md +1 -1
- package/skills/sector-rotation/SKILL.md +57 -0
- package/skills/sector-rotation/references/computation.md +83 -0
- package/skills/sector-rotation/references/strategy_rules.md +62 -0
- package/skills/sector-rotation/scripts/rotation_metrics.py +11 -0
- package/skills/stock-analysis/SKILL.md +5 -2
- package/skills/stock-analysis/references/host-workflows.md +45 -0
- package/skills/stock-screener/SKILL.md +2 -0
- package/skills/strategy-backtest/SKILL.md +12 -0
- package/tools/backtest.py +70 -5
- package/tools/capabilities.py +6 -0
- package/tools/cli_budgets.json +3 -1
- package/tools/report_renderer.py +4 -0
- package/tools/sector_rotation.py +466 -0
- package/tools/technical.py +186 -0
- package/tools/trend_strategy.py +365 -0
package/tools/technical.py
CHANGED
|
@@ -47,6 +47,182 @@ def ema_series(close: pd.Series, period: int) -> pd.Series:
|
|
|
47
47
|
return close.ewm(span=period, adjust=False).mean()
|
|
48
48
|
|
|
49
49
|
|
|
50
|
+
def _trend_prices(df: pd.DataFrame) -> tuple[pd.Series, pd.Series]:
|
|
51
|
+
if "date" not in df or "close" not in df:
|
|
52
|
+
raise ValueError("monthly_momentum requires date and close")
|
|
53
|
+
dates = pd.to_datetime(df["date"], errors="coerce")
|
|
54
|
+
if dates.isna().any() or dates.duplicated().any() or not dates.is_monotonic_increasing:
|
|
55
|
+
raise ValueError("monthly_momentum dates must be valid, unique and increasing")
|
|
56
|
+
close = pd.to_numeric(df["close"], errors="coerce")
|
|
57
|
+
if not np.isfinite(close).all() or (close <= 0).any():
|
|
58
|
+
raise ValueError("monthly_momentum requires finite positive close prices")
|
|
59
|
+
if "adjusted" in df and df["adjusted"].fillna("unknown").astype(str).nunique() > 1:
|
|
60
|
+
raise ValueError("monthly_momentum requires a consistent adjustment basis")
|
|
61
|
+
if "volume" in df:
|
|
62
|
+
volume = pd.to_numeric(df["volume"], errors="coerce")
|
|
63
|
+
if not np.isfinite(volume).all() or (volume < 0).any():
|
|
64
|
+
raise ValueError("monthly_momentum requires finite nonnegative volume")
|
|
65
|
+
close, dates = close[volume > 0], dates[volume > 0]
|
|
66
|
+
return close, dates
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def monthly_momentum_series(df: pd.DataFrame, period: int = 63) -> pd.Series:
|
|
70
|
+
"""Past log return observed on each month's first visible close, then held; never a price forecast."""
|
|
71
|
+
if isinstance(period, bool) or not isinstance(period, int) or period < 1:
|
|
72
|
+
raise ValueError("monthly_momentum requires a positive integer period")
|
|
73
|
+
close, dates = _trend_prices(df)
|
|
74
|
+
month = dates.dt.to_period("M")
|
|
75
|
+
first_bar = month.ne(month.shift())
|
|
76
|
+
return (np.log(close) - np.log(close.shift(period))).where(first_bar).reindex(df.index).ffill()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def monthly_market_entry_series(
|
|
80
|
+
df: pd.DataFrame, market: pd.DataFrame, period: int = 63, *, activation: pd.Timestamp | None = None
|
|
81
|
+
) -> pd.Series:
|
|
82
|
+
"""Monthly entry permission; a weak market never cancels an existing positive stock trend."""
|
|
83
|
+
momentum = monthly_momentum_series(df, period)
|
|
84
|
+
_, dates = _trend_prices(df)
|
|
85
|
+
market_close, market_dates = _trend_prices(market)
|
|
86
|
+
context = pd.DataFrame({"date": market_dates, "allowed": market_close > ma_series(market_close, 200)})
|
|
87
|
+
known = pd.merge_asof(pd.DataFrame({"date": dates}), context, on="date", direction="backward")
|
|
88
|
+
allowed = pd.Series(known.allowed.to_numpy(), index=dates.index).reindex(df.index).eq(True)
|
|
89
|
+
months = dates.dt.to_period("M")
|
|
90
|
+
observe = months.ne(months.shift()).reindex(df.index).eq(True)
|
|
91
|
+
active = pd.to_datetime(df.date).ge(activation) if activation is not None else pd.Series(True, index=df.index)
|
|
92
|
+
if activation is not None:
|
|
93
|
+
observe |= pd.to_datetime(df.date).eq(activation)
|
|
94
|
+
permission = ((momentum > 0) & allowed).astype("boolean").where(observe & active, pd.NA)
|
|
95
|
+
return permission.ffill().where(active & momentum.notna(), pd.NA)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def calc_trend_horizons(df: pd.DataFrame, period: str = "daily") -> dict:
|
|
99
|
+
result = {
|
|
100
|
+
"model": "monthly_momentum",
|
|
101
|
+
"experimental": True,
|
|
102
|
+
"validation_status": "not_validated",
|
|
103
|
+
"as_of": str(df["date"].iloc[-1].date()),
|
|
104
|
+
"history_start": str(df["date"].iloc[0].date()),
|
|
105
|
+
"price_basis": str(df["adjusted"].iloc[-1])
|
|
106
|
+
if "adjusted" in df and pd.notna(df["adjusted"].iloc[-1])
|
|
107
|
+
else "unknown",
|
|
108
|
+
"decision_as_of": None,
|
|
109
|
+
"positive_count": None,
|
|
110
|
+
"negative_count": None,
|
|
111
|
+
"neutral_count": None,
|
|
112
|
+
"direction": None,
|
|
113
|
+
"components": [],
|
|
114
|
+
"unavailable_reason": None,
|
|
115
|
+
"warnings": [
|
|
116
|
+
"Descriptive past-return directions, not probabilities or an automatic allocation. "
|
|
117
|
+
"Observed at each month's first visible daily close; any trade uses a later open. "
|
|
118
|
+
"Need 253 closes at the monthly observation; verify the observation bar is closed. "
|
|
119
|
+
"No stable cross-market trading advantage has been established."
|
|
120
|
+
],
|
|
121
|
+
}
|
|
122
|
+
if period != "daily":
|
|
123
|
+
result["unavailable_reason"] = "requires_daily_bars"
|
|
124
|
+
return result
|
|
125
|
+
try:
|
|
126
|
+
for horizon in (21, 63, 252):
|
|
127
|
+
value = monthly_momentum_series(df, horizon).iloc[-1]
|
|
128
|
+
result["components"].append({"period": horizon, "log_return": float(value) if np.isfinite(value) else None})
|
|
129
|
+
except ValueError as exc:
|
|
130
|
+
result["unavailable_reason"] = str(exc)
|
|
131
|
+
return result
|
|
132
|
+
dates = df.loc[df["volume"] > 0, "date"] if "volume" in df else df["date"]
|
|
133
|
+
month = dates.dt.to_period("M")
|
|
134
|
+
if not dates.empty:
|
|
135
|
+
result["decision_as_of"] = str(dates.loc[month.ne(month.shift())].iloc[-1].date())
|
|
136
|
+
values = [component["log_return"] for component in result["components"]]
|
|
137
|
+
if any(value is None for value in values):
|
|
138
|
+
result["unavailable_reason"] = "insufficient_history_at_monthly_observation"
|
|
139
|
+
return result
|
|
140
|
+
positive = sum(value > 0 for value in values)
|
|
141
|
+
negative = sum(value < 0 for value in values)
|
|
142
|
+
result.update(positive_count=positive, negative_count=negative, neutral_count=3 - positive - negative)
|
|
143
|
+
result["direction"] = (
|
|
144
|
+
"up" if positive >= 2 else "down" if negative >= 2 else "flat" if not positive + negative else "mixed"
|
|
145
|
+
)
|
|
146
|
+
return result
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def trend_score_series(df: pd.DataFrame, fast: int = 20, slow: int = 60, atr_period: int = 14) -> pd.Series:
|
|
150
|
+
"""Causal EMA spread / SMA true range; an independent, uncalibrated research baseline."""
|
|
151
|
+
if any(isinstance(n, bool) or not isinstance(n, int) or n < 1 for n in (fast, slow, atr_period)) or fast >= slow:
|
|
152
|
+
raise ValueError("trend_score requires positive integer periods and fast_period < slow_period")
|
|
153
|
+
if any(field not in df for field in ("high", "low", "close")):
|
|
154
|
+
raise ValueError("trend_score requires high, low and close")
|
|
155
|
+
prices = df[["high", "low", "close"]].apply(pd.to_numeric, errors="coerce")
|
|
156
|
+
if not np.isfinite(prices).all().all() or (prices <= 0).any().any():
|
|
157
|
+
raise ValueError("trend_score requires finite positive prices")
|
|
158
|
+
high, low, close = prices["high"], prices["low"], prices["close"]
|
|
159
|
+
if ((low > close) | (close > high)).any():
|
|
160
|
+
raise ValueError("trend_score requires low <= close <= high")
|
|
161
|
+
if "date" in df:
|
|
162
|
+
dates = pd.to_datetime(df["date"], errors="coerce")
|
|
163
|
+
if dates.isna().any() or dates.duplicated().any() or not dates.is_monotonic_increasing:
|
|
164
|
+
raise ValueError("trend_score dates must be valid, unique and increasing")
|
|
165
|
+
if "adjusted" in df and df["adjusted"].fillna("unknown").astype(str).nunique() > 1:
|
|
166
|
+
raise ValueError("trend_score requires a consistent adjustment basis")
|
|
167
|
+
previous = close.shift(1)
|
|
168
|
+
true_range = pd.concat([high - low, (high - previous).abs(), (low - previous).abs()], axis=1).max(
|
|
169
|
+
axis=1, skipna=False
|
|
170
|
+
)
|
|
171
|
+
atr = true_range.rolling(atr_period).mean()
|
|
172
|
+
score = (ema_series(close, fast) - ema_series(close, slow)) / atr.replace(0, np.nan)
|
|
173
|
+
return score.where(np.arange(len(df)) >= max(slow, atr_period + 1) - 1).replace([np.inf, -np.inf], np.nan)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def calc_trend_temperature(df: pd.DataFrame) -> dict:
|
|
177
|
+
thresholds = [0.5, 1.5, 3.0]
|
|
178
|
+
result = {
|
|
179
|
+
"model": "ema_atr",
|
|
180
|
+
"experimental": True,
|
|
181
|
+
"validation_status": "not_validated",
|
|
182
|
+
"parameters": {"fast_period": 20, "slow_period": 60, "atr_period": 14, "atr_method": "sma_true_range"},
|
|
183
|
+
"thresholds": thresholds,
|
|
184
|
+
"price_basis": str(df["adjusted"].iloc[-1])
|
|
185
|
+
if "adjusted" in df and pd.notna(df["adjusted"].iloc[-1])
|
|
186
|
+
else "unknown",
|
|
187
|
+
"history_start": str(df["date"].iloc[0].date()),
|
|
188
|
+
"score": None,
|
|
189
|
+
"state": None,
|
|
190
|
+
"direction": None,
|
|
191
|
+
"previous_score": None,
|
|
192
|
+
"previous_state": None,
|
|
193
|
+
"previous_direction": None,
|
|
194
|
+
"transition": None,
|
|
195
|
+
"as_of": str(df["date"].iloc[-1].date()),
|
|
196
|
+
"previous_as_of": str(df["date"].iloc[-2].date()) if len(df) > 1 else None,
|
|
197
|
+
"unavailable_reason": None,
|
|
198
|
+
"warnings": [
|
|
199
|
+
"Independent research baseline, not Trend Animal temperature or a Taleb fat-tail metric. "
|
|
200
|
+
"Thresholds are uncalibrated, not probabilities or automatic trade signals. "
|
|
201
|
+
"State labels are not entry rules; direction is only the EMA-spread sign. "
|
|
202
|
+
"EMA initialization depends on the supplied history; periods count bars, not calendar days. "
|
|
203
|
+
"Verify the latest bar is closed and the OHLC adjustment basis is consistent."
|
|
204
|
+
],
|
|
205
|
+
}
|
|
206
|
+
try:
|
|
207
|
+
scores = trend_score_series(df)
|
|
208
|
+
except ValueError as exc:
|
|
209
|
+
result["unavailable_reason"] = str(exc)
|
|
210
|
+
return result
|
|
211
|
+
for prefix, idx in (("", -1), ("previous_", -2)):
|
|
212
|
+
if len(scores) < abs(idx) or not np.isfinite(scores.iloc[idx]):
|
|
213
|
+
continue
|
|
214
|
+
value = float(scores.iloc[idx])
|
|
215
|
+
magnitude = sum(abs(value) > threshold for threshold in thresholds)
|
|
216
|
+
result[f"{prefix}score"] = value
|
|
217
|
+
result[f"{prefix}direction"] = "up" if value > 0 else "down" if value < 0 else "flat"
|
|
218
|
+
result[f"{prefix}state"] = (("平", "温", "热", "沸") if value >= 0 else ("平", "凉", "寒", "冻"))[magnitude]
|
|
219
|
+
if result["score"] is None:
|
|
220
|
+
result["unavailable_reason"] = "insufficient_history" if len(df) < 60 else "zero_or_nonfinite_atr_or_score"
|
|
221
|
+
elif result["previous_state"] is not None and result["previous_state"] != result["state"]:
|
|
222
|
+
result["transition"] = f"{result['previous_state']}→{result['state']}"
|
|
223
|
+
return result
|
|
224
|
+
|
|
225
|
+
|
|
50
226
|
def macd_series(close: pd.Series) -> tuple:
|
|
51
227
|
"""Full (dif, dea, macd) series: dif = EMA12-EMA26, dea = EMA9(dif), macd = 2*(dif-dea)."""
|
|
52
228
|
dif = ema_series(close, 12) - ema_series(close, 26)
|
|
@@ -599,6 +775,14 @@ def _period_summary(result: dict) -> dict:
|
|
|
599
775
|
return {
|
|
600
776
|
"period": result["period"],
|
|
601
777
|
"trend_overall": result["trend"]["overall"],
|
|
778
|
+
"trend_score": result["trend_temperature"]["score"],
|
|
779
|
+
"trend_temperature_state": result["trend_temperature"]["state"],
|
|
780
|
+
"trend_temperature_direction": result["trend_temperature"]["direction"],
|
|
781
|
+
"trend_temperature_validation_status": result["trend_temperature"]["validation_status"],
|
|
782
|
+
"trend_temperature_as_of": result["trend_temperature"]["as_of"],
|
|
783
|
+
"trend_temperature_price_basis": result["trend_temperature"]["price_basis"],
|
|
784
|
+
"trend_temperature_unavailable_reason": result["trend_temperature"]["unavailable_reason"],
|
|
785
|
+
"trend_horizons": result["trend_horizons"],
|
|
602
786
|
"ma_arrangement": result["moving_averages"]["ma_arrangement"],
|
|
603
787
|
"macd_signal": result["macd"]["signal"],
|
|
604
788
|
"rsi_signal": result["rsi"]["signal"],
|
|
@@ -697,6 +881,8 @@ def analyze_records(symbol: str, records: list, period: str = "daily") -> dict:
|
|
|
697
881
|
"volume": vol_data,
|
|
698
882
|
"support_resistance": sr_data,
|
|
699
883
|
"trend": trend_data,
|
|
884
|
+
"trend_temperature": calc_trend_temperature(df),
|
|
885
|
+
"trend_horizons": calc_trend_horizons(df, period),
|
|
700
886
|
"bias": bias_data,
|
|
701
887
|
"signal_score": score_data["signal_score"],
|
|
702
888
|
"buy_signal": score_data["buy_signal"],
|
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Stateless monthly signal plans with SMA200 eligibility and volatility budgets."""
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import re
|
|
8
|
+
import stat
|
|
9
|
+
import sys
|
|
10
|
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
import pandas as pd
|
|
15
|
+
|
|
16
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
17
|
+
|
|
18
|
+
from _subproc import run_tool, utf8_stdio
|
|
19
|
+
from stock_data import detect_market
|
|
20
|
+
from technical import _trend_prices, ma_series
|
|
21
|
+
|
|
22
|
+
MODEL = "sma200_risk_budget"
|
|
23
|
+
ALLOCATION = 0.8704
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def iso_date(value):
|
|
27
|
+
if not isinstance(value, str) or not re.fullmatch(r"\d{4}-\d{2}-\d{2}", value):
|
|
28
|
+
raise ValueError("as_of and price dates require YYYY-MM-DD")
|
|
29
|
+
day = pd.Timestamp(value)
|
|
30
|
+
if pd.isna(day) or str(day.date()) != value:
|
|
31
|
+
raise ValueError("Invalid date")
|
|
32
|
+
return day
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def symbol_set(payload, key, names):
|
|
36
|
+
values = payload.get(key, [])
|
|
37
|
+
if not isinstance(values, list) or any(type(n) is not str for n in values):
|
|
38
|
+
raise ValueError(f"{key} must be a list of unique pool symbols")
|
|
39
|
+
if len(values) != len(set(values)) or not set(values) <= names:
|
|
40
|
+
raise ValueError(f"{key} must contain unique pool symbols")
|
|
41
|
+
return set(values)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def symbol_identity(name, market):
|
|
45
|
+
return int(name[:-3]) if market == "HK" else name.replace(".", "-")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def pool_members(symbols, market):
|
|
49
|
+
patterns = {"A": r"\d{6}", "HK": r"\d{4,5}\.HK", "US": r"[A-Z][A-Z0-9.-]{0,14}"}
|
|
50
|
+
if market not in patterns:
|
|
51
|
+
raise ValueError("Rule62 supports a single A, HK or US stock pool")
|
|
52
|
+
if not isinstance(symbols, list) or not 1 <= len(symbols) <= 100:
|
|
53
|
+
raise ValueError("A pool requires 1..100 distinct stocks")
|
|
54
|
+
if any(type(n) is not str or not re.fullmatch(patterns[market], n) or detect_market(n) != market for n in symbols):
|
|
55
|
+
raise ValueError("Symbols must be stocks from the declared single market")
|
|
56
|
+
names = sorted(symbols, key=lambda n: symbol_identity(n, market))
|
|
57
|
+
if len({symbol_identity(n, market) for n in names}) != len(names):
|
|
58
|
+
raise ValueError("Duplicate symbol aliases")
|
|
59
|
+
return names
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def pool_state(payload, names):
|
|
63
|
+
held = symbol_set(payload, "held_symbols", set(names))
|
|
64
|
+
pending = symbol_set(payload, "pending_exit_symbols", set(names))
|
|
65
|
+
if not pending <= held:
|
|
66
|
+
raise ValueError("pending_exit_symbols must be real held_symbols")
|
|
67
|
+
slots = payload.get("slots", math.ceil(len(names) / 3))
|
|
68
|
+
if type(slots) not in (int, float) or not 1 <= slots <= len(names) or int(slots) != slots or len(held) > slots:
|
|
69
|
+
raise ValueError("slots requires an integer in 1..N and cannot be below actual held count")
|
|
70
|
+
return held, pending, int(slots)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def analyze(payload):
|
|
74
|
+
allowed = {"market", "as_of", "histories", "slots", "held_symbols", "pending_exit_symbols"}
|
|
75
|
+
if not isinstance(payload, dict) or set(payload) - allowed:
|
|
76
|
+
raise ValueError("Expected strategy input with only documented fields; corporate actions are not supported")
|
|
77
|
+
market = payload["market"]
|
|
78
|
+
as_of = iso_date(payload["as_of"])
|
|
79
|
+
histories = payload["histories"]
|
|
80
|
+
if not isinstance(histories, dict):
|
|
81
|
+
raise ValueError("histories requires distinct stocks")
|
|
82
|
+
names = pool_members(list(histories), market)
|
|
83
|
+
held, pending, slots = pool_state(payload, names)
|
|
84
|
+
stocks, calendar, known_vol = {}, set(), {}
|
|
85
|
+
for name in names:
|
|
86
|
+
records = histories[name]
|
|
87
|
+
if not isinstance(records, list) or not 1 <= len(records) <= 20000:
|
|
88
|
+
raise ValueError("Each history requires 1..20000 dated price rows")
|
|
89
|
+
for row in records:
|
|
90
|
+
if not isinstance(row, dict) or not {"date", "close", "volume"} <= row.keys():
|
|
91
|
+
raise ValueError("Each price row requires date, close and volume")
|
|
92
|
+
iso_date(row["date"])
|
|
93
|
+
if any(type(row[k]) not in (int, float) for k in ("close", "volume")):
|
|
94
|
+
raise ValueError("close and volume must be numbers, excluding booleans")
|
|
95
|
+
frame = pd.DataFrame(records)
|
|
96
|
+
frame["date"] = pd.to_datetime(frame.date)
|
|
97
|
+
# Validate chronology before cutting the prefix; never silently sort duplicate/bad input.
|
|
98
|
+
_trend_prices(frame)
|
|
99
|
+
frame = frame.loc[frame.date <= as_of]
|
|
100
|
+
if frame.empty:
|
|
101
|
+
raise ValueError("Every pool member needs history at or before as_of")
|
|
102
|
+
close, dates = _trend_prices(frame)
|
|
103
|
+
calendar.update(dates)
|
|
104
|
+
average = ma_series(close, 200)
|
|
105
|
+
returns = np.log(close).diff()
|
|
106
|
+
sigma = returns.rolling(63).std(ddof=1)
|
|
107
|
+
sigma = sigma.mask(returns.rolling(63).min().eq(returns.rolling(63).max()), 0.0)
|
|
108
|
+
available = not dates.empty and dates.iloc[-1] == as_of
|
|
109
|
+
|
|
110
|
+
def last(series, available=available):
|
|
111
|
+
value = series.iloc[-1] if available and not series.empty else np.nan
|
|
112
|
+
return float(value) if np.isfinite(value) else None
|
|
113
|
+
|
|
114
|
+
score = last(np.log(close) - np.log(average))
|
|
115
|
+
volatility = last(sigma)
|
|
116
|
+
if volatility is not None and volatility > 0:
|
|
117
|
+
known_vol[name] = volatility
|
|
118
|
+
basis = str(frame.adjusted.iloc[-1]) if "adjusted" in frame and pd.notna(frame.adjusted.iloc[-1]) else "unknown"
|
|
119
|
+
stocks[name] = {
|
|
120
|
+
"quote_available": bool(available),
|
|
121
|
+
"quote_as_of": str(dates.iloc[-1].date()) if not dates.empty else None,
|
|
122
|
+
"price_basis": basis,
|
|
123
|
+
"valid_bars": len(close),
|
|
124
|
+
"close": last(close),
|
|
125
|
+
"sma200": last(average),
|
|
126
|
+
"sma200_21_bars_ago": last(average.shift(21)),
|
|
127
|
+
"distance": score,
|
|
128
|
+
"sigma63": volatility,
|
|
129
|
+
"rising_sma200": bool(available and len(close) >= 221 and average.iloc[-1] > average.shift(21).iloc[-1]),
|
|
130
|
+
"new_entry_eligible": False,
|
|
131
|
+
"action": "wait",
|
|
132
|
+
"reason": "not_monthly_observation",
|
|
133
|
+
"new_budget_fraction": 0.0,
|
|
134
|
+
}
|
|
135
|
+
stocks[name]["new_entry_eligible"] = bool(
|
|
136
|
+
score is not None and score > 0 and stocks[name]["rising_sma200"] and name in known_vol
|
|
137
|
+
)
|
|
138
|
+
month_dates = [day for day in calendar if day.to_period("M") == as_of.to_period("M")]
|
|
139
|
+
monthly = bool(month_dates and min(month_dates) == as_of)
|
|
140
|
+
selected = []
|
|
141
|
+
reference = float(np.median(list(known_vol.values()))) if known_vol else None
|
|
142
|
+
insufficient_held = any(stocks[n]["quote_available"] and stocks[n]["sma200"] is None for n in held - pending)
|
|
143
|
+
status = "monthly_observation" if monthly else "waiting_for_monthly_observation"
|
|
144
|
+
if insufficient_held:
|
|
145
|
+
status = "insufficient_held_history"
|
|
146
|
+
if monthly and not insufficient_held:
|
|
147
|
+
retained = [
|
|
148
|
+
n for n in names if n in held - pending and (not stocks[n]["quote_available"] or stocks[n]["distance"] > 0)
|
|
149
|
+
]
|
|
150
|
+
ranked = sorted(
|
|
151
|
+
(n for n in names if n not in held and stocks[n]["new_entry_eligible"]),
|
|
152
|
+
key=lambda n: (-stocks[n]["distance"], symbol_identity(n, market)),
|
|
153
|
+
)
|
|
154
|
+
selected = retained + ranked[: max(0, slots - len(retained))]
|
|
155
|
+
for name, row in stocks.items():
|
|
156
|
+
if name in retained:
|
|
157
|
+
row.update(
|
|
158
|
+
action="hold",
|
|
159
|
+
reason="positive_stock_trend" if row["quote_available"] else "unobservable_held_reserves_slot",
|
|
160
|
+
)
|
|
161
|
+
elif name in held - pending:
|
|
162
|
+
row.update(action="exit_next_valid_open", reason="monthly_sma200_nonpositive")
|
|
163
|
+
elif name in selected:
|
|
164
|
+
row.update(
|
|
165
|
+
action="entry_candidate_next_valid_open",
|
|
166
|
+
reason="rising_sma200_ranked_vacancy",
|
|
167
|
+
new_budget_fraction=ALLOCATION / slots * min(1.0, reference / known_vol[name]),
|
|
168
|
+
)
|
|
169
|
+
else:
|
|
170
|
+
row["reason"] = "capacity_reserved" if row["new_entry_eligible"] else "entry_conditions_not_met"
|
|
171
|
+
for name in pending:
|
|
172
|
+
stocks[name].update(action="exit_pending", reason="previously_locked_exit")
|
|
173
|
+
return {
|
|
174
|
+
"model": MODEL,
|
|
175
|
+
"validation_status": "not_validated",
|
|
176
|
+
"kind": "monthly_signal_plan",
|
|
177
|
+
"market": market,
|
|
178
|
+
"as_of": str(as_of.date()),
|
|
179
|
+
"status": status,
|
|
180
|
+
"observation_date": str(as_of.date()) if monthly else None,
|
|
181
|
+
"last_available_date": str(max(calendar).date()) if calendar else None,
|
|
182
|
+
"portfolio_state": "explicit_held_symbols" if held else "initially_flat",
|
|
183
|
+
"slots": slots,
|
|
184
|
+
"allocation": ALLOCATION,
|
|
185
|
+
"reference_volatility": reference,
|
|
186
|
+
"selected": selected,
|
|
187
|
+
"stocks": stocks,
|
|
188
|
+
"execution": {
|
|
189
|
+
"requires_available_cash_and_capacity": True,
|
|
190
|
+
"budget_basis": "next_execution_batch_open_nav_times_new_budget_fraction_including_buy_costs",
|
|
191
|
+
"budget_is_not_target_weight": True,
|
|
192
|
+
"existing_holdings_are_not_resized": True,
|
|
193
|
+
"sell_before_buy": True,
|
|
194
|
+
"fills_or_quantities_calculated": False,
|
|
195
|
+
},
|
|
196
|
+
"validation": {
|
|
197
|
+
"development_gates": "passed",
|
|
198
|
+
"expanded_and_historical_pools": "failed",
|
|
199
|
+
"independent_validation": "not_completed",
|
|
200
|
+
},
|
|
201
|
+
"warnings": [
|
|
202
|
+
"Caller must provide complete daily history through a closed as_of bar, consistent adjusted prices and the real holdings at as_of. Missing pool members change ranking and the volatility median.",
|
|
203
|
+
"Only the first observed positive-volume stock-pool close of the month creates new plans. Mid-month output does not replay past decisions or reconstruct orders.",
|
|
204
|
+
"Budgets are conditional cash limits, not share quantities, target weights or fills. Locked exits require actual execution before cash/capacity is reused; no daily re-entry or averaging down.",
|
|
205
|
+
"Corporate-action conversion, raw-share lots, settlement, trading limits and fees require separate execution checks. No account is stored and no orders are submitted.",
|
|
206
|
+
"Development gates passed only on the development sample. Expanded and historical pools failed; allocation .8704 was fitted. This is not the private Trend Animal temperature or a forecast of fat-tail returns.",
|
|
207
|
+
],
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def latest_closed_date(market, now=None):
|
|
212
|
+
import exchange_calendars as xcals
|
|
213
|
+
|
|
214
|
+
calendar = xcals.get_calendar({"A": "XSHG", "HK": "XHKG", "US": "XNYS"}[market])
|
|
215
|
+
now = pd.Timestamp.now(tz="UTC") if now is None else pd.Timestamp(now)
|
|
216
|
+
if now.tzinfo is None:
|
|
217
|
+
raise ValueError("Current time must include a timezone")
|
|
218
|
+
local_date = str(now.tz_convert(calendar.tz).date())
|
|
219
|
+
session = calendar.date_to_session(local_date, direction="previous")
|
|
220
|
+
# XHKG calendars end continuous trading; its closing auction can run ten more minutes.
|
|
221
|
+
close = calendar.session_close(session) + pd.Timedelta(minutes=10 if market == "HK" else 0)
|
|
222
|
+
if now <= close:
|
|
223
|
+
session = calendar.previous_session(session)
|
|
224
|
+
return str(session.date())
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def request_symbol(name):
|
|
228
|
+
name = name.strip().upper()
|
|
229
|
+
if re.fullmatch(r"\d{4,5}\.HK", name):
|
|
230
|
+
return f"{int(name[:-3]):04d}.HK"
|
|
231
|
+
return name.replace(".", "-") if detect_market(name) == "US" else name
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _fetch_daily_history(symbol, count):
|
|
235
|
+
return run_tool("stock_data.py", ["kline", symbol, "--period", "daily", "--count", str(count)], timeout=30)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def fetch_plan(request):
|
|
239
|
+
allowed = {"symbols", "as_of", "held_symbols", "pending_exit_symbols", "slots"}
|
|
240
|
+
if not isinstance(request, dict) or set(request) - allowed:
|
|
241
|
+
raise ValueError("Expected symbols and optional as_of/held_symbols/pending_exit_symbols/slots")
|
|
242
|
+
symbols = request["symbols"]
|
|
243
|
+
if not isinstance(symbols, list) or not 1 <= len(symbols) <= 100 or any(type(n) is not str for n in symbols):
|
|
244
|
+
raise ValueError("symbols must be a nonempty list of stock codes")
|
|
245
|
+
symbols = [request_symbol(n) for n in symbols]
|
|
246
|
+
markets = {detect_market(n) for n in symbols}
|
|
247
|
+
if len(markets) != 1:
|
|
248
|
+
raise ValueError("A pool must contain a single market")
|
|
249
|
+
market = markets.pop()
|
|
250
|
+
names = pool_members(symbols, market)
|
|
251
|
+
state = {}
|
|
252
|
+
for key in ("held_symbols", "pending_exit_symbols"):
|
|
253
|
+
values = request.get(key, [])
|
|
254
|
+
if not isinstance(values, list) or any(type(n) is not str for n in values):
|
|
255
|
+
raise ValueError("Held and pending symbols require lists of codes")
|
|
256
|
+
state[key] = [request_symbol(n) for n in values]
|
|
257
|
+
if "slots" in request:
|
|
258
|
+
state["slots"] = request["slots"]
|
|
259
|
+
pool_state(state, names)
|
|
260
|
+
try:
|
|
261
|
+
closed = latest_closed_date(market)
|
|
262
|
+
except Exception:
|
|
263
|
+
return {
|
|
264
|
+
"error": "Exchange calendar unavailable; cannot identify a completed daily bar",
|
|
265
|
+
"error_code": "calendar_unavailable",
|
|
266
|
+
}
|
|
267
|
+
as_of = iso_date(request.get("as_of", closed))
|
|
268
|
+
if as_of > iso_date(closed):
|
|
269
|
+
raise ValueError("as_of must not be later than the most recently completed exchange session")
|
|
270
|
+
count = 360 + (iso_date(closed) - as_of).days
|
|
271
|
+
if count > 20000 or count * len(names) > 200000:
|
|
272
|
+
raise ValueError("Requested date exceeds the supported price history")
|
|
273
|
+
histories, failed = {}, []
|
|
274
|
+
with ThreadPoolExecutor(max_workers=min(6, len(names))) as pool:
|
|
275
|
+
futures = {pool.submit(_fetch_daily_history, name, count): name for name in names}
|
|
276
|
+
for future in as_completed(futures):
|
|
277
|
+
name = futures[future]
|
|
278
|
+
try:
|
|
279
|
+
records = future.result()
|
|
280
|
+
except Exception:
|
|
281
|
+
records = None
|
|
282
|
+
if not isinstance(records, list) or not records or len(records) > count:
|
|
283
|
+
failed.append(name)
|
|
284
|
+
else:
|
|
285
|
+
histories[name] = records
|
|
286
|
+
if failed:
|
|
287
|
+
return {
|
|
288
|
+
"error": "Cannot load the complete stock pool; no strategy plan was produced",
|
|
289
|
+
"error_code": "incomplete_pool",
|
|
290
|
+
"failed_symbols": sorted(failed),
|
|
291
|
+
}
|
|
292
|
+
try:
|
|
293
|
+
result = analyze({"market": market, "as_of": str(as_of.date()), "histories": histories, **state})
|
|
294
|
+
except (KeyError, TypeError, ValueError, OverflowError):
|
|
295
|
+
return {
|
|
296
|
+
"error": "Fetched daily prices failed validation; no strategy plan was produced",
|
|
297
|
+
"error_code": "invalid_market_data",
|
|
298
|
+
}
|
|
299
|
+
result["data_acquisition"] = {
|
|
300
|
+
"source": "stock_data.py:kline",
|
|
301
|
+
"symbols": names,
|
|
302
|
+
"requested_count": count,
|
|
303
|
+
"latest_closed_session": closed,
|
|
304
|
+
}
|
|
305
|
+
result["warnings"][0] = (
|
|
306
|
+
"Daily histories were fetched for the entire requested pool. Verify provider adjustment and quote dates; held_symbols must describe real holdings at as_of."
|
|
307
|
+
)
|
|
308
|
+
return result
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def unique_object(pairs):
|
|
312
|
+
result = {}
|
|
313
|
+
for key, value in pairs:
|
|
314
|
+
if key in result:
|
|
315
|
+
raise ValueError("Duplicate JSON object key")
|
|
316
|
+
result[key] = value
|
|
317
|
+
return result
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
class Parser(argparse.ArgumentParser):
|
|
321
|
+
def error(self, message):
|
|
322
|
+
raise ValueError(message)
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def main():
|
|
326
|
+
utf8_stdio()
|
|
327
|
+
parser = Parser(description=__doc__)
|
|
328
|
+
parser.add_argument(
|
|
329
|
+
"action", nargs="?", choices=["fetch"], help="Fetch prices from stock codes; omit only for offline snapshots"
|
|
330
|
+
)
|
|
331
|
+
parser.add_argument("--input", required=True, help="Internal UTF-8 request JSON or offline snapshot file")
|
|
332
|
+
try:
|
|
333
|
+
args = parser.parse_args()
|
|
334
|
+
except ValueError:
|
|
335
|
+
print(
|
|
336
|
+
json.dumps({"error": "Invalid command arguments; use --help for usage", "error_code": "invalid_arguments"})
|
|
337
|
+
)
|
|
338
|
+
return 1
|
|
339
|
+
try:
|
|
340
|
+
path = Path(args.input)
|
|
341
|
+
info = path.stat()
|
|
342
|
+
limit = 32 * 1024 * 1024
|
|
343
|
+
if not stat.S_ISREG(info.st_mode) or info.st_size > limit:
|
|
344
|
+
raise ValueError("Input requires a regular JSON file up to 32 MiB")
|
|
345
|
+
with path.open("rb") as source:
|
|
346
|
+
raw = source.read(limit + 1)
|
|
347
|
+
if len(raw) > limit:
|
|
348
|
+
raise ValueError("Input JSON exceeds 32 MiB")
|
|
349
|
+
payload = json.loads(raw.decode("utf-8"), object_pairs_hook=unique_object)
|
|
350
|
+
result = fetch_plan(payload) if args.action == "fetch" else analyze(payload)
|
|
351
|
+
except (KeyError, TypeError, ValueError, OverflowError, RecursionError):
|
|
352
|
+
result = {
|
|
353
|
+
"error": "Invalid stock-pool request; use one market and check codes, dates, holdings and slots"
|
|
354
|
+
if args.action == "fetch"
|
|
355
|
+
else "Invalid trend strategy input; check documented dates, symbols, prices, holdings and slots",
|
|
356
|
+
"error_code": "invalid_request" if args.action == "fetch" else "invalid_snapshot",
|
|
357
|
+
}
|
|
358
|
+
except OSError:
|
|
359
|
+
result = {"error": "Cannot read trend strategy input JSON file"}
|
|
360
|
+
print(json.dumps(result, ensure_ascii=False, allow_nan=False))
|
|
361
|
+
return 1 if "error" in result else 0
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
if __name__ == "__main__":
|
|
365
|
+
raise SystemExit(main())
|