Cisco Ponce commited on
Commit
2c6cc1b
·
1 Parent(s): 5201c65

feat(review-gate): stage analyses instead of auto-trading

Browse files

Implements the proposal.md 3-layer framework review gate:
- InvestmentVerdict gains framework fields (scenarios, sources,
data-quality flags, proposed action, review trigger)
- Senior Broker prompt requests the structured framework output
- portfolio_tracker: submit_analysis / get_pending_reviews /
accept_decision / dismiss_decision against the VPS review gate
- whale_hunter: discovery stages a watchlist analysis (INITIATE /
PENDING / DISCARD) instead of recording a trade or hitting Alpaca
- reeval: re-evals submit analyses; only MAINTAIN refreshes the ledger;
INCREASE/REDUCE/CLOSE/INITIATE wait for explicit acceptance
- vps/schema.sql: analyses + watchlist tables, paper_portfolio.analysis_id

src/models/verdict.py CHANGED
@@ -40,6 +40,72 @@ class InvestmentVerdict(BaseModel):
40
  description="Number of trades used for Kelly calc (set post-LLM)",
41
  )
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  def to_report(self) -> str:
44
  """Render as the markdown report format the pipeline expects."""
45
  qb = _strip_headers(self.quantitative_base)
 
40
  description="Number of trades used for Kelly calc (set post-LLM)",
41
  )
42
 
43
+ # --- 3-layer framework fields (proposal.md) — all optional, filled by the
44
+ # --- Senior Broker when data supports them. No universal thresholds. -------
45
+ business_summary: str | None = Field(
46
+ default=None, description="One paragraph: business model + sector"
47
+ )
48
+ financial_evolution: str | None = Field(
49
+ default=None, description="Revenue / EPS / EBITDA trend over recent periods"
50
+ )
51
+ cash_flow: str | None = Field(
52
+ default=None, description="Operating cash flow vs net income, FCF sign & trajectory"
53
+ )
54
+ debt_liquidity: str | None = Field(
55
+ default=None, description="Total debt, D/E, current ratio, refinancing risk"
56
+ )
57
+ dilution: str | None = Field(
58
+ default=None, description="Share-count trend, shelf/ATM risk, recent raises"
59
+ )
60
+ valuation_method: str | None = Field(
61
+ default=None, description="Method(s) used (multiples, DCF, asset-based) — never one formula alone"
62
+ )
63
+ valuation_bear: str | None = Field(
64
+ default=None, description="Bear scenario value + the assumption driving it"
65
+ )
66
+ valuation_base: str | None = Field(
67
+ default=None, description="Base scenario value + the assumption driving it"
68
+ )
69
+ valuation_bull: str | None = Field(
70
+ default=None, description="Bull scenario value + the assumption driving it"
71
+ )
72
+ valuation_range_low: float | None = Field(
73
+ default=None, description="Low end of the fair-value range (number only)"
74
+ )
75
+ valuation_range_high: float | None = Field(
76
+ default=None, description="High end of the fair-value range (number only)"
77
+ )
78
+ margin_of_safety: str | None = Field(
79
+ default=None, description="Current price vs base-scenario value as a %"
80
+ )
81
+ risks: str | None = Field(
82
+ default=None, description="Top 3-5 specific risks, each with why"
83
+ )
84
+ invalidation_facts: str | None = Field(
85
+ default=None, description="Exact facts whose publication would break the thesis"
86
+ )
87
+ macro_factors: str | None = Field(
88
+ default=None, description="Rate / inflation / sector-cycle links that matter"
89
+ )
90
+ portfolio_fit: str | None = Field(
91
+ default=None, description="Position size vs cap, sector overlap, liquidity"
92
+ )
93
+ sources: list | None = Field(
94
+ default=None, description="[{type,url,date,period}] cited per quantitative claim; published vs estimates vs inferences separated"
95
+ )
96
+ data_quality: dict | None = Field(
97
+ default=None, description="{facts, estimates, inferences, unverified, pending}"
98
+ )
99
+ proposed_action: str | None = Field(
100
+ default=None, description="INITIATE|MAINTAIN|INCREASE|REDUCE|CLOSE|DISCARD|PENDING"
101
+ )
102
+ review_trigger: str | None = Field(
103
+ default=None, description="Market/company event that triggers the next review"
104
+ )
105
+ next_review_at: str | None = Field(
106
+ default=None, description="Concrete next-review date (YYYY-MM-DD)"
107
+ )
108
+
109
  def to_report(self) -> str:
