feat: redesign workspaces and stabilize screeners
This commit is contained in:
+371
-32
@@ -7,6 +7,15 @@ from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
def _optional_float(value: Any) -> float | None:
|
||||
if value in (None, ""):
|
||||
return None
|
||||
try:
|
||||
return float(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
class ManagedConnection(sqlite3.Connection):
|
||||
"""Commit or roll back, then release the SQLite file handle on context exit."""
|
||||
|
||||
@@ -128,6 +137,7 @@ class ReviewDatabase:
|
||||
name TEXT NOT NULL,
|
||||
sector TEXT NOT NULL DEFAULT '',
|
||||
color TEXT NOT NULL DEFAULT 'red',
|
||||
remark TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
PRIMARY KEY (user_id, code),
|
||||
@@ -140,6 +150,7 @@ class ReviewDatabase:
|
||||
code TEXT NOT NULL DEFAULT '',
|
||||
stock_name TEXT NOT NULL DEFAULT '',
|
||||
trade_date TEXT NOT NULL,
|
||||
summary TEXT NOT NULL DEFAULT '',
|
||||
content TEXT NOT NULL DEFAULT '',
|
||||
plan TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL,
|
||||
@@ -204,9 +215,30 @@ class ReviewDatabase:
|
||||
volume_ratio REAL NOT NULL DEFAULT 0,
|
||||
total_mv REAL NOT NULL DEFAULT 0,
|
||||
circ_mv REAL NOT NULL DEFAULT 0,
|
||||
pe_ttm REAL,
|
||||
pb REAL,
|
||||
ps_ttm REAL,
|
||||
dv_ttm REAL,
|
||||
PRIMARY KEY (trade_date, ts_code)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS fundamental_indicators (
|
||||
end_date TEXT NOT NULL,
|
||||
ann_date TEXT NOT NULL DEFAULT '',
|
||||
ts_code TEXT NOT NULL,
|
||||
roe REAL,
|
||||
roa REAL,
|
||||
roic REAL,
|
||||
grossprofit_margin REAL,
|
||||
netprofit_yoy REAL,
|
||||
or_yoy REAL,
|
||||
ocf_to_opincome REAL,
|
||||
PRIMARY KEY (end_date, ts_code)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_fundamental_indicators_code_date
|
||||
ON fundamental_indicators(ts_code, ann_date DESC, end_date DESC);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS moneyflow_daily (
|
||||
trade_date TEXT NOT NULL,
|
||||
ts_code TEXT NOT NULL,
|
||||
@@ -251,6 +283,7 @@ class ReviewDatabase:
|
||||
user_id INTEGER,
|
||||
trade_date TEXT NOT NULL,
|
||||
regime TEXT NOT NULL,
|
||||
mode TEXT NOT NULL DEFAULT 'smart',
|
||||
strategy_name TEXT NOT NULL,
|
||||
formula TEXT NOT NULL,
|
||||
result TEXT NOT NULL,
|
||||
@@ -397,6 +430,19 @@ class ReviewDatabase:
|
||||
for column, statement in migrations.items():
|
||||
if column not in user_columns:
|
||||
connection.execute(statement)
|
||||
indicator_columns = {
|
||||
str(row["name"])
|
||||
for row in connection.execute("PRAGMA table_info(daily_indicators)")
|
||||
}
|
||||
indicator_migrations = {
|
||||
"pe_ttm": "ALTER TABLE daily_indicators ADD COLUMN pe_ttm REAL",
|
||||
"pb": "ALTER TABLE daily_indicators ADD COLUMN pb REAL",
|
||||
"ps_ttm": "ALTER TABLE daily_indicators ADD COLUMN ps_ttm REAL",
|
||||
"dv_ttm": "ALTER TABLE daily_indicators ADD COLUMN dv_ttm REAL",
|
||||
}
|
||||
for column, statement in indicator_migrations.items():
|
||||
if column not in indicator_columns:
|
||||
connection.execute(statement)
|
||||
connection.execute(
|
||||
"""
|
||||
UPDATE users SET role = 'admin'
|
||||
@@ -417,6 +463,7 @@ class ReviewDatabase:
|
||||
name TEXT NOT NULL,
|
||||
sector TEXT NOT NULL DEFAULT '',
|
||||
color TEXT NOT NULL DEFAULT 'red',
|
||||
remark TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
PRIMARY KEY (user_id, code),
|
||||
@@ -436,11 +483,20 @@ class ReviewDatabase:
|
||||
(int(first_user["id"]),),
|
||||
)
|
||||
connection.execute("DROP TABLE watchlist_legacy")
|
||||
watchlist_columns.add("remark")
|
||||
if "remark" not in watchlist_columns:
|
||||
connection.execute(
|
||||
"ALTER TABLE watchlist ADD COLUMN remark TEXT NOT NULL DEFAULT ''"
|
||||
)
|
||||
note_columns = {
|
||||
str(row["name"]) for row in connection.execute("PRAGMA table_info(review_notes)")
|
||||
}
|
||||
if "user_id" not in note_columns:
|
||||
connection.execute("ALTER TABLE review_notes ADD COLUMN user_id INTEGER")
|
||||
if "summary" not in note_columns:
|
||||
connection.execute(
|
||||
"ALTER TABLE review_notes ADD COLUMN summary TEXT NOT NULL DEFAULT ''"
|
||||
)
|
||||
first_user = connection.execute("SELECT MIN(id) AS id FROM users").fetchone()
|
||||
if first_user and first_user["id"]:
|
||||
connection.execute(
|
||||
@@ -463,6 +519,33 @@ class ReviewDatabase:
|
||||
}
|
||||
if "user_id" not in run_columns:
|
||||
connection.execute("ALTER TABLE screener_runs ADD COLUMN user_id INTEGER")
|
||||
if "mode" not in run_columns:
|
||||
connection.execute(
|
||||
"ALTER TABLE screener_runs ADD COLUMN mode TEXT NOT NULL DEFAULT 'smart'"
|
||||
)
|
||||
legacy_runs = connection.execute(
|
||||
"SELECT id, strategy_name, formula FROM screener_runs"
|
||||
).fetchall()
|
||||
for run in legacy_runs:
|
||||
try:
|
||||
formula = json.loads(run["formula"])
|
||||
except (TypeError, json.JSONDecodeError):
|
||||
formula = {}
|
||||
meta = formula.get("meta") if isinstance(formula, dict) else {}
|
||||
library = str((meta or {}).get("library") or "")
|
||||
category = str((meta or {}).get("category") or "")
|
||||
if library == "curated":
|
||||
mode = "curated"
|
||||
elif library == "quant" or (
|
||||
library == "custom" and category == "量化公式"
|
||||
) or str(run["strategy_name"] or "") == "自定义量化公式":
|
||||
mode = "quant"
|
||||
else:
|
||||
mode = "smart"
|
||||
connection.execute(
|
||||
"UPDATE screener_runs SET mode = ? WHERE id = ?",
|
||||
(mode, int(run["id"])),
|
||||
)
|
||||
if first_user and first_user["id"]:
|
||||
first_user_id = int(first_user["id"])
|
||||
connection.execute(
|
||||
@@ -485,6 +568,12 @@ class ReviewDatabase:
|
||||
ON screener_runs(user_id, trade_date DESC, id DESC)
|
||||
"""
|
||||
)
|
||||
connection.execute(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS idx_screener_runs_user_mode_date
|
||||
ON screener_runs(user_id, mode, trade_date DESC, id DESC)
|
||||
"""
|
||||
)
|
||||
|
||||
def count_users(self) -> int:
|
||||
with self.connect() as connection:
|
||||
@@ -883,7 +972,7 @@ class ReviewDatabase:
|
||||
with self.connect() as connection:
|
||||
rows = connection.execute(
|
||||
"""
|
||||
SELECT code, name, sector, color, created_at, updated_at
|
||||
SELECT code, name, sector, color, remark, created_at, updated_at
|
||||
FROM watchlist WHERE user_id = ? ORDER BY updated_at DESC, code
|
||||
""",
|
||||
(int(user_id),),
|
||||
@@ -891,24 +980,53 @@ class ReviewDatabase:
|
||||
return [dict(row) for row in rows]
|
||||
|
||||
def save_watchlist(
|
||||
self, user_id: int, code: str, name: str, sector: str, color: str
|
||||
self, user_id: int, code: str, name: str, sector: str, color: str,
|
||||
remark: str | None = None,
|
||||
) -> None:
|
||||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
with self.connect() as connection:
|
||||
existing = connection.execute(
|
||||
"SELECT remark FROM watchlist WHERE user_id = ? AND code = ?",
|
||||
(int(user_id), code),
|
||||
).fetchone()
|
||||
saved_remark = (
|
||||
str(existing["remark"] or "") if remark is None and existing else str(remark or "")
|
||||
)
|
||||
connection.execute(
|
||||
"""
|
||||
INSERT INTO watchlist
|
||||
(user_id, code, name, sector, color, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
(user_id, code, name, sector, color, remark, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(user_id, code) DO UPDATE SET
|
||||
name = excluded.name,
|
||||
sector = excluded.sector,
|
||||
color = excluded.color,
|
||||
remark = excluded.remark,
|
||||
updated_at = excluded.updated_at
|
||||
""",
|
||||
(int(user_id), code, name, sector, color, now, now),
|
||||
(int(user_id), code, name, sector, color, saved_remark, now, now),
|
||||
)
|
||||
|
||||
def watchlist_price_history(
|
||||
self, codes: list[str], end_date: str, limit_per_code: int = 6
|
||||
) -> dict[str, list[dict[str, Any]]]:
|
||||
result: dict[str, list[dict[str, Any]]] = {}
|
||||
if not codes:
|
||||
return result
|
||||
with self.connect() as connection:
|
||||
for code in codes:
|
||||
rows = connection.execute(
|
||||
"""
|
||||
SELECT trade_date, ts_code, close, pct_chg
|
||||
FROM daily_bars
|
||||
WHERE substr(ts_code, 1, 6) = ? AND trade_date <= ?
|
||||
ORDER BY trade_date DESC LIMIT ?
|
||||
""",
|
||||
(str(code), end_date, int(limit_per_code)),
|
||||
).fetchall()
|
||||
result[str(code)] = [dict(row) for row in reversed(rows)]
|
||||
return result
|
||||
|
||||
def delete_watchlist(self, user_id: int, code: str) -> bool:
|
||||
with self.connect() as connection:
|
||||
cursor = connection.execute(
|
||||
@@ -940,7 +1058,7 @@ class ReviewDatabase:
|
||||
with self.connect() as connection:
|
||||
rows = connection.execute(
|
||||
f"""
|
||||
SELECT id, code, stock_name, trade_date, content, plan, created_at, updated_at
|
||||
SELECT id, code, stock_name, trade_date, summary, content, plan, created_at, updated_at
|
||||
FROM review_notes {where}
|
||||
ORDER BY trade_date DESC, updated_at DESC, id DESC LIMIT 200
|
||||
""",
|
||||
@@ -957,6 +1075,7 @@ class ReviewDatabase:
|
||||
content: str,
|
||||
plan: str,
|
||||
note_id: int | None = None,
|
||||
summary: str = "",
|
||||
) -> int:
|
||||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
with self.connect() as connection:
|
||||
@@ -964,10 +1083,10 @@ class ReviewDatabase:
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
UPDATE review_notes
|
||||
SET code = ?, stock_name = ?, trade_date = ?, content = ?, plan = ?, updated_at = ?
|
||||
SET code = ?, stock_name = ?, trade_date = ?, summary = ?, content = ?, plan = ?, updated_at = ?
|
||||
WHERE id = ? AND user_id = ?
|
||||
""",
|
||||
(code, stock_name, trade_date, content, plan, now, note_id, int(user_id)),
|
||||
(code, stock_name, trade_date, summary, content, plan, now, note_id, int(user_id)),
|
||||
)
|
||||
if cursor.rowcount == 0:
|
||||
raise ValueError("复盘笔记不存在。")
|
||||
@@ -975,10 +1094,10 @@ class ReviewDatabase:
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO review_notes
|
||||
(user_id, code, stock_name, trade_date, content, plan, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
(user_id, code, stock_name, trade_date, summary, content, plan, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(int(user_id), code, stock_name, trade_date, content, plan, now, now),
|
||||
(int(user_id), code, stock_name, trade_date, summary, content, plan, now, now),
|
||||
)
|
||||
return int(cursor.lastrowid)
|
||||
|
||||
@@ -1148,6 +1267,8 @@ class ReviewDatabase:
|
||||
str(row.get("trade_date") or ""), row.get("ts_code", ""),
|
||||
float(row.get("turnover_rate") or 0), float(row.get("volume_ratio") or 0),
|
||||
float(row.get("total_mv") or 0), float(row.get("circ_mv") or 0),
|
||||
_optional_float(row.get("pe_ttm")), _optional_float(row.get("pb")),
|
||||
_optional_float(row.get("ps_ttm")), _optional_float(row.get("dv_ttm")),
|
||||
)
|
||||
for row in rows if row.get("trade_date") and row.get("ts_code")
|
||||
]
|
||||
@@ -1155,11 +1276,44 @@ class ReviewDatabase:
|
||||
connection.executemany(
|
||||
"""
|
||||
INSERT INTO daily_indicators
|
||||
(trade_date, ts_code, turnover_rate, volume_ratio, total_mv, circ_mv)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
(trade_date, ts_code, turnover_rate, volume_ratio, total_mv, circ_mv,
|
||||
pe_ttm, pb, ps_ttm, dv_ttm)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(trade_date, ts_code) DO UPDATE SET
|
||||
turnover_rate=excluded.turnover_rate, volume_ratio=excluded.volume_ratio,
|
||||
total_mv=excluded.total_mv, circ_mv=excluded.circ_mv
|
||||
total_mv=excluded.total_mv, circ_mv=excluded.circ_mv,
|
||||
pe_ttm=excluded.pe_ttm, pb=excluded.pb,
|
||||
ps_ttm=excluded.ps_ttm, dv_ttm=excluded.dv_ttm
|
||||
""",
|
||||
values,
|
||||
)
|
||||
return len(values)
|
||||
|
||||
def upsert_fundamental_indicators(self, rows: list[dict[str, Any]]) -> int:
|
||||
values = [
|
||||
(
|
||||
str(row.get("end_date") or ""), str(row.get("ann_date") or ""),
|
||||
str(row.get("ts_code") or ""), _optional_float(row.get("roe")),
|
||||
_optional_float(row.get("roa")), _optional_float(row.get("roic")),
|
||||
_optional_float(row.get("grossprofit_margin")),
|
||||
_optional_float(row.get("netprofit_yoy")), _optional_float(row.get("or_yoy")),
|
||||
_optional_float(row.get("ocf_to_opincome")),
|
||||
)
|
||||
for row in rows
|
||||
if row.get("end_date") and row.get("ts_code")
|
||||
]
|
||||
with self.connect() as connection:
|
||||
connection.executemany(
|
||||
"""
|
||||
INSERT INTO fundamental_indicators
|
||||
(end_date, ann_date, ts_code, roe, roa, roic, grossprofit_margin,
|
||||
netprofit_yoy, or_yoy, ocf_to_opincome)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(end_date, ts_code) DO UPDATE SET
|
||||
ann_date=excluded.ann_date, roe=excluded.roe, roa=excluded.roa,
|
||||
roic=excluded.roic, grossprofit_margin=excluded.grossprofit_margin,
|
||||
netprofit_yoy=excluded.netprofit_yoy, or_yoy=excluded.or_yoy,
|
||||
ocf_to_opincome=excluded.ocf_to_opincome
|
||||
""",
|
||||
values,
|
||||
)
|
||||
@@ -1244,6 +1398,24 @@ class ReviewDatabase:
|
||||
).fetchall()
|
||||
return [row["trade_date"] for row in reversed(rows)]
|
||||
|
||||
def daily_indicator_dates(self, end_date: str = "", limit: int = 400) -> list[str]:
|
||||
where = "WHERE trade_date <= ?" if end_date else ""
|
||||
parameters: tuple[Any, ...] = (end_date, limit) if end_date else (limit,)
|
||||
with self.connect() as connection:
|
||||
rows = connection.execute(
|
||||
f"SELECT DISTINCT trade_date FROM daily_indicators {where} "
|
||||
"ORDER BY trade_date DESC LIMIT ?",
|
||||
parameters,
|
||||
).fetchall()
|
||||
return [row["trade_date"] for row in reversed(rows)]
|
||||
|
||||
def fundamental_periods(self) -> list[str]:
|
||||
with self.connect() as connection:
|
||||
rows = connection.execute(
|
||||
"SELECT DISTINCT end_date FROM fundamental_indicators ORDER BY end_date"
|
||||
).fetchall()
|
||||
return [str(row["end_date"]) for row in rows]
|
||||
|
||||
def auction_factors_for_date(self, trade_date: str) -> list[dict[str, Any]]:
|
||||
with self.connect() as connection:
|
||||
rows = connection.execute(
|
||||
@@ -1270,10 +1442,71 @@ class ReviewDatabase:
|
||||
).fetchall()
|
||||
return [row["trade_date"] for row in reversed(rows)]
|
||||
|
||||
def factor_health_summary(self, end_date: str) -> dict[str, Any]:
|
||||
dividend_start = f"{max(0, int(end_date[:4] or 0) - 5)}0101"
|
||||
with self.connect() as connection:
|
||||
market = connection.execute(
|
||||
"SELECT EXISTS(SELECT 1 FROM daily_bars WHERE trade_date <= ? LIMIT 1)",
|
||||
(end_date,),
|
||||
).fetchone()[0]
|
||||
auction = connection.execute(
|
||||
"SELECT EXISTS(SELECT 1 FROM auction_factors WHERE trade_date <= ? LIMIT 1)",
|
||||
(end_date,),
|
||||
).fetchone()[0]
|
||||
indicator_date = connection.execute(
|
||||
"SELECT MAX(trade_date) FROM daily_indicators WHERE trade_date <= ?",
|
||||
(end_date,),
|
||||
).fetchone()[0]
|
||||
if indicator_date:
|
||||
valuation_rows, valuation_available = connection.execute(
|
||||
"""
|
||||
SELECT COUNT(*), COALESCE(MAX(pe_ttm IS NOT NULL), 0)
|
||||
FROM daily_indicators WHERE trade_date = ?
|
||||
""",
|
||||
(indicator_date,),
|
||||
).fetchone()
|
||||
else:
|
||||
valuation_rows, valuation_available = 0, 0
|
||||
dividend_years = connection.execute(
|
||||
"""
|
||||
SELECT COUNT(DISTINCT substr(trade_date, 1, 4))
|
||||
FROM daily_indicators
|
||||
WHERE trade_date <= ? AND trade_date >= ?
|
||||
""",
|
||||
(end_date, dividend_start),
|
||||
).fetchone()[0]
|
||||
fundamental_rows = connection.execute(
|
||||
"""
|
||||
SELECT COUNT(*) FROM fundamental_indicators fi
|
||||
INNER JOIN (
|
||||
SELECT ts_code, MAX(ann_date || ':' || end_date) AS latest_key
|
||||
FROM fundamental_indicators
|
||||
WHERE ann_date = '' OR ann_date <= ?
|
||||
GROUP BY ts_code
|
||||
) latest
|
||||
ON latest.ts_code = fi.ts_code
|
||||
AND latest.latest_key = (fi.ann_date || ':' || fi.end_date)
|
||||
""",
|
||||
(end_date,),
|
||||
).fetchone()[0]
|
||||
return {
|
||||
"market": bool(market),
|
||||
"auction": bool(auction),
|
||||
"valuation": bool(valuation_available),
|
||||
"fundamental": int(fundamental_rows or 0) >= 100,
|
||||
"dividend_history": int(dividend_years or 0) >= 4,
|
||||
"valuation_rows": int(valuation_rows or 0),
|
||||
"fundamental_rows": int(fundamental_rows or 0),
|
||||
"dividend_years": int(dividend_years or 0),
|
||||
}
|
||||
|
||||
def load_factor_data(self, end_date: str, limit_dates: int = 80) -> dict[str, Any]:
|
||||
dates = self.factor_dates(end_date, limit_dates)
|
||||
if not dates:
|
||||
return {"dates": [], "bars": [], "master": [], "indicators": [], "moneyflow": [], "auction": []}
|
||||
return {
|
||||
"dates": [], "bars": [], "master": [], "indicators": [],
|
||||
"indicator_history": [], "fundamentals": [], "moneyflow": [], "auction": [],
|
||||
}
|
||||
placeholders = ",".join("?" for _ in dates)
|
||||
with self.connect() as connection:
|
||||
bars = connection.execute(
|
||||
@@ -1290,6 +1523,35 @@ class ReviewDatabase:
|
||||
""",
|
||||
(end_date,),
|
||||
).fetchall()
|
||||
indicator_history = connection.execute(
|
||||
"""
|
||||
SELECT di.* FROM daily_indicators di
|
||||
INNER JOIN (
|
||||
SELECT ts_code, substr(trade_date, 1, 4) AS year_key,
|
||||
MAX(trade_date) AS max_date
|
||||
FROM daily_indicators
|
||||
WHERE trade_date <= ? AND trade_date >= ?
|
||||
GROUP BY ts_code, substr(trade_date, 1, 4)
|
||||
) latest
|
||||
ON latest.ts_code = di.ts_code AND latest.max_date = di.trade_date
|
||||
ORDER BY di.trade_date, di.ts_code
|
||||
""",
|
||||
(end_date, str(max(0, int(end_date[:4] or 0) - 5)) + "0101"),
|
||||
).fetchall()
|
||||
fundamentals = connection.execute(
|
||||
"""
|
||||
SELECT fi.* FROM fundamental_indicators fi
|
||||
INNER JOIN (
|
||||
SELECT ts_code, MAX(ann_date || ':' || end_date) AS latest_key
|
||||
FROM fundamental_indicators
|
||||
WHERE ann_date = '' OR ann_date <= ?
|
||||
GROUP BY ts_code
|
||||
) latest
|
||||
ON latest.ts_code = fi.ts_code
|
||||
AND latest.latest_key = (fi.ann_date || ':' || fi.end_date)
|
||||
""",
|
||||
(end_date,),
|
||||
).fetchall()
|
||||
moneyflow = connection.execute(
|
||||
"""
|
||||
SELECT * FROM moneyflow_daily
|
||||
@@ -1313,6 +1575,8 @@ class ReviewDatabase:
|
||||
"bars": [dict(row) for row in bars],
|
||||
"master": [dict(row) for row in master],
|
||||
"indicators": [dict(row) for row in indicators],
|
||||
"indicator_history": [dict(row) for row in indicator_history],
|
||||
"fundamentals": [dict(row) for row in fundamentals],
|
||||
"moneyflow": [dict(row) for row in moneyflow],
|
||||
"auction": [dict(row) for row in auction],
|
||||
}
|
||||
@@ -1440,39 +1704,106 @@ class ReviewDatabase:
|
||||
|
||||
def save_screener_run(
|
||||
self, user_id: int, trade_date: str, regime: str, strategy_name: str,
|
||||
formula: dict[str, Any], result: dict[str, Any],
|
||||
formula: dict[str, Any], result: dict[str, Any], mode: str = "smart",
|
||||
) -> int:
|
||||
normalized_mode = mode if mode in {"smart", "curated", "quant"} else "smart"
|
||||
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
with self.connect() as connection:
|
||||
cursor = connection.execute(
|
||||
"""
|
||||
INSERT INTO screener_runs
|
||||
(user_id, trade_date, regime, strategy_name, formula, result, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
(user_id, trade_date, regime, mode, strategy_name, formula, result, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(int(user_id), trade_date, regime, strategy_name,
|
||||
(int(user_id), trade_date, regime, normalized_mode, strategy_name,
|
||||
json.dumps(formula, ensure_ascii=False, separators=(",", ":")),
|
||||
json.dumps(result, ensure_ascii=False, separators=(",", ":")), now),
|
||||
)
|
||||
return int(cursor.lastrowid)
|
||||
|
||||
def latest_screener_run(self, user_id: int, trade_date: str) -> dict[str, Any] | None:
|
||||
with self.connect() as connection:
|
||||
row = connection.execute(
|
||||
"""
|
||||
SELECT id, trade_date, regime, strategy_name, result, created_at
|
||||
FROM screener_runs WHERE user_id = ? AND trade_date <= ? ORDER BY id DESC LIMIT 1
|
||||
""",
|
||||
(int(user_id), trade_date),
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
@staticmethod
|
||||
def _screener_run_payload(row: sqlite3.Row) -> dict[str, Any] | None:
|
||||
try:
|
||||
result = json.loads(row["result"])
|
||||
except json.JSONDecodeError:
|
||||
return None
|
||||
result.setdefault("meta", {})["run_id"] = row["id"]
|
||||
result["meta"]["created_at"] = row["created_at"]
|
||||
result.setdefault("meta", {}).update(
|
||||
{
|
||||
"run_id": int(row["id"]),
|
||||
"mode": str(row["mode"] or "smart"),
|
||||
"created_at": row["created_at"],
|
||||
}
|
||||
)
|
||||
return result
|
||||
|
||||
def latest_screener_run(
|
||||
self, user_id: int, trade_date: str, mode: str = "",
|
||||
) -> dict[str, Any] | None:
|
||||
parameters: tuple[Any, ...] = (int(user_id), trade_date)
|
||||
mode_clause = ""
|
||||
if mode in {"smart", "curated", "quant"}:
|
||||
mode_clause = " AND mode = ?"
|
||||
parameters += (mode,)
|
||||
with self.connect() as connection:
|
||||
row = connection.execute(
|
||||
f"""
|
||||
SELECT id, trade_date, regime, mode, strategy_name, result, created_at
|
||||
FROM screener_runs
|
||||
WHERE user_id = ? AND trade_date <= ?{mode_clause}
|
||||
ORDER BY id DESC LIMIT 1
|
||||
""",
|
||||
parameters,
|
||||
).fetchone()
|
||||
return self._screener_run_payload(row) if row else None
|
||||
|
||||
def latest_screener_runs(self, user_id: int, trade_date: str) -> dict[str, dict[str, Any]]:
|
||||
with self.connect() as connection:
|
||||
rows = connection.execute(
|
||||
"""
|
||||
SELECT runs.id, runs.trade_date, runs.regime, runs.mode,
|
||||
runs.strategy_name, runs.result, runs.created_at
|
||||
FROM screener_runs runs
|
||||
INNER JOIN (
|
||||
SELECT mode, MAX(id) AS id
|
||||
FROM screener_runs
|
||||
WHERE user_id = ? AND trade_date <= ?
|
||||
GROUP BY mode
|
||||
) latest ON latest.id = runs.id
|
||||
""",
|
||||
(int(user_id), trade_date),
|
||||
).fetchall()
|
||||
results: dict[str, dict[str, Any]] = {}
|
||||
for row in rows:
|
||||
mode = str(row["mode"] or "smart")
|
||||
payload = self._screener_run_payload(row)
|
||||
if mode in {"smart", "curated", "quant"} and payload:
|
||||
results[mode] = payload
|
||||
return results
|
||||
|
||||
def get_screener_run(self, user_id: int, run_id: int) -> dict[str, Any] | None:
|
||||
with self.connect() as connection:
|
||||
row = connection.execute(
|
||||
"""
|
||||
SELECT id, trade_date, regime, mode, strategy_name, result, created_at
|
||||
FROM screener_runs WHERE id = ? AND user_id = ?
|
||||
""",
|
||||
(int(run_id), int(user_id)),
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
result = self._screener_run_payload(row)
|
||||
if result is None:
|
||||
return None
|
||||
result.setdefault("meta", {}).update(
|
||||
{
|
||||
"run_id": int(row["id"]),
|
||||
"trade_date": row["trade_date"],
|
||||
"mode": str(row["mode"] or "smart"),
|
||||
"created_at": row["created_at"],
|
||||
}
|
||||
)
|
||||
result["strategy_name"] = row["strategy_name"]
|
||||
result["regime"] = row["regime"]
|
||||
return result
|
||||
|
||||
def save_mentor_exchange(
|
||||
@@ -1625,6 +1956,14 @@ class ReviewDatabase:
|
||||
).fetchall()
|
||||
return [dict(row) for row in rows]
|
||||
|
||||
def delete_strategy_track(self, user_id: int, track_id: int) -> bool:
|
||||
with self.connect() as connection:
|
||||
cursor = connection.execute(
|
||||
"DELETE FROM strategy_tracks WHERE id = ? AND user_id = ?",
|
||||
(int(track_id), int(user_id)),
|
||||
)
|
||||
return cursor.rowcount > 0
|
||||
|
||||
def load_tracking_bars(
|
||||
self, targets: list[tuple[str, str]], limit: int = 5
|
||||
) -> dict[tuple[str, str], list[dict[str, Any]]]:
|
||||
|
||||
Reference in New Issue
Block a user