stock-analysis-plugin 0.2.6 → 0.2.7

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.
@@ -16,12 +16,13 @@ import math
16
16
  import os
17
17
  import sys
18
18
  import tempfile
19
+ import time
19
20
  from datetime import datetime
20
21
  from pathlib import Path
21
22
  from uuid import uuid4
22
23
 
23
24
  sys.path.insert(0, str(Path(__file__).resolve().parent))
24
- from _subproc import run_tool, utf8_stdio # noqa: E402
25
+ from _subproc import command_timeout, run_tool, utf8_stdio # noqa: E402
25
26
  from stock_data import detect_market # noqa: E402
26
27
 
27
28
 
@@ -234,7 +235,26 @@ def _valid_bar(bar) -> bool:
234
235
  )
235
236
 
236
237
 
238
+ def _price_factor(rec, bars):
239
+ if all(bar.get("adjusted") == "none" for bar in bars):
240
+ return 1.0
241
+ anchor = next((bar for bar in bars if bar["date"] == rec["record_date"]), {})
242
+ basis = anchor.get("adjusted")
243
+ factor = anchor.get("adjustment_factor")
244
+ if (
245
+ basis in ("qfq", "total_return")
246
+ and all(bar.get("adjusted") == basis for bar in bars)
247
+ and not isinstance(factor, bool)
248
+ and isinstance(factor, (int, float))
249
+ and math.isfinite(factor)
250
+ and factor > 0
251
+ ):
252
+ return factor
253
+ return None
254
+
255
+
237
256
  def cmd_evaluate(args):
257
+ deadline = time.monotonic() + command_timeout("signal_tracker.py", ["evaluate"]) - 30
238
258
  store = _store_path(args)
239
259
  try:
240
260
  with _store_lock(store):
@@ -244,16 +264,22 @@ def cmd_evaluate(args):
244
264
  results = []
245
265
  evaluated = closed = 0
246
266
  changed = False
267
+ deferred = 0
247
268
  for rec in records:
248
269
  if rec.get("status") != "open":
249
270
  continue
250
271
  if args.symbol and rec.get("symbol") != args.symbol:
251
272
  continue
273
+ remaining = deadline - time.monotonic()
274
+ if remaining <= 0:
275
+ deferred += 1
276
+ continue
252
277
  evaluated += 1
253
278
  entry = {"id": rec.get("id"), "symbol": rec.get("symbol")}
254
279
  bars = run_tool(
255
280
  "stock_data.py",
256
281
  ["kline", rec["symbol"], "--period", "daily", "--count", str(_kline_count(rec))],
282
+ timeout=min(command_timeout("stock_data.py", ["kline"]), remaining),
257
283
  )
258
284
  if (
259
285
  not isinstance(bars, list)
@@ -262,12 +288,24 @@ def cmd_evaluate(args):
262
288
  or min(str(b.get("date", ""))[:10] for b in bars) > rec["record_date"]
263
289
  ):
264
290
  entry.update({"outcome": "skipped_no_data", "return_pct": None, "exit_date": None})
291
+ elif (factor := _price_factor(rec, bars)) is None:
292
+ entry.update(
293
+ outcome="skipped_price_basis",
294
+ return_pct=None,
295
+ exit_date=None,
296
+ warning="Adjusted or unknown prices lack a verified conversion to the original signal prices",
297
+ )
265
298
  else:
266
- ev = _evaluate_bars(rec, bars)
299
+ priced = dict(rec)
300
+ for key in ("entry_price", "target_price", "stop_price"):
301
+ if priced.get(key) is not None:
302
+ priced[key] *= factor
303
+ ev = _evaluate_bars(priced, bars)
267
304
  if ev is None:
268
305
  entry.update({"outcome": "open", "return_pct": None, "exit_date": None})
269
306
  else:
270
307
  outcome, exit_price, exit_date = ev
308
+ exit_price /= factor
271
309
  ret = round((exit_price - rec["entry_price"]) / rec["entry_price"] * 100, 2)