110
  """Render as the markdown report format the pipeline expects."""
111
  qb = _strip_headers(self.quantitative_base)
src/portfolio_tracker.py CHANGED
@@ -148,6 +148,155 @@ def record_paper_trade(
148
  logger.error("Error recording paper trade: %s", exc)
149
 
150
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  def evaluate_portfolio() -> str:
152
  """Read the paper portfolio and calculate live performance."""
153
 
 
148
  logger.error("Error recording paper trade: %s", exc)
149
 
150
 
151
+ # ---------------------------------------------------------------------------
152
+ # 3-layer framework: submit analyses -> stage on watchlist -> review gate
153
+ # (proposal.md). Analyses NEVER execute orders. A trade is only recorded after
154
+ # an explicit accept (human via dashboard/Chainlit, or API).
155
+ # ---------------------------------------------------------------------------
156
+
157
+ ANALYSIS_FILE = "analyses.json"
158
+
159
+ # Fields we lift from a structured InvestmentVerdict into the analysis payload
160
+ _FRAMEWORK_FIELDS = [
161
+ "business_summary", "financial_evolution", "cash_flow", "debt_liquidity",
162
+ "dilution", "valuation_method", "valuation_bear", "valuation_base",
163
+ "valuation_bull", "valuation_range_low", "valuation_range_high",
164
+ "margin_of_safety", "risks", "invalidation_facts", "macro_factors",
165
+ "portfolio_fit", "sources", "data_quality", "review_trigger", "next_review_at",
166
+ ]
167
+
168
+
169
+ def _pick(obj, name):
170
+ """Read a field from a pydantic model or dict, tolerating missing attrs."""
171
+ if obj is None:
172
+ return None
173
+ try:
174
+ value = getattr(obj, name)
175
+ except AttributeError:
176
+ value = obj.get(name) if isinstance(obj, dict) else None
177
+ if value in (None, "", [], {}):
178
+ return None
179
+ return value
180
+
181
+
182
+ def _framework_payload(structured=None, proposed_action=None) -> dict:
183
+ """Extract the 3-layer framework fields from a structured verdict."""
184
+ payload = {name: _pick(structured, name) for name in _FRAMEWORK_FIELDS}
185
+ if proposed_action:
186
+ payload["proposed_action"] = proposed_action
187
+ elif structured is not None:
188
+ payload["proposed_action"] = _pick(structured, "proposed_action")
189
+ if isinstance(payload.get("sources"), list):
190
+ payload["sources"] = [
191
+ s if isinstance(s, dict) else {"type": "self", "url": None, "value": str(s)}
192
+ for s in payload["sources"]
193
+ ]
194
+ return payload
195
+
196
+
197
+ def submit_analysis(
198
+ ticker: str,
199
+ price: float,
200
+ source: str,
201
+ verdict: str | None = None,
202
+ report_text: str | None = None,
203
+ position_size: float = 0.0,
204
+ structured=None,
205
+ proposed_action: str | None = None,
206
+ ) -> dict | None:
207
+ """Submit a framework-compliant analysis and stage the ticker for review.
208
+
209
+ Replaces automatic paper-trading: the analysis lands on the watchlist /
210
+ review queue, and a paper trade is only recorded after an explicit accept.
211
+ Never executes a broker order by itself.
212
+ """
213
+ payload = {
214
+ "ticker": ticker,
215
+ "stage": None, # VPS derives stage from verdict
216
+ "verdict": verdict,
217
+ "source": source,
218
+ "price": float(price) if price else None,
219
+ "currency": "USD",
220
+ "report_text": report_text,
221
+ "position_size": float(position_size or 0),
222
+ **_framework_payload(structured, proposed_action=proposed_action),
223
+ }
224
+ payload = {k: v for k, v in payload.items() if v is not None}
225
+
226
+ if VPS_API_URL:
227
+ try:
228
+ resp = requests.post(
229
+ f"{VPS_API_URL}/analyses", headers=_vps_headers(), json=payload, timeout=10,
230
+ )
231
+ resp.raise_for_status()
232
+ data = resp.json()
233
+ logger.info("Analysis submitted (VPS): %s stage=%s",
234
+ ticker, data.get("stage", "?"))
235
+ return data
236
+ except Exception as exc:
237
+ logger.warning("submit_analysis failed (VPS), using local fallback: %s", exc)
238
+
239
+ # Local fallback (keeps behavior when VPS is unreachable)
240
+ try:
241
+ records = []
242
+ if os.path.exists(ANALYSIS_FILE):
243
+ with open(ANALYSIS_FILE, "r") as f:
244
+ records = json.load(f)
245
+ records.append({**payload, "analyzed_at": datetime.now().isoformat()})
246
+ with open(ANALYSIS_FILE, "w") as f:
247
+ json.dump(records, f, indent=2)
248
+ logger.info("Analysis submitted (local fallback): %s", ticker)
249
+ return {"status": "ok", "ticker": ticker}
250
+ except Exception as exc:
251
+ logger.error("submit_analysis local fallback failed: %s", exc)
252
+ return None
253
+
254
+
255
+ def get_pending_reviews() -> list:
256
+ """Active watchlist items awaiting an accept/dismiss decision."""
257
+ if not VPS_API_URL:
258
+ return []
259
+ try:
260
+ resp = requests.get(
261
+ f"{VPS_API_URL}/portfolio/reviews", headers=_vps_headers(), timeout=10,
262
+ )
263
+ resp.raise_for_status()
264
+ return resp.json()
265
+ except Exception as exc:
266
+ logger.warning("get_pending_reviews failed: %s", exc)
267
+ return []
268
+
269
+
270
+ def accept_decision(ticker: str, action: str | None = None,
271
+ position_size: float | None = None,
272
+ entry_price: float | None = None) -> dict | None:
273
+ """Accept a staged analysis — the VPS writes the paper trade (no orders)."""
274
+ if not VPS_API_URL:
275
+ logger.warning("accept_decision skipped: VPS_API_URL not set")
276
+ return None
277
+ body = {"action": action, "position_size": position_size, "entry_price": entry_price}
278
+ body = {k: v for k, v in body.items() if v is not None}
279
+ resp = requests.post(
280
+ f"{VPS_API_URL}/watchlist/{ticker}/accept",
281
+ headers=_vps_headers(), json=body, timeout=10,
282
+ )
283
+ resp.raise_for_status()
284
+ return resp.json()
285
+
286
+
287
+ def dismiss_decision(ticker: str) -> dict | None:
288
+ """Dismiss a staged analysis without recording any trade."""
289
+ if not VPS_API_URL:
290
+ logger.warning("dismiss_decision skipped: VPS_API_URL not set")
291
+ return None
292
+ resp = requests.post(
293
+ f"{VPS_API_URL}/watchlist/{ticker}/dismiss",
294
+ headers=_vps_headers(), timeout=10,
295
+ )
296
+ resp.raise_for_status()
297
+ return resp.json()
298
+
299
+
300
  def evaluate_portfolio() -> str:
301
  """Read the paper portfolio and calculate live performance."""
302
 
src/prompts/senior_broker.py CHANGED
@@ -45,6 +45,33 @@ Format your response EXACTLY like this:
45
 
46
  ### FINAL VERDICT
47
  STRONG BUY / BUY / WATCH / AVOID (Choose one, followed by a 1-sentence bottom line).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  """
49
 
50
 
 
45
 
46
  ### FINAL VERDICT
47
  STRONG BUY / BUY / WATCH / AVOID (Choose one, followed by a 1-sentence bottom line).
48
+
49
+ ### FRAMEWORK OUTPUT (structured fields — 3-layer method)
50
+ Fill every structured field you emit for which the data supports an answer; otherwise leave it blank and say so under data_quality. No fluff.
51
+
52
+ - business_summary: one paragraph on the business model and its sector.
53
+ - financial_evolution: 3-4 lines of revenue / EPS / EBITDA trend over recent periods.
54
+ - cash_flow: operating cash flow vs net income, FCF sign and trajectory.
55
+ - debt_liquidity: total debt, debt/equity, current ratio, refinancing risk.
56
+ - dilution: share-count trend, shelf/ATM risk, recent raises.
57
+ - valuation_method: the method(s) used (multiples, DCF, asset-based, sum-of-parts). NEVER rely on a single formula in isolation; triangulate.
58
+ - valuation_bear / valuation_base / valuation_bull: a number for each scenario WITH the one assumption driving it.
59
+ - valuation_range_low / valuation_range_high: the numeric fair-value range (numbers only).
60
+ - margin_of_safety: current price vs the base scenario as a %.
61
+ - risks: the top 3-5 SPECIFIC risks, each with the reason it matters for this name.
62
+ - invalidation_facts: the exact fact(s) (metric, filing, event) whose publication would break the thesis.
63
+ - macro_factors: the rate / inflation / sector-cycle links that actually affect the outcome.
64
+ - portfolio_fit: how this fits a diversified portfolio — position cap, sector overlap, liquidity.
65
+ - sources: list each quantitative claim used, as [{type,url,date,period}] (filings/price/analyst/news). SEPARATE published facts from your estimates and from your inferences. Mark anything not verified as "no verificado".
66
+ - data_quality: which inputs are published facts, which are estimates, which are your inferences, and which data is PENDING and would change the conclusion.
67
+ - proposed_action: one of INITIATE / MAINTAIN / INCREASE / REDUCE / CLOSE / DISCARD / PENDING.
68
+ - review_trigger: the concrete market or company event that should trigger the next review.
69
+ - next_review_at: a concrete date (YYYY-MM-DD).
70
+
71
+ Rules (never break these):
72
+ - No universal PER / debt / valuation thresholds as the conclusion.
73
+ - A price alert is NOT an order — it only starts a review; never propose an automatic buy/sell.
74
+ - If valuation, risk or portfolio-fit data is missing, say so and mark the conclusion provisional.
75
  """
76
 
77
 
src/reeval_portfolio.py CHANGED
@@ -32,7 +32,7 @@ from src.finance_tools import (
32
  get_company_news,
33
  get_basic_financials,
34
  )
35
- from src.portfolio_tracker import record_paper_trade
36
  from src.discovery.insider_feed import get_insider_buys
37
  from src.email_utils import send_email_report
38
 
@@ -148,6 +148,7 @@ def analyse_ticker(ticker: str, company_name: str, info: dict) -> Optional[dict]
148
  "report": report,
149
  "position_size": result.position_size,
150
  "price": price,
 
151
  }
