stock-analysis-plugin 0.2.8 → 0.2.10
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 +34 -26
- package/package.json +15 -8
- package/pi/index.ts +446 -13
- package/scripts/profile-offline.py +127 -0
- package/scripts/profile-workflows.py +87 -0
- package/scripts/setup-python.mjs +11 -4
- package/scripts/venv-python.mjs +7 -0
- package/skills/event-driven/SKILL.md +2 -0
- package/skills/growth-quality/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 +15 -4
- package/skills/stock-analysis/references/host-workflows.md +45 -0
- package/skills/stock-analysis/references/stateless-analysis.md +16 -2
- package/skills/stock-screener/SKILL.md +6 -0
- package/skills/strategy-backtest/SKILL.md +10 -3
- package/tools/_cache.py +93 -21
- package/tools/_subproc.py +43 -8
- package/tools/anomaly_detect.py +11 -6
- package/tools/backtest.py +225 -70
- package/tools/capabilities.py +3 -0
- package/tools/cli_budgets.json +2 -1
- package/tools/gather.py +63 -8
- package/tools/market_regime.py +26 -15
- package/tools/market_review.py +2 -2
- package/tools/position_context.py +5 -2
- package/tools/report_renderer.py +4 -0
- package/tools/requirements.txt +2 -2
- package/tools/risk_screening.py +40 -15
- package/tools/screener.py +44 -18
- package/tools/search_intel.py +94 -32
- package/tools/sec_holders.py +27 -25
- package/tools/sector_rotation.py +466 -0
- package/tools/signal_tracker.py +100 -49
- package/tools/stateless_analysis.py +600 -33
- package/tools/stock_data.py +111 -26
- package/tools/technical.py +42 -40
- package/tools/trading_calendar.py +26 -21
- package/tools/value_data.py +6 -2
- package/tools/watchlist.py +24 -15
- package/tools/watchlist_context.py +63 -49
package/tools/stock_data.py
CHANGED
|
@@ -16,7 +16,7 @@ from pathlib import Path
|
|
|
16
16
|
from zoneinfo import ZoneInfo
|
|
17
17
|
|
|
18
18
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
19
|
-
from _cache import DAY, WEEK, cached # noqa: E402
|
|
19
|
+
from _cache import DAY, WEEK, atomic_write, cached # noqa: E402
|
|
20
20
|
from _subproc import run_tool, scrub_secrets, socket_timeout, utf8_stdio # noqa: E402
|
|
21
21
|
|
|
22
22
|
# Explicitly exchange-prefixed A-share codes (sh600519 / sz000858 / bj920001).
|
|
@@ -71,11 +71,12 @@ def normalize_stock_code(symbol: str) -> dict:
|
|
|
71
71
|
|
|
72
72
|
|
|
73
73
|
def calc_limit_price(pre_close: float, ratio: float, direction: str = "up") -> float:
|
|
74
|
-
"""Calculate limit-up or limit-down price with
|
|
75
|
-
import
|
|
74
|
+
"""Calculate limit-up or limit-down price with decimal round-half-up."""
|
|
75
|
+
from decimal import ROUND_HALF_UP, Decimal
|
|
76
76
|
|
|
77
77
|
sign = 1 if direction == "up" else -1
|
|
78
|
-
|
|
78
|
+
price = Decimal(str(pre_close)) * (1 + sign * Decimal(str(ratio)))
|
|
79
|
+
return float(price.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))
|
|
79
80
|
|
|
80
81
|
|
|
81
82
|
# Chains that get sticky ordering: the CN free-source chains, where failures are
|
|
@@ -145,8 +146,37 @@ def _akshare_retry(fn, *args, retries=2, delay=1, **kwargs):
|
|
|
145
146
|
for attempt in range(retries + 1):
|
|
146
147
|
try:
|
|
147
148
|
return fn(*args, **kwargs)
|
|
148
|
-
except Exception:
|
|
149
|
-
|
|
149
|
+
except Exception as exc:
|
|
150
|
+
from requests.exceptions import ChunkedEncodingError, HTTPError, Timeout
|
|
151
|
+
from requests.exceptions import ConnectionError as RequestsConnectionError
|
|
152
|
+
from requests.exceptions import JSONDecodeError as RequestsJSONDecodeError
|
|
153
|
+
|
|
154
|
+
transport_errors = (
|
|
155
|
+
ConnectionError,
|
|
156
|
+
TimeoutError,
|
|
157
|
+
RequestsConnectionError,
|
|
158
|
+
Timeout,
|
|
159
|
+
ChunkedEncodingError,
|
|
160
|
+
RequestsJSONDecodeError,
|
|
161
|
+
json.JSONDecodeError,
|
|
162
|
+
)
|
|
163
|
+
http_errors = (HTTPError,)
|
|
164
|
+
if type(exc).__module__.startswith("curl_cffi."):
|
|
165
|
+
from curl_cffi.requests.exceptions import ConnectionError as CurlConnectionError
|
|
166
|
+
from curl_cffi.requests.exceptions import HTTPError as CurlHTTPError
|
|
167
|
+
from curl_cffi.requests.exceptions import Timeout as CurlTimeout
|
|
168
|
+
|
|
169
|
+
transport_errors += (CurlConnectionError, CurlTimeout)
|
|
170
|
+
http_errors += (CurlHTTPError,)
|
|
171
|
+
transient = isinstance(exc, transport_errors)
|
|
172
|
+
if isinstance(exc, http_errors):
|
|
173
|
+
status = getattr(exc.response, "status_code", None)
|
|
174
|
+
transient = status in (408, 429) or isinstance(status, int) and 500 <= status < 600
|
|
175
|
+
if type(exc).__module__.startswith("yfinance."):
|
|
176
|
+
from yfinance import exceptions as yf_errors
|
|
177
|
+
|
|
178
|
+
transient = isinstance(exc, getattr(yf_errors, "YFRateLimitError", ()))
|
|
179
|
+
if not transient or attempt == retries:
|
|
150
180
|
raise
|
|
151
181
|
time.sleep(delay)
|
|
152
182
|
|
|
@@ -260,6 +290,7 @@ def _quote_efinance(symbol: str) -> dict:
|
|
|
260
290
|
with contextlib.suppress(ValueError, TypeError):
|
|
261
291
|
val = float(val) if en_key not in ("symbol", "name") else val
|
|
262
292
|
result[en_key] = val
|
|
293
|
+
result["pe_basis"] = "dynamic"
|
|
263
294
|
return _clean_row(result)
|
|
264
295
|
|
|
265
296
|
|
|
@@ -328,6 +359,7 @@ def _tencent_payload_row(f: list, symbol: str) -> dict:
|
|
|
328
359
|
"prev_close": _parse_float(f[4]),
|
|
329
360
|
"market_cap": market_cap * 1e8 if market_cap is not None else None,
|
|
330
361
|
"pe": _parse_float(f[39]),
|
|
362
|
+
"pe_basis": "unknown",
|
|
331
363
|
# Tencent's HK map labels f[47] DY and f[49] WK52_Low; neither is an A-share ratio.
|
|
332
364
|
"pb": None if hk else _parse_float(f[46]),
|
|
333
365
|
"turnover_rate": None if hk else _parse_float(f[38]),
|
|
@@ -626,6 +658,9 @@ def _kline_tushare(symbol: str, period: str, count: int) -> list:
|
|
|
626
658
|
df = df.rename(columns={f"{c}_qfq": c for c in prices})
|
|
627
659
|
if not df[prices].abs().lt(float("inf")).all().all():
|
|
628
660
|
raise ValueError("tushare returned invalid adjusted prices")
|
|
661
|
+
df["trade_date"] = pd.to_datetime(df["trade_date"], format="%Y%m%d")
|
|
662
|
+
if "amount" in df.columns:
|
|
663
|
+
df["amount"] = pd.to_numeric(df["amount"], errors="coerce") * 1000
|
|
629
664
|
col_map = {"trade_date": "date", "vol": "volume", "amount": "turnover", "pct_chg": "change_pct"}
|
|
630
665
|
df = df.rename(columns=col_map)
|
|
631
666
|
df = df.sort_values("date")
|
|
@@ -798,7 +833,7 @@ def _kline_finnhub(symbol: str, period: str, count: int) -> list:
|
|
|
798
833
|
rows.append(
|
|
799
834
|
_clean_row(
|
|
800
835
|
{
|
|
801
|
-
"date": datetime.fromtimestamp(candles["t"][i]).strftime("%Y-%m-%d"),
|
|
836
|
+
"date": datetime.fromtimestamp(candles["t"][i], timezone.utc).strftime("%Y-%m-%d"),
|
|
802
837
|
"open": candles["o"][i],
|
|
803
838
|
"high": candles["h"][i],
|
|
804
839
|
"low": candles["l"][i],
|
|
@@ -1130,6 +1165,7 @@ def _quote_akshare(symbol: str) -> dict:
|
|
|
1130
1165
|
"prev_close": r.get("昨收"),
|
|
1131
1166
|
"market_cap": r.get("总市值"),
|
|
1132
1167
|
"pe": r.get("市盈率-动态"),
|
|
1168
|
+
"pe_basis": "dynamic",
|
|
1133
1169
|
"pb": r.get("市净率"),
|
|
1134
1170
|
"turnover_rate": r.get("换手率"),
|
|
1135
1171
|
"volume_ratio": r.get("量比"),
|
|
@@ -1161,6 +1197,7 @@ def _quote_yfinance(symbol: str) -> dict:
|
|
|
1161
1197
|
"prev_close": info.get("regularMarketPreviousClose"),
|
|
1162
1198
|
"market_cap": info.get("marketCap"),
|
|
1163
1199
|
"pe": info.get("trailingPE"),
|
|
1200
|
+
"pe_basis": "trailing",
|
|
1164
1201
|
"pb": info.get("priceToBook"),
|
|
1165
1202
|
}
|
|
1166
1203
|
)
|
|
@@ -1370,8 +1407,10 @@ def cmd_capital_flow(args):
|
|
|
1370
1407
|
summary = {"symbol": args.symbol}
|
|
1371
1408
|
for days, label in [(5, "5d"), (10, "10d"), (20, "20d")]:
|
|
1372
1409
|
tail = df_all.tail(days)
|
|
1373
|
-
summary[f"main_net_{label}"] = _sanitize(tail.get("main_net_inflow", pd.Series()).sum())
|
|
1374
|
-
summary[f"super_large_net_{label}"] = _sanitize(
|
|
1410
|
+
summary[f"main_net_{label}"] = _sanitize(tail.get("main_net_inflow", pd.Series()).sum(min_count=days))
|
|
1411
|
+
summary[f"super_large_net_{label}"] = _sanitize(
|
|
1412
|
+
tail.get("super_large_net", pd.Series()).sum(min_count=days)
|
|
1413
|
+
)
|
|
1375
1414
|
recent = df_all["main_net_inflow"].tail(5) if "main_net_inflow" in df_all.columns else pd.Series()
|
|
1376
1415
|
if len(recent) >= 3:
|
|
1377
1416
|
pos_count = (recent > 0).sum()
|
|
@@ -1566,6 +1605,13 @@ def financials_yf(symbol: str, periods: int = 1, annual: bool = False) -> dict:
|
|
|
1566
1605
|
"roe": info.get("returnOnEquity"),
|
|
1567
1606
|
"debt_to_equity": info.get("debtToEquity"),
|
|
1568
1607
|
"dividend_yield": info.get("dividendYield"),
|
|
1608
|
+
"snapshot_units": {
|
|
1609
|
+
"pe": "trailing",
|
|
1610
|
+
"roe": "ratio",
|
|
1611
|
+
"profit_margin": "ratio",
|
|
1612
|
+
"debt_to_equity": "percent",
|
|
1613
|
+
"dividend_yield": "ratio",
|
|
1614
|
+
},
|
|
1569
1615
|
}
|
|
1570
1616
|
)
|
|
1571
1617
|
if warnings:
|
|
@@ -1703,7 +1749,8 @@ def _snapshot_efinance() -> list:
|
|
|
1703
1749
|
"昨收": "prev_close",
|
|
1704
1750
|
}
|
|
1705
1751
|
df = df.rename(columns=col_map)
|
|
1706
|
-
|
|
1752
|
+
df["pe_basis"] = "dynamic"
|
|
1753
|
+
keep = [c for c in col_map.values() if c in df.columns] + ["pe_basis"]
|
|
1707
1754
|
return [_clean_row(r) for r in df[keep].to_dict("records")]
|
|
1708
1755
|
|
|
1709
1756
|
|
|
@@ -1815,7 +1862,8 @@ def _snapshot_akshare() -> list:
|
|
|
1815
1862
|
"60日涨跌幅": "change_pct_60d",
|
|
1816
1863
|
}
|
|
1817
1864
|
df = df.rename(columns=col_map)
|
|
1818
|
-
|
|
1865
|
+
df["pe_basis"] = "dynamic"
|
|
1866
|
+
keep = [c for c in col_map.values() if c in df.columns] + ["pe_basis"]
|
|
1819
1867
|
df = df[keep]
|
|
1820
1868
|
return [_clean_row(r) for r in df.to_dict("records")]
|
|
1821
1869
|
|
|
@@ -1837,7 +1885,11 @@ def snapshot_hk() -> list:
|
|
|
1837
1885
|
"总市值": "market_cap",
|
|
1838
1886
|
}
|
|
1839
1887
|
df = df.rename(columns=col_map)
|
|
1840
|
-
|
|
1888
|
+
if "symbol" in df.columns:
|
|
1889
|
+
symbols = df["symbol"].astype(str).str.upper()
|
|
1890
|
+
df["symbol"] = symbols.map(lambda s: s if s.endswith(".HK") else f"{s}.HK")
|
|
1891
|
+
df["pe_basis"] = "unknown"
|
|
1892
|
+
keep = [c for c in col_map.values() if c in df.columns] + ["pe_basis"]
|
|
1841
1893
|
return [_clean_row(r) for r in df[keep].to_dict("records")]
|
|
1842
1894
|
except Exception as e:
|
|
1843
1895
|
# summary only (type + short message) — never a stack trace or response body
|
|
@@ -1860,7 +1912,11 @@ def snapshot_us() -> list:
|
|
|
1860
1912
|
"总市值": "market_cap",
|
|
1861
1913
|
}
|
|
1862
1914
|
df = df.rename(columns=col_map)
|
|
1863
|
-
|
|
1915
|
+
if "symbol" in df.columns:
|
|
1916
|
+
symbols = df["symbol"].astype(str).str.upper().str.replace(r"\.(?:OQ|N|A)$", "", regex=True)
|
|
1917
|
+
df["symbol"] = symbols.str.replace(".", "-", regex=False)
|
|
1918
|
+
df["pe_basis"] = "unknown"
|
|
1919
|
+
keep = [c for c in col_map.values() if c in df.columns] + ["pe_basis"]
|
|
1864
1920
|
return [_clean_row(r) for r in df[keep].to_dict("records")]
|
|
1865
1921
|
except Exception as e:
|
|
1866
1922
|
return [{"error": f"US snapshot unavailable: {type(e).__name__}: {scrub_secrets(str(e))}"[:200]}]
|
|
@@ -2154,8 +2210,8 @@ def _disk_cache_get(key: str):
|
|
|
2154
2210
|
|
|
2155
2211
|
def _disk_cache_set(key: str, data):
|
|
2156
2212
|
try:
|
|
2157
|
-
_DATA_CACHE_DIR.
|
|
2158
|
-
|
|
2213
|
+
with atomic_write(_DATA_CACHE_DIR / f"{key}.json") as stream:
|
|
2214
|
+
json.dump(data, stream, ensure_ascii=False, allow_nan=False)
|
|
2159
2215
|
except Exception:
|
|
2160
2216
|
pass
|
|
2161
2217
|
|
|
@@ -2711,6 +2767,9 @@ def compute_market_stats(data: list) -> dict:
|
|
|
2711
2767
|
code_info = normalize_stock_code(sym)
|
|
2712
2768
|
lp = code_info.get("limit_pct")
|
|
2713
2769
|
if lp:
|
|
2770
|
+
name = s.get("name", "")
|
|
2771
|
+
if name and "ST" in name.upper() and code_info["board"] == "main":
|
|
2772
|
+
lp = 0.05
|
|
2714
2773
|
limit_up = calc_limit_price(float(prev), lp, "up")
|
|
2715
2774
|
limit_down = calc_limit_price(float(prev), lp, "down")
|
|
2716
2775
|
if abs(float(price) - limit_up) < 0.01:
|
|
@@ -2775,6 +2834,7 @@ def cmd_fundamental_context(args):
|
|
|
2775
2834
|
quote = quote_a(args.symbol)
|
|
2776
2835
|
result["valuation"] = {
|
|
2777
2836
|
"pe": quote.get("pe"),
|
|
2837
|
+
"pe_basis": quote.get("pe_basis"),
|
|
2778
2838
|
"pb": quote.get("pb"),
|
|
2779
2839
|
"market_cap": quote.get("market_cap"),
|
|
2780
2840
|
}
|
|
@@ -3149,15 +3209,12 @@ def cmd_margin_trading(args):
|
|
|
3149
3209
|
try:
|
|
3150
3210
|
import concurrent.futures
|
|
3151
3211
|
|
|
3152
|
-
import akshare as ak
|
|
3153
3212
|
from trading_calendar import prev_trading_days
|
|
3154
3213
|
|
|
3155
3214
|
if exchange == "sh":
|
|
3156
3215
|
col_map = _MARGIN_DETAIL_SSE_COLS
|
|
3157
|
-
detail_fn = ak.stock_margin_detail_sse
|
|
3158
3216
|
elif exchange == "sz":
|
|
3159
3217
|
col_map = _MARGIN_DETAIL_SZSE_COLS
|
|
3160
|
-
detail_fn = ak.stock_margin_detail_szse
|
|
3161
3218
|
else:
|
|
3162
3219
|
return {"error": f"margin_trading: {args.symbol} is a BSE code; only SSE/SZSE margin detail is available"}
|
|
3163
3220
|
trade_days = prev_trading_days("CN", days)
|
|
@@ -3165,17 +3222,45 @@ def cmd_margin_trading(args):
|
|
|
3165
3222
|
return {"error": "margin_trading: trading calendar unavailable"}
|
|
3166
3223
|
|
|
3167
3224
|
def fetch_day(date_iso):
|
|
3168
|
-
"""
|
|
3169
|
-
|
|
3225
|
+
"""Cache the published exchange-day table, then select this stock."""
|
|
3226
|
+
|
|
3227
|
+
def fetch_table():
|
|
3228
|
+
import akshare as ak
|
|
3229
|
+
|
|
3230
|
+
detail_fn = ak.stock_margin_detail_sse if exchange == "sh" else ak.stock_margin_detail_szse
|
|
3170
3231
|
df = _akshare_retry(detail_fn, date=date_iso.replace("-", ""))
|
|
3232
|
+
if df is None or df.empty:
|
|
3233
|
+
return []
|
|
3234
|
+
df = df.rename(columns=col_map)
|
|
3235
|
+
required = {"symbol", "margin_buy", "margin_balance"}
|
|
3236
|
+
if not required.issubset(df.columns):
|
|
3237
|
+
raise ValueError("margin detail table missing financial columns")
|
|
3238
|
+
df = df[df["symbol"].astype(str).str.fullmatch(r"\d{6}")]
|
|
3239
|
+
if "信用交易日期" in df.columns:
|
|
3240
|
+
source_days = df["信用交易日期"].map(lambda v: re.sub(r"\D", "", str(v))[:8])
|
|
3241
|
+
if not (source_days == date_iso.replace("-", "")).all():
|
|
3242
|
+
raise ValueError("margin detail table date does not match requested day")
|
|
3243
|
+
keep = [c for c in col_map.values() if c in df.columns]
|
|
3244
|
+
table = [{"date": date_iso, **_clean_row(r)} for r in df[keep].to_dict("records")]
|
|
3245
|
+
for row in table:
|
|
3246
|
+
values = [_parse_float(row.get(field)) for field in ("margin_buy", "margin_balance")]
|
|
3247
|
+
if any(value is None or not math.isfinite(value) for value in values):
|
|
3248
|
+
# Keep usable stocks without persisting an incomplete exchange snapshot.
|
|
3249
|
+
return {"rows": table, "warnings": ["incomplete financial values"]}
|
|
3250
|
+
return table
|
|
3251
|
+
|
|
3252
|
+
try:
|
|
3253
|
+
today = datetime.now(ZoneInfo("Asia/Shanghai")).date().isoformat()
|
|
3254
|
+
table = (
|
|
3255
|
+
cached(f"margin-table:{exchange}:{date_iso}", DAY, fetch_table)
|
|
3256
|
+
if date_iso < today
|
|
3257
|
+
else fetch_table()
|
|
3258
|
+
)
|
|
3259
|
+
if isinstance(table, dict):
|
|
3260
|
+
table = table["rows"]
|
|
3261
|
+
return date_iso, [r for r in table if str(r.get("symbol")) == bare], None
|
|
3171
3262
|
except Exception as e:
|
|
3172
3263
|
return date_iso, [], f"{date_iso}: {type(e).__name__}: {scrub_secrets(str(e))}"
|
|
3173
|
-
if df is None or df.empty:
|
|
3174
|
-
return date_iso, [], None
|
|
3175
|
-
df = df.rename(columns=col_map)
|
|
3176
|
-
keep = [c for c in col_map.values() if c in df.columns]
|
|
3177
|
-
hit = df[df["symbol"].astype(str) == bare] if "symbol" in df.columns else df.iloc[0:0]
|
|
3178
|
-
return date_iso, [{"date": date_iso, **_clean_row(r)} for r in hit[keep].to_dict("records")], None
|
|
3179
3264
|
|
|
3180
3265
|
rows = []
|
|
3181
3266
|
failures = []
|
package/tools/technical.py
CHANGED
|
@@ -231,12 +231,13 @@ def macd_series(close: pd.Series) -> tuple:
|
|
|
231
231
|
|
|
232
232
|
|
|
233
233
|
def rsi_series(close: pd.Series, period: int) -> pd.Series:
|
|
234
|
-
"""Full RSI series (SMA of gains/losses over `period`).
|
|
234
|
+
"""Full RSI series (SMA of gains/losses over `period`)."""
|
|
235
235
|
delta = close.diff()
|
|
236
236
|
gain = delta.where(delta > 0, 0.0).rolling(period).mean()
|
|
237
237
|
loss = (-delta.where(delta < 0, 0.0)).rolling(period).mean()
|
|
238
238
|
rs = gain / loss.replace(0, np.nan)
|
|
239
|
-
|
|
239
|
+
rsi = (100 - 100 / (1 + rs)).mask((loss == 0) & (gain > 0), 100)
|
|
240
|
+
return rsi.mask((loss == 0) & (gain == 0), 50)
|
|
240
241
|
|
|
241
242
|
|
|
242
243
|
def bollinger_series(close: pd.Series, period: int = 20) -> tuple:
|
|
@@ -257,22 +258,23 @@ def kdj_series(high: pd.Series, low: pd.Series, close: pd.Series) -> tuple:
|
|
|
257
258
|
return k, d, 3 * k - 2 * d
|
|
258
259
|
|
|
259
260
|
|
|
261
|
+
def _ma_arrangement(values):
|
|
262
|
+
valid = [value for value in values if value is not None]
|
|
263
|
+
if len(valid) < 3:
|
|
264
|
+
return "insufficient_data"
|
|
265
|
+
if all(a > b for a, b in zip(valid, valid[1:])):
|
|
266
|
+
return "bullish"
|
|
267
|
+
if all(a < b for a, b in zip(valid, valid[1:])):
|
|
268
|
+
return "bearish"
|
|
269
|
+
return "mixed"
|
|
270
|
+
|
|
271
|
+
|
|
260
272
|
def calc_ma(close: pd.Series) -> dict:
|
|
261
273
|
mas = {}
|
|
262
274
|
for n in [5, 10, 20, 60]:
|
|
263
275
|
ma = ma_series(close, n)
|
|
264
276
|
mas[f"ma{n}"] = round(float(ma.iloc[-1]), 2) if len(ma.dropna()) > 0 else None
|
|
265
|
-
|
|
266
|
-
valid = [v for v in vals if v is not None]
|
|
267
|
-
if len(valid) >= 3:
|
|
268
|
-
if valid == sorted(valid, reverse=True):
|
|
269
|
-
mas["ma_arrangement"] = "bullish"
|
|
270
|
-
elif valid == sorted(valid):
|
|
271
|
-
mas["ma_arrangement"] = "bearish"
|
|
272
|
-
else:
|
|
273
|
-
mas["ma_arrangement"] = "mixed"
|
|
274
|
-
else:
|
|
275
|
-
mas["ma_arrangement"] = "insufficient_data"
|
|
277
|
+
mas["ma_arrangement"] = _ma_arrangement([mas.get(f"ma{n}") for n in [5, 10, 20, 60]])
|
|
276
278
|
return mas
|
|
277
279
|
|
|
278
280
|
|
|
@@ -353,11 +355,13 @@ def calc_kdj(high: pd.Series, low: pd.Series, close: pd.Series) -> dict:
|
|
|
353
355
|
|
|
354
356
|
|
|
355
357
|
def calc_volume(volume: pd.Series) -> dict:
|
|
356
|
-
vol_ma5 = float(volume.rolling(5).mean().iloc[-1])
|
|
357
|
-
vol_ma10 = float(volume.rolling(10).mean().iloc[-1])
|
|
358
|
+
vol_ma5 = float(volume.rolling(5).mean().shift(1).iloc[-1])
|
|
359
|
+
vol_ma10 = float(volume.rolling(10).mean().shift(1).iloc[-1])
|
|
358
360
|
cur = float(volume.iloc[-1])
|
|
359
|
-
ratio = cur / vol_ma5 if vol_ma5 > 0 else
|
|
360
|
-
if ratio
|
|
361
|
+
ratio = cur / vol_ma5 if np.isfinite(vol_ma5) and vol_ma5 > 0 else None
|
|
362
|
+
if ratio is None:
|
|
363
|
+
signal = "insufficient_data"
|
|
364
|
+
elif ratio > 3:
|
|
361
365
|
signal = "extremely_heavy"
|
|
362
366
|
elif ratio > 2:
|
|
363
367
|
signal = "heavy"
|
|
@@ -367,9 +371,9 @@ def calc_volume(volume: pd.Series) -> dict:
|
|
|
367
371
|
signal = "normal"
|
|
368
372
|
return {
|
|
369
373
|
"current": int(cur),
|
|
370
|
-
"vol_ma5": round(vol_ma5, 0),
|
|
371
|
-
"vol_ma10": round(vol_ma10, 0),
|
|
372
|
-
"volume_ratio": round(ratio, 2),
|
|
374
|
+
"vol_ma5": round(vol_ma5, 0) if np.isfinite(vol_ma5) else None,
|
|
375
|
+
"vol_ma10": round(vol_ma10, 0) if np.isfinite(vol_ma10) else None,
|
|
376
|
+
"volume_ratio": round(ratio, 2) if ratio is not None else None,
|
|
373
377
|
"signal": signal,
|
|
374
378
|
}
|
|
375
379
|
|
|
@@ -411,9 +415,11 @@ def calc_bias(close: pd.Series, ma_data: dict) -> dict:
|
|
|
411
415
|
|
|
412
416
|
def calc_volume_direction(close: pd.Series, volume: pd.Series) -> str:
|
|
413
417
|
if len(close) < 2:
|
|
414
|
-
return "
|
|
418
|
+
return "insufficient_data"
|
|
415
419
|
price_up = float(close.iloc[-1]) > float(close.iloc[-2])
|
|
416
|
-
vol_ma5 = float(volume.rolling(5).mean().iloc[-1])
|
|
420
|
+
vol_ma5 = float(volume.rolling(5).mean().shift(1).iloc[-1])
|
|
421
|
+
if not np.isfinite(vol_ma5) or vol_ma5 <= 0:
|
|
422
|
+
return "insufficient_data"
|
|
417
423
|
cur_vol = float(volume.iloc[-1])
|
|
418
424
|
heavy = cur_vol > vol_ma5 * 1.5
|
|
419
425
|
shrink = cur_vol < vol_ma5 * 0.7
|
|
@@ -461,6 +467,8 @@ def generate_signal_score(
|
|
|
461
467
|
# --- Trend score (30 points) ---
|
|
462
468
|
arrangement = ma_data.get("ma_arrangement", "mixed")
|
|
463
469
|
overall = trend_data.get("overall", "neutral")
|
|
470
|
+
ma_values = [value for value in (ma_data.get(f"ma{n}") for n in (5, 10, 20, 60)) if value is not None]
|
|
471
|
+
flat_ma = len(ma_values) >= 3 and len(set(ma_values)) == 1
|
|
464
472
|
short_t = trend_data.get("short_term", "neutral")
|
|
465
473
|
medium_t = trend_data.get("medium_term", "neutral")
|
|
466
474
|
long_t = trend_data.get("long_term", "neutral")
|
|
@@ -479,15 +487,15 @@ def generate_signal_score(
|
|
|
479
487
|
reasons.append("短中期趋势偏多")
|
|
480
488
|
elif arrangement == "mixed":
|
|
481
489
|
trend_score = 12
|
|
482
|
-
elif bear_count >= 2:
|
|
483
|
-
trend_score = 8
|
|
484
|
-
risks.append("中长期趋势偏空")
|
|
485
490
|
elif arrangement == "bearish" and bear_count == 3:
|
|
486
491
|
trend_score = 0
|
|
487
492
|
risks.append("均线空头排列,趋势极弱")
|
|
488
493
|
elif arrangement == "bearish":
|
|
489
494
|
trend_score = 4
|
|
490
495
|
risks.append("均线空头排列,不宜做多")
|
|
496
|
+
elif bear_count >= 2:
|
|
497
|
+
trend_score = 8
|
|
498
|
+
risks.append("中长期趋势偏空")
|
|
491
499
|
else:
|
|
492
500
|
trend_score = 12
|
|
493
501
|
score += trend_score
|
|
@@ -604,9 +612,9 @@ def generate_signal_score(
|
|
|
604
612
|
score += rsi_score
|
|
605
613
|
|
|
606
614
|
# --- Buy signal classification ---
|
|
607
|
-
if score >= 75 and overall == "bullish":
|
|
615
|
+
if score >= 75 and overall == "bullish" and not flat_ma:
|
|
608
616
|
buy_signal = "STRONG_BUY"
|
|
609
|
-
elif score >= 60 and overall in ("bullish", "neutral"):
|
|
617
|
+
elif score >= 60 and overall in ("bullish", "neutral") and not flat_ma:
|
|
610
618
|
buy_signal = "BUY"
|
|
611
619
|
elif score >= 45:
|
|
612
620
|
buy_signal = "HOLD"
|
|
@@ -640,7 +648,9 @@ def generate_signals(
|
|
|
640
648
|
signals.append("MACD空头排列(DIF < DEA)")
|
|
641
649
|
|
|
642
650
|
rsi_sig = rsi_data.get("signal", "")
|
|
643
|
-
if "
|
|
651
|
+
if rsi_sig == "insufficient_data":
|
|
652
|
+
signals.append("RSI数据不足,无法判断超买超卖")
|
|
653
|
+
elif "overbought" in rsi_sig:
|
|
644
654
|
signals.append(f"RSI超买区间(RSI6={rsi_data.get('rsi6')}),注意回调风险")
|
|
645
655
|
elif "oversold" in rsi_sig:
|
|
646
656
|
signals.append(f"RSI超卖区间(RSI6={rsi_data.get('rsi6')}),关注反弹机会")
|
|
@@ -663,7 +673,9 @@ def generate_signals(
|
|
|
663
673
|
signals.append(f"KDJ超卖(J={kdj_data['j']}),关注低位机会")
|
|
664
674
|
|
|
665
675
|
vs = vol_data.get("signal", "")
|
|
666
|
-
if "
|
|
676
|
+
if vs == "insufficient_data":
|
|
677
|
+
signals.append("成交量数据不足,无法判断放量或缩量")
|
|
678
|
+
elif "heavy" in vs:
|
|
667
679
|
signals.append(f"成交量放大(量比={vol_data['volume_ratio']}),市场关注度高")
|
|
668
680
|
elif vs == "light":
|
|
669
681
|
signals.append(f"缩量交易(量比={vol_data['volume_ratio']}),市场观望情绪浓")
|
|
@@ -712,17 +724,7 @@ def calculate_ma_standalone(
|
|
|
712
724
|
else:
|
|
713
725
|
bias[f"bias_ma{n}"] = None
|
|
714
726
|
|
|
715
|
-
|
|
716
|
-
if len(valid_mas) >= 3:
|
|
717
|
-
vals = [v for _, v in valid_mas]
|
|
718
|
-
if vals == sorted(vals, reverse=True):
|
|
719
|
-
alignment = "bullish"
|
|
720
|
-
elif vals == sorted(vals):
|
|
721
|
-
alignment = "bearish"
|
|
722
|
-
else:
|
|
723
|
-
alignment = "mixed"
|
|
724
|
-
else:
|
|
725
|
-
alignment = "insufficient_data"
|
|
727
|
+
alignment = _ma_arrangement([mas[f"ma{n}"] for n in periods if mas.get(f"ma{n}") is not None])
|
|
726
728
|
|
|
727
729
|
cross_signals = []
|
|
728
730
|
for fast, slow in [(5, 10), (5, 20), (10, 20), (20, 60)]:
|
|
@@ -4,10 +4,12 @@
|
|
|
4
4
|
import argparse
|
|
5
5
|
import json
|
|
6
6
|
import sys
|
|
7
|
-
from datetime import datetime, timedelta
|
|
7
|
+
from datetime import date, datetime, timedelta
|
|
8
8
|
from pathlib import Path
|
|
9
|
+
from zoneinfo import ZoneInfo
|
|
9
10
|
|
|
10
11
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
12
|
+
from _cache import DAY, cached
|
|
11
13
|
from _subproc import socket_timeout, utf8_stdio
|
|
12
14
|
|
|
13
15
|
# Supported markets. argparse uses type=str.upper so lowercase input is accepted too.
|
|
@@ -18,10 +20,8 @@ def _is_weekend(d: datetime) -> bool:
|
|
|
18
20
|
return d.weekday() >= 5
|
|
19
21
|
|
|
20
22
|
|
|
21
|
-
#
|
|
22
|
-
|
|
23
|
-
# re-fetch the sina calendar per step — up to ~5 fetches for one stale check.
|
|
24
|
-
_CN_TRADE_DATES: dict[int, set[str]] = {}
|
|
23
|
+
# Year views reuse a daily cached full calendar across CLI processes.
|
|
24
|
+
_CN_TRADE_DATES: dict[tuple[str, int], set[str]] = {}
|
|
25
25
|
|
|
26
26
|
|
|
27
27
|
def cn_trade_dates(year: int) -> set[str]:
|
|
@@ -30,25 +30,30 @@ def cn_trade_dates(year: int) -> set[str]:
|
|
|
30
30
|
Empty set when the calendar can't be fetched (failures are not cached — the
|
|
31
31
|
next call retries); callers treat empty as "weekends are the only non-trading
|
|
32
32
|
days"."""
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
33
|
+
stamp = datetime.now(ZoneInfo("Asia/Shanghai")).date().isoformat()
|
|
34
|
+
memo = _CN_TRADE_DATES.get((stamp, year))
|
|
35
|
+
if memo is not None:
|
|
36
|
+
return memo
|
|
36
37
|
try:
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
38
|
+
|
|
39
|
+
def fetch():
|
|
40
|
+
import akshare as ak
|
|
41
|
+
|
|
42
|
+
with socket_timeout(25):
|
|
43
|
+
df = ak.tool_trade_date_hist_sina()
|
|
44
|
+
if df is None or df.empty:
|
|
45
|
+
return []
|
|
46
|
+
return sorted({date.fromisoformat(str(value)[:10]).isoformat() for value in df.iloc[:, 0]})
|
|
47
|
+
|
|
48
|
+
dates = cached(f"cn-trade-calendar:v1:{stamp}", DAY, fetch)
|
|
49
|
+
grouped = {}
|
|
50
|
+
for day in dates:
|
|
51
|
+
parsed = date.fromisoformat(day).isoformat()
|
|
52
|
+
grouped.setdefault((stamp, int(parsed[:4])), set()).add(parsed)
|
|
53
|
+
_CN_TRADE_DATES.update(grouped)
|
|
47
54
|
except Exception:
|
|
48
55
|
return set()
|
|
49
|
-
|
|
50
|
-
_CN_TRADE_DATES[year] = dates
|
|
51
|
-
return dates
|
|
56
|
+
return _CN_TRADE_DATES.get((stamp, year), set())
|
|
52
57
|
|
|
53
58
|
|
|
54
59
|
def _is_exchange_trading_day(exchange_code: str, date_str: str) -> bool:
|
package/tools/value_data.py
CHANGED
|
@@ -1146,7 +1146,11 @@ def etf_basket(symbol):
|
|
|
1146
1146
|
|
|
1147
1147
|
def fund_disclosed_equities(symbol):
|
|
1148
1148
|
import requests
|
|
1149
|
-
|
|
1149
|
+
|
|
1150
|
+
try:
|
|
1151
|
+
from akshare.utils.jsonish import loads as decode
|
|
1152
|
+
except ImportError:
|
|
1153
|
+
from akshare.utils.demjson import decode
|
|
1150
1154
|
from bs4 import BeautifulSoup
|
|
1151
1155
|
|
|
1152
1156
|
limit = 10000
|
|
@@ -1160,7 +1164,7 @@ def fund_disclosed_equities(symbol):
|
|
|
1160
1164
|
)
|
|
1161
1165
|
response.raise_for_status()
|
|
1162
1166
|
text = response.text
|
|
1163
|
-
payload =
|
|
1167
|
+
payload = decode(text[text.index("{") : text.rindex("}") + 1])
|
|
1164
1168
|
soup = BeautifulSoup(payload["content"], "lxml")
|
|
1165
1169
|
for block in soup.select("div.boxitem"):
|
|
1166
1170
|
heading = block.find("h4")
|
package/tools/watchlist.py
CHANGED
|
@@ -6,11 +6,12 @@ import json
|
|
|
6
6
|
import math
|
|
7
7
|
import sys
|
|
8
8
|
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
9
|
+
from contextlib import nullcontext
|
|
9
10
|
from pathlib import Path
|
|
10
11
|
|
|
11
12
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
12
13
|
from _subproc import utf8_stdio
|
|
13
|
-
from gather import gather_analysis
|
|
14
|
+
from gather import Collection, gather_analysis
|
|
14
15
|
|
|
15
16
|
|
|
16
17
|
def has_analysis_data(data) -> bool:
|
|
@@ -28,27 +29,35 @@ def has_analysis_data(data) -> bool:
|
|
|
28
29
|
return False
|
|
29
30
|
|
|
30
31
|
|
|
31
|
-
def analyze_watchlist(symbols: list[str], workers: int = 3) -> dict:
|
|
32
|
+
def analyze_watchlist(symbols: list[str], workers: int = 3, *, session=None, on_result=None) -> dict:
|
|
32
33
|
if isinstance(workers, bool) or not isinstance(workers, int) or workers <= 0:
|
|
33
34
|
return {"error": "workers must be a positive integer"}
|
|
34
35
|
results = {}
|
|
35
36
|
success = 0
|
|
36
37
|
failed = 0
|
|
37
38
|
|
|
38
|
-
with
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
sym =
|
|
42
|
-
|
|
43
|
-
data
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
39
|
+
with Collection() if session is None else nullcontext(session) as session:
|
|
40
|
+
|
|
41
|
+
def analyze(sym):
|
|
42
|
+
data = gather_analysis(sym, session=session)
|
|
43
|
+
if on_result is not None:
|
|
44
|
+
on_result(sym, data)
|
|
45
|
+
return data
|
|
46
|
+
|
|
47
|
+
with ThreadPoolExecutor(max_workers=workers) as pool:
|
|
48
|
+
futures = {pool.submit(analyze, sym): sym for sym in symbols}
|
|
49
|
+
for future in as_completed(futures):
|
|
50
|
+
sym = futures[future]
|
|
51
|
+
try:
|
|
52
|
+
data = future.result()
|
|
53
|
+
results[sym] = data
|
|
54
|
+
if has_analysis_data(data):
|
|
55
|
+
success += 1
|
|
56
|
+
else:
|
|
57
|
+
failed += 1
|
|
58
|
+
except Exception:
|
|
59
|
+
results[sym] = None
|
|
48
60
|
failed += 1
|
|
49
|
-
except Exception:
|
|
50
|
-
results[sym] = None
|
|
51
|
-
failed += 1
|
|
52
61
|
|
|
53
62
|
return {
|
|
54
63
|
"results": results,
|