feat: Specialist Desks — per asset-class fundamental configs + report catalogue
- 7 pre-seeded desks (Forex, Metals, Agri, Energy, Indices, Crypto, Bonds) each with default fundamental drivers, macro regime sensitivities and price delta thresholds - Global report catalogue (specialist_reports) fully manual — add any report including non-calendar ones (e.g. Cocoa Grinding Report, ICCO) - Many-to-many report ↔ desk linking (report_desk_links table) - 12 default reports pre-seeded (COT, EIA, WASDE, FOMC, ECB, CPI, NFP…) - AI scorer injects SPECIALIST DESK context block for asset classes present in each scoring batch (upcoming reports, key drivers, regime sensitivity) - /specialist-desks page: desk sidebar + fundamentals editor + macro sensitivity tag editor + reports tab + global reports catalogue + modal to create/edit any report with desk assignment Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -641,6 +641,101 @@ def init_db():
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ── Specialist Desks ───────────────────────────────────────────────────────
|
||||
c.execute("""CREATE TABLE IF NOT EXISTS specialist_reports (
|
||||
id TEXT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
source TEXT NOT NULL DEFAULT '',
|
||||
cadence TEXT NOT NULL DEFAULT 'monthly',
|
||||
next_date TEXT,
|
||||
last_date TEXT,
|
||||
importance INTEGER NOT NULL DEFAULT 2,
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
url TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
)""")
|
||||
|
||||
c.execute("""CREATE TABLE IF NOT EXISTS asset_class_configs (
|
||||
asset_class TEXT PRIMARY KEY,
|
||||
display_name TEXT NOT NULL,
|
||||
icon TEXT NOT NULL DEFAULT '',
|
||||
fundamentals TEXT NOT NULL DEFAULT '',
|
||||
macro_sensitivity TEXT NOT NULL DEFAULT '[]',
|
||||
price_delta_thresholds TEXT NOT NULL DEFAULT '{}',
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
)""")
|
||||
|
||||
c.execute("""CREATE TABLE IF NOT EXISTS report_desk_links (
|
||||
report_id TEXT NOT NULL,
|
||||
asset_class TEXT NOT NULL,
|
||||
PRIMARY KEY (report_id, asset_class)
|
||||
)""")
|
||||
|
||||
# Seed desk defaults (idempotent)
|
||||
_desk_count = c.execute("SELECT COUNT(*) FROM asset_class_configs").fetchone()[0]
|
||||
if _desk_count == 0:
|
||||
_desk_defaults = [
|
||||
("forex", "Forex", "💱",
|
||||
"Rate differentials (Fed vs ECB/BOJ/BOE), current account balances, political risk premium, USD index trend, carry trade positioning, intervention risk.",
|
||||
'[{"regime":"dollar_strength","effect":"bearish EUR/JPY, bullish DXY pairs"},{"regime":"risk_off","effect":"bullish JPY/CHF, bearish EM FX"},{"regime":"dovish_fed","effect":"bearish USD, bullish EM FX"},{"regime":"rate_divergence_us_up","effect":"bullish USD across board"}]',
|
||||
'{"significant_day":0.5,"extreme_day":1.5,"significant_week":1.0,"extreme_week":2.5}'),
|
||||
("metals", "Metals", "🥇",
|
||||
"Real interest rates (TIPS), DXY trend, China PMI/demand, ETF flows (GLD/SLV), COT net positioning, inflation breakevens, central bank gold buying, industrial demand (copper/silver).",
|
||||
'[{"regime":"risk_off","effect":"bullish gold, silver underperforms"},{"regime":"real_rates_rising","effect":"bearish gold/silver"},{"regime":"dollar_weakness","effect":"bullish all metals"},{"regime":"china_stimulus","effect":"bullish copper/industrial metals"}]',
|
||||
'{"significant_day":1.0,"extreme_day":3.0,"significant_week":2.0,"extreme_week":5.0}'),
|
||||
("agri", "Agri & Softs", "🌾",
|
||||
"WASDE supply/demand balance, weather events (La Niña/El Niño), crop calendar (planting/harvest), freight rates, USD/BRL (soy), USD/ARS, biofuel mandates (corn/soy), export inspections.",
|
||||
'[{"regime":"la_nina","effect":"bullish corn/wheat (US drought), bearish soy (S. America)"},{"regime":"dollar_strength","effect":"bearish USD-denominated agri exports"},{"regime":"energy_shock","effect":"bullish corn (ethanol), bullish soy (biodiesel)"},{"regime":"china_demand_drop","effect":"bearish soy/corn"}]',
|
||||
'{"significant_day":1.5,"extreme_day":4.0,"significant_week":3.0,"extreme_week":8.0}'),
|
||||
("energy", "Energy", "⚡",
|
||||
"OPEC+ production decisions, EIA weekly inventory build/draw, US rig count/shale production, geopolitical premium (Middle East/Russia), demand/growth cycle, refinery margins, seasonal demand (summer driving/winter heating).",
|
||||
'[{"regime":"geopolitical_escalation","effect":"bullish crude, nat gas spike risk"},{"regime":"recession_fear","effect":"bearish crude (demand destruction)"},{"regime":"opec_cut","effect":"bullish crude"},{"regime":"dollar_strength","effect":"mildly bearish crude"}]',
|
||||
'{"significant_day":1.5,"extreme_day":4.0,"significant_week":3.0,"extreme_week":8.0}'),
|
||||
("indices", "Equity Indices", "📈",
|
||||
"Earnings growth trajectory, Fed policy path (PE multiples), credit spreads (HYG), buyback activity, market breadth/concentration, Buffett indicator, VIX regime, sector rotation (growth vs value).",
|
||||
'[{"regime":"fed_pivot_dovish","effect":"bullish equities, PE expansion"},{"regime":"credit_stress","effect":"bearish equities, flight to safety"},{"regime":"earnings_miss_wave","effect":"bearish indices, vol spike"},{"regime":"risk_on","effect":"bullish equities, small caps outperform"}]',
|
||||
'{"significant_day":1.0,"extreme_day":3.0,"significant_week":2.0,"extreme_week":5.0}'),
|
||||
("crypto", "Crypto", "₿",
|
||||
"BTC halving cycle position, on-chain net flows (exchange inflows/outflows), stablecoin supply growth, regulatory risk (SEC/CFTC), BTC dominance, macro correlation (SPY), ETF flows.",
|
||||
'[{"regime":"risk_off","effect":"bearish BTC/ETH, correlation with equities rises"},{"regime":"dollar_weakness_qe","effect":"bullish BTC as inflation hedge"},{"regime":"regulatory_crackdown","effect":"bearish all crypto"},{"regime":"btc_halving_post","effect":"bullish BTC 6-12m horizon"}]',
|
||||
'{"significant_day":3.0,"extreme_day":10.0,"significant_week":8.0,"extreme_week":20.0}'),
|
||||
("bonds", "Bonds & Rates", "📉",
|
||||
"Fed funds path (dots plot), real rates (TIPS), term premium, fiscal deficit trajectory, inflation breakevens, foreign central bank demand (Japan/China UST), credit spreads, duration risk.",
|
||||
'[{"regime":"hawkish_fed","effect":"bearish long duration (TLT), bearish EM bonds"},{"regime":"recession_confirmed","effect":"bullish long bonds (flight to quality)"},{"regime":"fiscal_expansion","effect":"bearish bonds (supply pressure)"},{"regime":"disinflation","effect":"bullish bonds, real rate normalization"}]',
|
||||
'{"significant_day":0.5,"extreme_day":1.5,"significant_week":1.0,"extreme_week":3.0}'),
|
||||
]
|
||||
for _ac, _dn, _ic, _fund, _macro, _thresh in _desk_defaults:
|
||||
c.execute("""INSERT OR IGNORE INTO asset_class_configs
|
||||
(asset_class, display_name, icon, fundamentals, macro_sensitivity, price_delta_thresholds)
|
||||
VALUES (?,?,?,?,?,?)""", (_ac, _dn, _ic, _fund, _macro, _thresh))
|
||||
|
||||
# Seed default reports (idempotent)
|
||||
_rpt_count = c.execute("SELECT COUNT(*) FROM specialist_reports").fetchone()[0]
|
||||
if _rpt_count == 0:
|
||||
import uuid as _uuid
|
||||
_rpt_defaults = [
|
||||
("RPT_COT", "COT — Commitment of Traders", "CFTC", "weekly", 3, ["metals","forex","agri","energy"]),
|
||||
("RPT_EIA", "EIA Petroleum Status Report", "EIA", "weekly", 3, ["energy"]),
|
||||
("RPT_WASDE", "WASDE — World Ag Supply & Demand", "USDA", "monthly", 3, ["agri"]),
|
||||
("RPT_FOMC", "FOMC Statement & Projections", "Federal Reserve","6-weekly", 3, ["forex","indices","bonds"]),
|
||||
("RPT_ECB", "ECB Monetary Policy Decision", "ECB", "6-weekly", 3, ["forex","bonds"]),
|
||||
("RPT_CPI", "US CPI (Consumer Price Index)", "BLS", "monthly", 3, ["forex","indices","bonds","metals"]),
|
||||
("RPT_NFP", "US Non-Farm Payrolls", "BLS", "monthly", 3, ["forex","indices","bonds"]),
|
||||
("RPT_CN_PMI", "China PMI (NBS Manufacturing)", "NBS China", "monthly", 2, ["metals","agri","energy","indices"]),
|
||||
("RPT_BAKER", "Baker Hughes Rig Count", "Baker Hughes", "weekly", 2, ["energy"]),
|
||||
("RPT_EXPORT", "USDA Weekly Export Inspections", "USDA", "weekly", 2, ["agri"]),
|
||||
("RPT_BOJ", "BOJ Monetary Policy Decision", "Bank of Japan", "irregular", 2, ["forex","bonds"]),
|
||||
("RPT_VIX", "VIX Futures Monthly Settlement", "CBOE", "monthly", 2, ["indices"]),
|
||||
]
|
||||
for _rid, _rname, _rsrc, _rcad, _rimp, _racs in _rpt_defaults:
|
||||
c.execute("""INSERT OR IGNORE INTO specialist_reports (id, name, source, cadence, importance)
|
||||
VALUES (?,?,?,?,?)""", (_rid, _rname, _rsrc, _rcad, _rimp))
|
||||
for _rac in _racs:
|
||||
c.execute("INSERT OR IGNORE INTO report_desk_links (report_id, asset_class) VALUES (?,?)",
|
||||
(_rid, _rac))
|
||||
|
||||
try:
|
||||
c.execute("CREATE INDEX IF NOT EXISTS idx_kb_category ON knowledge_base(category, status)")
|
||||
c.execute("CREATE INDEX IF NOT EXISTS idx_rs_version ON reasoning_state(version DESC)")
|
||||
@@ -3918,3 +4013,170 @@ def get_economic_events_for_calendar(days_back: int = 30, days_forward: int = 14
|
||||
return result
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
# ── Specialist Desks ──────────────────────────────────────────────────────────
|
||||
|
||||
def get_all_specialist_reports() -> List[Dict[str, Any]]:
|
||||
conn = get_conn()
|
||||
try:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM specialist_reports ORDER BY importance DESC, name ASC"
|
||||
).fetchall()
|
||||
result = []
|
||||
for r in rows:
|
||||
d = dict(r)
|
||||
d["desks"] = [
|
||||
lnk["asset_class"] for lnk in
|
||||
conn.execute(
|
||||
"SELECT asset_class FROM report_desk_links WHERE report_id=?", (d["id"],)
|
||||
).fetchall()
|
||||
]
|
||||
result.append(d)
|
||||
return result
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def upsert_specialist_report(
|
||||
report_id: str, name: str, source: str, cadence: str,
|
||||
next_date: Optional[str], last_date: Optional[str],
|
||||
importance: int, notes: str, url: str,
|
||||
) -> str:
|
||||
conn = get_conn()
|
||||
try:
|
||||
conn.execute("""INSERT INTO specialist_reports
|
||||
(id, name, source, cadence, next_date, last_date, importance, notes, url, updated_at)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,datetime('now'))
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
name=excluded.name, source=excluded.source, cadence=excluded.cadence,
|
||||
next_date=excluded.next_date, last_date=excluded.last_date,
|
||||
importance=excluded.importance, notes=excluded.notes, url=excluded.url,
|
||||
updated_at=datetime('now')""",
|
||||
(report_id, name, source, cadence, next_date or None, last_date or None,
|
||||
importance, notes, url))
|
||||
conn.commit()
|
||||
return report_id
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def delete_specialist_report(report_id: str) -> bool:
|
||||
conn = get_conn()
|
||||
try:
|
||||
conn.execute("DELETE FROM report_desk_links WHERE report_id=?", (report_id,))
|
||||
conn.execute("DELETE FROM specialist_reports WHERE id=?", (report_id,))
|
||||
conn.commit()
|
||||
return True
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def link_report_desk(report_id: str, asset_class: str) -> bool:
|
||||
conn = get_conn()
|
||||
try:
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO report_desk_links (report_id, asset_class) VALUES (?,?)",
|
||||
(report_id, asset_class)
|
||||
)
|
||||
conn.commit()
|
||||
return True
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def unlink_report_desk(report_id: str, asset_class: str) -> bool:
|
||||
conn = get_conn()
|
||||
try:
|
||||
conn.execute(
|
||||
"DELETE FROM report_desk_links WHERE report_id=? AND asset_class=?",
|
||||
(report_id, asset_class)
|
||||
)
|
||||
conn.commit()
|
||||
return True
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_desk_reports(asset_class: str) -> List[Dict[str, Any]]:
|
||||
conn = get_conn()
|
||||
try:
|
||||
rows = conn.execute("""
|
||||
SELECT sr.* FROM specialist_reports sr
|
||||
JOIN report_desk_links rdl ON rdl.report_id = sr.id
|
||||
WHERE rdl.asset_class = ?
|
||||
ORDER BY sr.importance DESC, sr.name ASC""", (asset_class,)).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_all_asset_class_configs() -> List[Dict[str, Any]]:
|
||||
conn = get_conn()
|
||||
try:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM asset_class_configs ORDER BY asset_class ASC"
|
||||
).fetchall()
|
||||
result = []
|
||||
for r in rows:
|
||||
d = dict(r)
|
||||
try:
|
||||
d["macro_sensitivity"] = json.loads(d.get("macro_sensitivity") or "[]")
|
||||
except Exception:
|
||||
d["macro_sensitivity"] = []
|
||||
try:
|
||||
d["price_delta_thresholds"] = json.loads(d.get("price_delta_thresholds") or "{}")
|
||||
except Exception:
|
||||
d["price_delta_thresholds"] = {}
|
||||
d["reports"] = get_desk_reports(d["asset_class"])
|
||||
result.append(d)
|
||||
return result
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_asset_class_config(asset_class: str) -> Optional[Dict[str, Any]]:
|
||||
conn = get_conn()
|
||||
try:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM asset_class_configs WHERE asset_class=?", (asset_class,)
|
||||
).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
d = dict(row)
|
||||
try:
|
||||
d["macro_sensitivity"] = json.loads(d.get("macro_sensitivity") or "[]")
|
||||
except Exception:
|
||||
d["macro_sensitivity"] = []
|
||||
try:
|
||||
d["price_delta_thresholds"] = json.loads(d.get("price_delta_thresholds") or "{}")
|
||||
except Exception:
|
||||
d["price_delta_thresholds"] = {}
|
||||
return d
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def upsert_asset_class_config(
|
||||
asset_class: str, display_name: str, icon: str,
|
||||
fundamentals: str, macro_sensitivity: list,
|
||||
price_delta_thresholds: dict, notes: str,
|
||||
) -> bool:
|
||||
conn = get_conn()
|
||||
try:
|
||||
conn.execute("""INSERT INTO asset_class_configs
|
||||
(asset_class, display_name, icon, fundamentals, macro_sensitivity,
|
||||
price_delta_thresholds, notes, updated_at)
|
||||
VALUES (?,?,?,?,?,?,?,datetime('now'))
|
||||
ON CONFLICT(asset_class) DO UPDATE SET
|
||||
display_name=excluded.display_name, icon=excluded.icon,
|
||||
fundamentals=excluded.fundamentals,
|
||||
macro_sensitivity=excluded.macro_sensitivity,
|
||||
price_delta_thresholds=excluded.price_delta_thresholds,
|
||||
notes=excluded.notes, updated_at=datetime('now')""",
|
||||
(asset_class, display_name, icon, fundamentals,
|
||||
json.dumps(macro_sensitivity), json.dumps(price_delta_thresholds), notes))
|
||||
conn.commit()
|
||||
return True
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
Reference in New Issue
Block a user