152
  except Exception as exc:
153
  logger.warning("Debate failed for %s, falling back: %s", ticker, exc)
@@ -261,14 +262,34 @@ def main():
261
  new_verdict = analysis["verdict"]
262
  changed = new_verdict != old_verdict
263
 
264
- # Record the re-evaluated trade (this handles Alpaca + VPS automatically)
265
- record_paper_trade(
266
- ticker, analysis["price"], analysis["report"],
267
- source="reeval_cron",
268
- structured_verdict=new_verdict,
 
 
 
 
 
 
 
 
 
 
269
  position_size=analysis["position_size"],
 
 
270
  )
271
 
 
 
 
 
 
 
 
 
272
  # Online eval feedback
273
  _run_id = get_current_run_id()
274
  log_online_feedback(analysis["report"], ticker, run_id=_run_id)
 
32
  get_company_news,
33
  get_basic_financials,
34
  )
35
+ from src.portfolio_tracker import record_paper_trade, submit_analysis
36
  from src.discovery.insider_feed import get_insider_buys
37
  from src.email_utils import send_email_report
38
 
 
148
  "report": report,
149
  "position_size": result.position_size,
150
  "price": price,
151
+ "structured": result,
152
  }
153
  except Exception as exc:
154
  logger.warning("Debate failed for %s, falling back: %s", ticker, exc)
 