272
310
  if rec.get("direction") == "sell":
273
311
  ret = -ret
@@ -278,6 +316,7 @@ def cmd_evaluate(args):
278
316
  "exit_price": exit_price,
279
317
  "exit_date": exit_date,
280
318
  "return_pct": ret,
319
+ "evaluation_price_basis": {"adjusted": bars[0].get("adjusted"), "factor": factor},
281
320
  }
282
321
  )
283
322
  changed = True
@@ -289,7 +328,18 @@ def cmd_evaluate(args):
289
328
  with _store_lock(store):
290
329
  current = _load_records(store, strict=True)
291
330
  merged = [updates.get(r["id"], r) if r.get("status") == "open" else r for r in current]
292
- if changed:
331
+ if deferred:
332
+ attempted = {entry["id"] for entry in results}
333
+ positions = [
334
+ i
335
+ for i, rec in enumerate(merged)
336
+ if rec.get("status") == "open" and (not args.symbol or rec.get("symbol") == args.symbol)
337
+ ]
338
+ # Keep closed/unselected records in place; give unattempted signals the next turn.
339
+ queued = sorted((merged[i] for i in positions), key=lambda rec: rec["id"] in attempted)
340
+ for i, rec in zip(positions, queued):
341
+ merged[i] = rec
342
+ if changed or deferred:
293
343
  _save_records(store, merged)
294
344
  persisted = {r["id"]: r for r in merged}
295
345
  for entry in results:
@@ -299,7 +349,15 @@ def cmd_evaluate(args):
299
349
  closed += 1
300
350
  except (OSError, ValueError) as e:
301
351
  return {"error": str(e)}
302
- return {"evaluated": evaluated, "closed": closed, "still_open": evaluated - closed, "results": results}
352
+ return {
353
+ "evaluated": evaluated,
354
+ "closed": closed,
355
+ "still_open": evaluated + deferred - closed,
356
+ "results": results,
357
+ "deferred": deferred,
358
+ "complete": deferred == 0,
359
+ "warnings": ["Time budget exhausted; deferred signals remain open for the next evaluation"] if deferred else [],
360
+ }
303
361
 
304
362
 
305
363
  def cmd_summary(args):
@@ -324,14 +382,27 @@ def cmd_summary(args):
324
382
  for o in ("target_hit", "stop_hit", "timeout_profit", "timeout_loss")
325
383
  }
326
384
  wins = counts["target_hit"] + counts["timeout_profit"]
327
- returns = [r["return_pct"] for r in closed_recs if isinstance(r.get("return_pct"), (int, float))]
385
+ returns = [
386
+ r["return_pct"]
387
+ for r in closed_recs
388
+ if isinstance(r.get("return_pct"), (int, float))
389
+ and not isinstance(r["return_pct"], bool)
390
+ and math.isfinite(r["return_pct"])
391
+ ]
328
392
  by_source = {}
329
393
  for r in closed_recs:
330
- agg = by_source.setdefault(r.get("source") or "unknown", {"closed": 0, "wins": 0})
394
+ agg = by_source.setdefault(r.get("source") or "unknown", {"closed": 0, "wins": 0, "returns": []})
331
395
  agg["closed"] += 1
396
+ value = r.get("return_pct")
397
+ if isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value):
398
+ agg["returns"].append(value)
332
399
  if r.get("outcome") in ("target_hit", "timeout_profit"):
333
400
  agg["wins"] += 1
334
401
  for agg in by_source.values():
402
+ samples = agg.pop("returns")
403
+ agg["return_samples"] = len(samples)
404
+ agg["avg_return_pct"] = round(sum(samples) / len(samples), 2) if samples else None
405
+ agg["sample_warning"] = "Small observational sample; not strategy validation" if len(samples) < 15 else None
335
406
  agg["win_rate"] = round(agg["wins"] / agg["closed"] * 100, 2) if agg["closed"] else None
336
407
  return {
337
408
  "filters": {"source": args.source, "symbol": args.symbol, "status": args.status},