Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ Stock analysis, screening, and backtesting live in the shared Python CLIs under
3. **Work in verifiable units.** For multi-step work, set the dependency order and verification check for each unit before editing, and verify each unit before building on it. Follow [ponytail](https://github.com/DietrichGebert/ponytail) by reusing [scripts/tool-calls.mjs](scripts/tool-calls.mjs), [scripts/venv-python.mjs](scripts/venv-python.mjs), [tools/_subproc.py](tools/_subproc.py), and [tests/conftest.py](tests/conftest.py) instead of adding parallel helpers or dependencies.
4. **Prove the change.** Rerun the failing reproduction and exercise the real affected entry point. Report the exact commands, observed results, and the host, OS, install mode, or artifact checked. When a target such as Windows, macOS, or an installed host is unavailable, run the nearest local check and state what remains unverified.

When the external [Matt Pocock skills](https://github.com/mattpocock/skills) are installed locally, use `diagnosing-bugs` for regressions, `tdd` for Python behavior changes, and `to-spec` with `to-tickets` for breaking or multi-phase changes. Keep specs, review notes, and external skill files out of commits.
When the external [Matt Pocock skills](https://github.com/mattpocock/skills) are installed locally, use `diagnosing-bugs` for regressions, `tdd` for Python behavior changes, and `to-spec` with `to-tickets` for breaking or multi-phase changes. When the [pstack skills](https://github.com/cursor/plugins/tree/main/pstack/) are installed locally, use `benchmark-checklist` and `principle-explain-the-number` before trusting or reporting performance measurements (name the limiter from profiles or counters, verify outputs and error counts, and report run count, median, and range), and use `blast-radius` for cross-cutting changes alongside `principle-fix-root-causes`, `principle-subtract-before-you-add`, and `principle-prove-it-works`. Keep specs, review notes, and external skill files out of commits.

## Local setup and verification

Expand Down
97 changes: 82 additions & 15 deletions dsh/dashboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -357,10 +357,12 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand
}

function quoteJob(symbol: string, priority: number): Job {
const region = watchRegion(symbol);
return {
key: `quote:${symbol}`, kind: "quote", region: watchRegion(symbol), priority, batched: true,
key: `quote:${symbol}`, kind: "quote", region, priority, batched: true,
// Per-region batches: slow overseas/fund/advisor quotes must not hold up A-share quotes.
run: async () => {
const value = await batched("quotes", "all", symbol, priority) as Record<string, unknown> | null;
const value = await batched("quotes", region, symbol, priority) as Record<string, unknown> | null;
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("报价数据格式不正确");
if (value.error) throw new Error(safeError(value.error, "报价暂不可用"));
return { ...value, symbol };
Expand All @@ -382,16 +384,43 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand
};
}

const pendingPhases: Array<{ market: string; resolve: (value: unknown) => void; reject: (error: unknown) => void }> = [];
let phasesScheduled = false;
function batchedPhase(region: Region): Promise<unknown> {
const market = region.toUpperCase();
return new Promise((resolve, reject) => {
pendingPhases.push({ market, resolve, reject });
if (!phasesScheduled) {
phasesScheduled = true;
queueMicrotask(flushPhases);
}
});
}
function flushPhases() {
phasesScheduled = false;
const batch = pendingPhases.splice(0);
const markets = batch.map(item => item.market).join(",");
limiter.run(0, () => py("trading_calendar.py", ["phases", markets], 10_000)).then(
Comment thread
Weaxs marked this conversation as resolved.
Resolved
map => {
if (!map || typeof map !== "object" || Array.isArray(map) || "error" in map) {
throw new Error("交易阶段暂不可用");
}
const record = map as Record<string, unknown>;
for (const item of batch) {
const value = record[item.market] as Record<string, unknown> | undefined;
if (!value || typeof value !== "object" || value.error) item.reject(new Error("交易阶段暂不可用"));
else item.resolve(value);
}
},
).catch(error => batch.forEach(item => item.reject(error)));
}

function jobs(symbols: string[]): Job[] {
const list: Job[] = [];
for (const region of REGIONS) {
list.push({
key: `phase:${region}`, kind: "phase", region, priority: 0,
run: async () => {
const value = await py("trading_calendar.py", ["phase", region.toUpperCase()], 10_000) as Record<string, unknown>;
if (!value || typeof value !== "object" || value.error) throw new Error("交易阶段暂不可用");
return value;
},
key: `phase:${region}`, kind: "phase", region, priority: 0, batched: true,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
run: () => batchedPhase(region),
});
}
for (const symbol of symbols) list.push(quoteJob(symbol, 1));
Expand Down Expand Up @@ -482,8 +511,32 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand
return task;
}

const assetCache = new Map<string, { ino: bigint; mtimeNs: bigint; size: bigint; body: Buffer; etag: string }>();
let watchlistCache: { ino: bigint; mtimeNs: bigint; size: bigint; symbols: string[] } | null = null;
function cachedWatchlist(): string[] {
let st;
try {
st = statSync(watchlistFile, { bigint: true });
} catch (error) {
watchlistCache = null;
if ((error as { code?: string }).code === "ENOENT") return [];
throw new Error("无法读取自选股文件");
}
if (watchlistCache && watchlistCache.ino === st.ino && watchlistCache.mtimeNs === st.mtimeNs && watchlistCache.size === st.size) {
return watchlistCache.symbols;
}
try {
const symbols = readWatchlist(watchlistFile);
watchlistCache = { ino: st.ino, mtimeNs: st.mtimeNs, size: st.size, symbols };
return symbols;
} catch (error) {
watchlistCache = null;
throw error;
}
}

function currentSymbols(): string[] {
try { return readWatchlist(watchlistFile); } catch { return []; }
try { return cachedWatchlist(); } catch { return []; }
}

/** Start every due job; resolves when the jobs started by this tick finish. */
Expand Down Expand Up @@ -548,7 +601,7 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand
function snapshot(region: Region) {
lastSeen = Date.now();
viewedRegion = region;
const symbols = readWatchlist(watchlistFile);
const symbols = cachedWatchlist();
kick();
void checkLatest();
return {
Expand Down Expand Up @@ -616,11 +669,12 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand
return sendJson(res, 202, { ok: true, pending: limiter.queued });
}
if (rest === "/api/watchlist") {
if (req.method === "GET") return sendJson(res, 200, { symbols: readWatchlist(watchlistFile) });
if (req.method === "GET") return sendJson(res, 200, { symbols: cachedWatchlist() });
if (req.method === "POST") {
const body = await readJson(req);
if (!body?.op) throw new HttpError(400, "必须指定 add 或 remove 操作");
const saved = await updateWatchlist(watchlistFile, body.op, body.symbols);
watchlistCache = null;
kick();
return sendJson(res, 200, { symbols: saved });
}
Expand Down Expand Up @@ -653,19 +707,32 @@ export function createDashboardHandler(options: DashboardOptions): DashboardHand
const asset = STATIC_FILES.get(rest as "/" | "/app.js" | "/style.css");
if (!asset) return sendJson(res, 404, { error: "Not found" });
const [file, contentType] = asset;
let body: Buffer;
const assetPath = join(webDir, file);
let entry = assetCache.get(file);
try {
body = readFileSync(join(webDir, file));
const st = statSync(assetPath, { bigint: true });
if (!entry || entry.ino !== st.ino || entry.mtimeNs !== st.mtimeNs || entry.size !== st.size) {
const body = readFileSync(assetPath);
entry = { ino: st.ino, mtimeNs: st.mtimeNs, size: st.size, body, etag: `"${st.ino}-${st.mtimeNs}-${st.size}"` };
assetCache.set(file, entry);
}
} catch {
assetCache.delete(file);
return sendJson(res, 404, { error: "Not found" });
}
if (req.headers["if-none-match"] === entry.etag) {
res.writeHead(304, { etag: entry.etag, "cache-control": "no-cache" });
res.end();
return;
}
res.writeHead(200, {
"content-type": contentType,
"content-length": body.length,
"content-length": entry.body.length,
etag: entry.etag,
"cache-control": "no-cache",
"x-content-type-options": "nosniff",
});
res.end(req.method === "HEAD" ? undefined : body);
res.end(req.method === "HEAD" ? undefined : entry.body);
} catch (error) {
if (error instanceof HttpError) return sendJson(res, error.status, { error: error.message });
const message = error instanceof Error && !/[/\\]/.test(error.message) ? error.message : "仪表盘服务暂时不可用";
Expand Down
3 changes: 3 additions & 0 deletions dsh/web/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -743,9 +743,12 @@ function renderRows(flash: Map<string, Direction>) {
return;
}
if (!state.snap.watchlist.length) {
for (const key of sparkCache.keys()) if (key.startsWith("watch:")) sparkCache.delete(key);
body.append(emptyRow());
return;
}
const activeWatchKeys = new Set(state.snap.watchlist.map(item => `watch:${item.symbol}`));
for (const key of sparkCache.keys()) if (key.startsWith("watch:") && !activeWatchKeys.has(key)) sparkCache.delete(key);
for (const item of items!) {
const quote = item.quote;
const price = watchPrice(item);
Expand Down
29 changes: 23 additions & 6 deletions tests/test_dsh_dashboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,14 @@ function fakePython(options: { phase?: string; fail?: (script: string, args: str
? { error: "secret stderr at /private/provider.py" }
: [{ date: "2026-01-01", close: 10, open: 9 }, { date: "2026-01-02", close: 11 }, { date: "2026-01-03", close: "bad" }]));
}
if (script === "trading_calendar.py") return JSON.stringify({ market: args[1], phase: options.phase ?? "post_market", phase_label: "盘后" });
if (script === "trading_calendar.py") {
if (args[0] === "phases") {
return JSON.stringify(Object.fromEntries(
args[1].split(",").map(market => [market, { market, phase: options.phase ?? "post_market", phase_label: "盘后" }]),
));
}
return JSON.stringify({ market: args[1], phase: options.phase ?? "post_market", phase_label: "盘后" });
}
if (args[0] === "quote") return JSON.stringify({ symbol: args[1], name: `Name ${args[1]}`, price: 100, change_pct: 1.2, high: 101, low: 99 });
if (args[0] === "market_indices") return JSON.stringify([{ code: "^HSI", name: "恒生指数", price: 20000, change_pct: -0.5 }]);
if (args[0] === "sector_rankings") return JSON.stringify({ top: [{ name: "元件", change_pct: 5 }], bottom: [{ name: "白酒", change_pct: -3 }] });
Expand Down Expand Up @@ -310,18 +317,22 @@ try {
await handler.tick();
await handler.settle();
assert(py.maxActive() <= 4, `python concurrency ${py.maxActive()} exceeded four`);
assert.equal(py.calls.filter(call => call.startsWith("stock_data.py:quotes ")).length, 1, "one process serves every due quote");
assert(py.calls.some(call => call.startsWith("stock_data.py:quotes ") && call.endsWith(" --watchlist")));
const quoteBatches = py.calls.filter(call => call.startsWith("stock_data.py:quotes "));
assert.equal(quoteBatches.length, 3, "one quote process per active watchlist region (cn, us, hk)");
assert(quoteBatches.every(call => call.endsWith(" --watchlist")));
const cnQuoteBatch = quoteBatches.find(call => call.includes("600519"));
assert(cnQuoteBatch && cnQuoteBatch.includes("sh000001") && !cnQuoteBatch.includes("AAPL"), "CN stock and indices share one batch separate from overseas symbols");
for (const symbol of ["600519", "AAPL", "00700.HK", "sh000001"]) assert.equal(quoted(py.calls, symbol), 1, `missing quote ${symbol}`);
assert.equal(py.timeouts.get(py.calls.find(call => call.startsWith("stock_data.py:quotes "))!), 40_000, "the batch outlives the CLI's own 30 s per-row deadline");
assert(quoteBatches.every(call => py.timeouts.get(call) === 40_000), "the batch outlives the CLI's own 30 s per-row deadline");
for (const expected of [
"stock_data.py:market_indices --region hk",
"stock_data.py:sector_rankings --top 5 --direction both --board-type industry",
"stock_data.py:market_stats --market A",
"stock_data.py:market_stats --market HK",
"stock_data.py:market_stats --market US",
"trading_calendar.py:phase JP",
"trading_calendar.py:phases CN,HK,US,JP,KR,TW",
]) assert(py.calls.includes(expected), `missing ${expected}`);
assert.equal(py.calls.filter(call => call.startsWith("trading_calendar.py:")).length, 1, "one process serves every due market phase");
assert(!py.calls.includes("stock_data.py:market_indices --region cn"), "A-share indices use direct quotes");
assert.equal(py.timeouts.get("stock_data.py:market_stats --market US"), 60_000);
const klines = py.calls.filter(call => call.startsWith("stock_data.py:klines "));
Expand Down Expand Up @@ -412,7 +423,7 @@ try {
const failFile = join(temp, "fail", "watchlist.json");
writeWatchlist(failFile, ["AAPL"]);
let failing = false;
const flaky = fakePython({ fail: (_script, args) => failing && args[1] === "AAPL" });
const flaky = fakePython({ fail: (_script, args) => failing && (args[0] === "quote" || args[0] === "kline") && args[1] === "AAPL" });
const failHandler = createDashboardHandler({ runPy: flaky.runPy, watchlistFile: failFile, webDir });
await failHandler.tick();
await failHandler.settle();
Expand Down Expand Up @@ -558,6 +569,12 @@ try {
assert.equal(page.status(), 200);
assert.match(page.body(), /股票仪表盘/);
assert.match(page.headers()["content-type"] as string, /text\/html/);
assert(typeof page.headers().etag === "string", "static assets emit an ETag");
const cachedReq = get("/stock-analysis/");
cachedReq.headers["if-none-match"] = page.headers().etag as string;
const notModified = await call(handler, cachedReq);
assert.equal(notModified.status(), 304, "matching If-None-Match returns 304 without body");
assert.equal(notModified.body(), "");
assert.match(page.body(), /<script src="\.\/app\.js"/, "the page loads the compiled bundle");
assert.match((await call(handler, get("/stock-analysis/app.js"))).headers()["content-type"] as string, /javascript/);
for (const asset of ["app.js", "style.css"]) assert.equal((await call(handler, get(`/stock-analysis/${asset}`))).status(), 200);
Expand Down
13 changes: 13 additions & 0 deletions tests/test_market_review.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,3 +286,16 @@ def fetch(script, args, *a, **kw):
assert "partial_data" in result["data_quality"]["flags"]
assert any("indices" in warning for warning in result["warnings"])
assert any("sectors" in warning for warning in result["warnings"])


def test_review_all_runs_markets_concurrently_in_order(monkeypatch):
import threading

barrier = threading.Barrier(3, timeout=5)

def fake_review(market):
barrier.wait()
return {"market": market}

monkeypatch.setattr(mr, "review_market", fake_review)
assert mr.review_all() == [{"market": "A"}, {"market": "HK"}, {"market": "US"}]
29 changes: 29 additions & 0 deletions tests/test_risk_screening.py
Original file line number Diff line number Diff line change
Expand Up @@ -4236,6 +4236,7 @@ def fake_tv(region, body):
assert "error" in bad

# Fallback to HK ETF proxies when TradingView fails
monkeypatch.setattr(stock_data, "cached", lambda _k, _ttl, fetch: fetch())
monkeypatch.setattr(stock_data, "_tradingview_scan", lambda *a, **kw: (_ for _ in ()).throw(RuntimeError("down")))
idx = pd.to_datetime(["2026-10-01", "2026-10-02"])
closes = pd.DataFrame({"3033.HK": [4.0, 4.2], "2800.HK": [20.0, 19.8]}, index=idx)
Expand All @@ -4246,3 +4247,31 @@ def fake_tv(region, body):
assert fb[0]["etf"] == "3033.HK"
assert fb[0]["proxy"] == "HK Sector ETF"
assert fb[0]["change_pct"] == 5.0


def test_lockup_cache_skips_subprocess_on_warm_hit_and_never_caches_failures(monkeypatch):
import pandas as pd

today = risk_screening.market_now("CN").strftime("%Y-%m-%d")
ak_calls = []

def flaky_fetch(**kwargs):
ak_calls.append(kwargs["symbol"])
if len(ak_calls) == 1:
raise ConnectionError("offline")
return pd.DataFrame({"解禁日期": [today]})

monkeypatch.setattr("akshare.stock_restricted_release_queue_em", flaky_fetch)
# Failures are not cached — next call retries.
assert risk_screening._fetch_lockup("600519")["available"] is False
populated = risk_screening._fetch_lockup("600519")
assert populated["available"] is True
assert populated["upcoming_30d"] == [today]
assert len(ak_calls) == 2

# Warm disk cache hit in check_lockup avoids spawning the lockup subprocess.
subproc_calls = []
monkeypatch.setattr(risk_screening, "_run_tool", lambda *a, **kw: subproc_calls.append((a, kw)))
cached_result = risk_screening.check_lockup("600519")
assert cached_result == populated
assert subproc_calls == []
25 changes: 25 additions & 0 deletions tests/test_search_intel.py
Original file line number Diff line number Diff line change
Expand Up @@ -392,3 +392,28 @@ def test_extract_cli_validation_error_exits_nonzero():
def test_extract_rejects_invalid_text_limit(limit):
result = extract_article("https://example.com/story", max_chars=limit)
assert "max_chars" in result["error"]


def test_comprehensive_fans_out_remaining_dimensions_concurrently(monkeypatch):
import threading

monkeypatch.setenv("BOCHA_API_KEY", "fixture")
barrier = threading.Barrier(5, timeout=5)
calls = []
lock = threading.Lock()

def post(url, **kwargs):
query = kwargs["json"]["query"]
with lock:
calls.append(query)
if "最新消息" not in query:
barrier.wait()
return _mock_requests({"data": {"webPages": {"value": [{"name": query, "url": f"https://ex/{query}"}]}}}).post()

req = MagicMock()
req.post.side_effect = post
with patch.dict(sys.modules, {"requests": req}):
result = search_comprehensive("600519", "贵州茅台")
assert len(result["dimensions"]) == 6
assert len(calls) == 6
assert "最新消息" in calls[0]
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
10 changes: 10 additions & 0 deletions tests/test_signal_tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -1216,3 +1216,13 @@ def test_failed_append_preserves_valid_store(store):
assert result.returncode == 0, result.stderr
assert store.read_bytes() == original
assert len(st._load_records(store, strict=True)) == 1


def test_evaluate_reuses_successful_kline_across_same_symbol_signals(store, mock_run_tool):
st.cmd_record(_rec_args(store, symbol="600519", date="2026-09-01", horizon_days=3, target_price=12))
st.cmd_record(_rec_args(store, symbol="600519", date="2026-09-01", horizon_days=10, target_price=12))
mock_run_tool.return_value = [_bar("2026-09-01", 10, 10, 10), _bar("2026-09-02", 12.5, 10.0, 12.1)]
result = st.cmd_evaluate(Namespace(symbol=None, store=str(store)))
assert result["evaluated"] == 2
assert result["closed"] == 2
assert mock_run_tool.call_count == 1
Loading
Loading