262
  new_verdict = analysis["verdict"]
263
  changed = new_verdict != old_verdict
264
 
265
+ # proposal.md review gate: every re-eval becomes a structured analysis
266
+ # staged on the watchlist. Only "MAINTAIN" refreshes the ledger
267
+ # automatically (informational — WATCH, never an order). INCREASE /
268
+ # REDUCE / CLOSE / INITIATE wait for an explicit accept (dashboard/API).
269
+ proposed_action = {
270
+ "STRONG BUY": "INCREASE",
271
+ "BUY": "INCREASE",
272
+ "WATCH": "MAINTAIN",
273
+ "AVOID": "CLOSE",
274
+ }.get(new_verdict, "PENDING")
275
+
276
+ submit_analysis(
277
+ ticker, analysis["price"], source="reeval_cron",
278
+ verdict=new_verdict,
279
+ report_text=analysis["report"],
280
  position_size=analysis["position_size"],
281
+ structured=analysis.get("structured"),
282
+ proposed_action=proposed_action,
283
  )
284
 
285
+ if proposed_action == "MAINTAIN":
286
+ record_paper_trade(
287
+ ticker, analysis["price"], analysis["report"],
288
+ source="reeval_cron",
289
+ structured_verdict=new_verdict,
290
+ position_size=analysis["position_size"],
291
+ )
292
+
293
  # Online eval feedback
294
  _run_id = get_current_run_id()
295
  log_online_feedback(analysis["report"], ticker, run_id=_run_id)
src/whale_hunter.py CHANGED
@@ -33,7 +33,7 @@ from src.finance_tools import (
33
  get_company_news,
34
  get_basic_financials,
35
  )
36
- from src.portfolio_tracker import record_paper_trade
37
  from src.email_utils import send_email_report
38
 
39
  from src.core.logger import get_logger
@@ -264,6 +264,19 @@ def build_value_snapshot(info: dict, ticker: str, currency: str) -> str:
264
  return "\n".join(lines)
265
 
266
 
 
 
 
 
 
 
 
 
 
 
 
 
 
267
  def analyst_node(state):
268
  """Senior Broker analysis with Graham Number, Finnhub data, and insider signals."""
269
  ticker = state["ticker"]
@@ -370,9 +383,12 @@ def analyst_node(state):
370
  result.kelly_total_trades = stats.total_trades
371
 
372
  verdict = result.to_report()
373
- record_paper_trade(ticker, price, verdict, source="Morning Cron",
374
- structured_verdict=result.verdict,
375
- position_size=result.position_size)
 
 
 
376
 
377
  _run_id = get_current_run_id()
378
  log_online_feedback(verdict, ticker, run_id=_run_id)
@@ -432,9 +448,12 @@ def analyst_node(state):
432
  result.kelly_total_trades = stats.total_trades
433
 
434
  verdict = result.to_report()
435
- record_paper_trade(ticker, price, verdict, source="Morning Cron",
436
- structured_verdict=result.verdict,
437
- position_size=result.position_size)
 
 
 
438
  _run_id = get_current_run_id()
439
  log_online_feedback(verdict, ticker, run_id=_run_id)
440
  tag_for_review(verdict, ticker, run_id=_run_id)
@@ -457,8 +476,11 @@ def analyst_node(state):
457
  f"\n\n### POSITION SIZING (Kelly Criterion)\n"
458
  f"**Recommended allocation: {pos:.1f}% of portfolio**"
459
  )
460
- record_paper_trade(ticker, price, verdict, source="Morning Cron",
461
- position_size=pos)
 
 
 
462
  _run_id = get_current_run_id()
463
  log_online_feedback(verdict, ticker, run_id=_run_id, is_fallback=True)
464
  tag_for_review(verdict, ticker, run_id=_run_id, is_fallback=True)
 
33
  get_company_news,
34
  get_basic_financials,
35
  )
36
+ from src.portfolio_tracker import submit_analysis
37
  from src.email_utils import send_email_report
38
 
39
  from src.core.logger import get_logger
 
264
  return "\n".join(lines)
265
 
266
 
267
+ def _new_position_action(verdict: str) -> str:
268
+ """proposal.md action for a NEW ticker staged by the automated hunter.
269
+
270
+ Discovery results never trade by themselves — they go to the review gate.
271
+ """
272
+ upper = (verdict or "").upper()
273
+ if "STRONG BUY" in upper or upper == "BUY":
274
+ return "INITIATE"
275
+ if upper == "WATCH":
276
+ return "PENDING"
277
+ return "DISCARD"
278
+
279
+
280
  def analyst_node(state):
281
  """Senior Broker analysis with Graham Number, Finnhub data, and insider signals."""
282
  ticker = state["ticker"]
 
383
  result.kelly_total_trades = stats.total_trades
384
 
385
  verdict = result.to_report()
386
+ submit_analysis(ticker, price, source="Morning Cron",
387
+ verdict=result.verdict,
388
+ report_text=verdict,
389
+ position_size=result.position_size,
390
+ structured=result,
391
+ proposed_action=_new_position_action(result.verdict))
392
 
393
  _run_id = get_current_run_id()
394
  log_online_feedback(verdict, ticker, run_id=_run_id)
 
448
  result.kelly_total_trades = stats.total_trades
449
 
450
  verdict = result.to_report()
451
+ submit_analysis(ticker, price, source="Morning Cron",
452
+ verdict=result.verdict,
453
+ report_text=verdict,
454
+ position_size=result.position_size,
455
+ structured=result,
456
+ proposed_action=_new_position_action(result.verdict))
457
  _run_id = get_current_run_id()
458
  log_online_feedback(verdict, ticker, run_id=_run_id)
459
  tag_for_review(verdict, ticker, run_id=_run_id)
 
476
  f"\n\n### POSITION SIZING (Kelly Criterion)\n"
477
  f"**Recommended allocation: {pos:.1f}% of portfolio**"
478
  )
479
+ submit_analysis(ticker, price, source="Morning Cron",
480
+ verdict=verdict_type,
481
+ report_text=verdict,
482
+ position_size=pos,
483
+ proposed_action=_new_position_action(verdict_type))
484
  _run_id = get_current_run_id()
485
  log_online_feedback(verdict, ticker, run_id=_run_id, is_fallback=True)
486
  tag_for_review(verdict, ticker, run_id=_run_id, is_fallback=True)
vps/schema.sql CHANGED
@@ -21,6 +21,7 @@ CREATE TABLE IF NOT EXISTS paper_portfolio (
21
  order_id VARCHAR,
22
  fill_price DOUBLE,
23
  broker_status VARCHAR DEFAULT 'none',
 
24
  created_at TIMESTAMP DEFAULT current_timestamp,
25
  UNIQUE (ticker, date) -- prevent duplicate same-day entries
26
  );
@@ -37,3 +38,52 @@ CREATE TABLE IF NOT EXISTS agent_runs (
37
  latency_ms INTEGER,
38
  region VARCHAR DEFAULT 'USA'
39
  );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  order_id VARCHAR,
22
  fill_price DOUBLE,
23
  broker_status VARCHAR DEFAULT 'none',
24
+ analysis_id INTEGER, -- link to the accepted analysis (review gate)
25
  created_at TIMESTAMP DEFAULT current_timestamp,
26
  UNIQUE (ticker, date) -- prevent duplicate same-day entries
27
  );
 
38
  latency_ms INTEGER,
39
  region VARCHAR DEFAULT 'USA'
40
  );
41
+
42
+ -- Structured investment analyses (proposal.md 3-layer framework)
43
+ CREATE SEQUENCE IF NOT EXISTS analysis_seq START 1;
44
+
45
+ CREATE TABLE IF NOT EXISTS analyses (
46
+ id INTEGER PRIMARY KEY DEFAULT nextval('analysis_seq'),
47
+ ticker VARCHAR NOT NULL,
48
+ analyzed_at TIMESTAMP DEFAULT current_timestamp,
49
+ stage VARCHAR NOT NULL, -- RESEARCH | WATCHLIST | BUY_CANDIDATE | DISCARD
50
+ verdict VARCHAR, -- STRONG BUY | BUY | WATCH | AVOID (legacy label)
51
+ source VARCHAR DEFAULT 'unknown',
52
+ price DOUBLE,
53
+ currency VARCHAR DEFAULT 'USD',
54
+ business_summary TEXT,
55
+ financial_evolution TEXT,
56
+ cash_flow TEXT,
57
+ debt_liquidity TEXT,
58
+ dilution TEXT,
59
+ valuation_method TEXT,
60
+ valuation_bear TEXT,
61
+ valuation_base TEXT,
62
+ valuation_bull TEXT,
63
+ valuation_range_low DOUBLE,
64
+ valuation_range_high DOUBLE,
65
+ margin_of_safety TEXT,
66
+ risks TEXT,
67
+ invalidation_facts TEXT,
68
+ macro_factors TEXT,
69
+ portfolio_fit TEXT,
70
+ sources TEXT, -- JSON: [{type,url,date,period}]
71
+ data_quality TEXT, -- JSON: {facts,estimates,inferences,unverified,pending}
72
+ proposed_action VARCHAR, -- PENDING|INITIATE|MAINTAIN|INCREASE|REDUCE|CLOSE|DISCARD
73
+ review_trigger TEXT,
74
+ next_review_at DATE,
75
+ report_text TEXT,
76
+ position_size DOUBLE DEFAULT 0,
77
+ created_at TIMESTAMP DEFAULT current_timestamp
78
+ );
79
+
80
+ -- Watchlist funnel: research stage -> accept/dismiss decision gate
81
+ CREATE TABLE IF NOT EXISTS watchlist (
82
+ ticker VARCHAR NOT NULL PRIMARY KEY,
83
+ stage VARCHAR NOT NULL,
84
+ source VARCHAR DEFAULT 'unknown',
85
+ analysis_id INTEGER,
86
+ reason TEXT,
87
+ added_at TIMESTAMP DEFAULT current_timestamp,
88
+ status VARCHAR DEFAULT 'active' -- active | accepted | dismissed
89
+ );