s-ttp commited on
Commit
f2aabea
·
verified ·
1 Parent(s): e10211f

Upload engine/predict_yearly.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. engine/predict_yearly.py +89 -8
engine/predict_yearly.py CHANGED
@@ -4484,6 +4484,64 @@ def _call_claude_yearly(user_msg, system=None, verbose=False):
4484
  return None
4485
 
4486
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4487
  def analyze_llm_debate_yearly(
4488
  ticker,
4489
  current_price,
@@ -4516,7 +4574,11 @@ def analyze_llm_debate_yearly(
4516
  _llm_cache_key = f"llm_debate_yearly_{ticker}_{_date_str}" + ("_gclass" if class_note else "")
4517
  _llm_cache_file = CACHE_DIR / f"{_llm_cache_key}.json"
4518
  _llm_meta_file = CACHE_DIR / f"{_llm_cache_key}.meta.json"
4519
- if not no_cache and _llm_cache_file.exists() and _llm_meta_file.exists():
 
 
 
 
4520
  try:
4521
  _meta = json.loads(_llm_meta_file.read_text())
4522
  _age = (datetime.now() - datetime.fromisoformat(_meta["cached_at"])).total_seconds()
@@ -4629,6 +4691,7 @@ def analyze_llm_debate_yearly(
4629
  print(f" {'Gemini (Neutral)':<20} {rc}{neutral_result['expected_return']*100:+.1f}%{RESET} "
4630
  f"{neutral_result.get('recommendation','HOLD'):<11} "
4631
  f"conf:{neutral_result['confidence']*100:.0f}%")
 
4632
  else:
4633
  print(f" {'Gemini (Neutral)':<20} {YELLOW}parse failed (check verbose){RESET}")
4634
  except Exception as e:
@@ -4674,6 +4737,7 @@ def analyze_llm_debate_yearly(
4674
  rc = GREEN if bear_r1["expected_return"] > 0 else RED
4675
  print(f" {'Kimi (Bear)':<20} {rc}{bear_r1['expected_return']*100:+.1f}%{RESET} "
4676
  f"{bear_r1.get('recommendation','HOLD'):<11} conf:{bear_r1['confidence']*100:.0f}%")
 
4677
  except Exception as e:
4678
  print(f" {'Kimi (Bear)':<20} {RED}{str(e)[:60]}{RESET}")
4679
 
@@ -4686,6 +4750,7 @@ def analyze_llm_debate_yearly(
4686
  rc = GREEN if bull_r1["expected_return"] > 0 else RED
4687
  print(f" {'GPT (Bull)':<20} {rc}{bull_r1['expected_return']*100:+.1f}%{RESET} "
4688
  f"{bull_r1.get('recommendation','HOLD'):<11} conf:{bull_r1['confidence']*100:.0f}%")
 
4689
  except Exception as e:
4690
  print(f" {'GPT (Bull)':<20} {RED}{str(e)[:60]}{RESET}")
4691
  _ex2.shutdown(wait=True)
@@ -4749,6 +4814,7 @@ def analyze_llm_debate_yearly(
4749
  tag = f"{YELLOW}REVISED{RESET}" if changed else f"{DIM}held{RESET}"
4750
  print(f" {'Kimi (Bear)':<20} {rc}{bear_rebuttal['expected_return']*100:+.1f}%{RESET} "
4751
  f"{bear_rebuttal.get('recommendation','HOLD'):<11} {tag}")
 
4752
  except Exception as e:
4753
  print(f" {'Kimi (Bear)':<20} {RED}{str(e)[:60]}{RESET}")
4754
 
@@ -4764,6 +4830,7 @@ def analyze_llm_debate_yearly(
4764
  tag = f"{YELLOW}REVISED{RESET}" if changed else f"{DIM}held{RESET}"
4765
  print(f" {'GPT (Bull)':<20} {rc}{bull_rebuttal['expected_return']*100:+.1f}%{RESET} "
4766
  f"{bull_rebuttal.get('recommendation','HOLD'):<11} {tag}")
 
4767
  except Exception as e:
4768
  print(f" {'GPT (Bull)':<20} {RED}{str(e)[:60]}{RESET}")
4769
  _ex3.shutdown(wait=True)
@@ -4787,7 +4854,7 @@ def analyze_llm_debate_yearly(
4787
  _bl_price = _bl.get("predicted_price") or current_price * (1 + _bl["expected_return"])
4788
  try:
4789
  pm_synthesis = _call_claude_synthesis(
4790
- _PM_SYNTHESIS_USER_TEMPLATE.format(
4791
  ticker=ticker, current_price=current_price, months=12,
4792
  neutral_return=_nr_ret, neutral_rec=_nr_rec,
4793
  neutral_conf=_nr_conf, neutral_reasoning=_nr_rsn,
@@ -4834,13 +4901,19 @@ def analyze_llm_debate_yearly(
4834
  f"p_bear={p_bear:.0%} p_bull={p_bull:.0%} p_neutral={p_neutral:.0%} "
4835
  f"→ {GREEN if final_return > 0 else RED}{final_return*100:+.1f}%{RESET}")
4836
  elif _bear_ret is not None and _bull_ret is not None:
4837
- p_bear = p_bull = 0.40; p_neutral = 0.20
 
 
 
 
 
 
 
 
4838
  final_return = p_bear * _bear_ret + p_bull * _bull_ret
4839
- final_confidence = float(np.mean([
4840
- (bear_final or {}).get("confidence", 0.5),
4841
- (bull_final or {}).get("confidence", 0.5),
4842
- ]))
4843
- pm_reasoning = "PM synthesis unavailable — equal-weight average."
4844
  all_flags = _dedup_flags(
4845
  (bear_final or {}).get("risk_flags", []) + (bull_final or {}).get("risk_flags", [])
4846
  )
@@ -4886,6 +4959,14 @@ def analyze_llm_debate_yearly(
4886
 
4887
  final_predicted_price = current_price * (1 + final_return)
4888
 
 
 
 
 
 
 
 
 
4889
  # Display-compatible round dicts
4890
  _round1 = {}
4891
  if neutral_result:
 
4484
  return None
4485
 
4486
 
4487
+ # Yearly PM synthesis template — the yearly debate has NO blind Round-1 PM pass
4488
+ # (the monthly path's {pm_r1_*} baseline). It anchors on the Neutral analyst instead.
4489
+ # The shared monthly template requires {pm_r1_*}; formatting it with the yearly
4490
+ # kwargs raised KeyError, silently collapsing the PM to an equal-weight fallback.
4491
+ _PM_SYNTHESIS_USER_TEMPLATE_YEARLY = """STOCK: {ticker} | CURRENT: ${current_price:.2f} | HORIZON: {months}-month
4492
+
4493
+ NEUTRAL ANALYST (objective baseline — heard before the advocates):
4494
+ Return: {neutral_return:+.2f}% | Recommendation: {neutral_rec} | Confidence: {neutral_conf:.0f}%
4495
+ Reasoning: {neutral_reasoning}
4496
+
4497
+ RISK MANAGER (Bear) says:
4498
+ Return: {bear_return:+.2f}% → ${bear_price:.2f} | Recommendation: {bear_rec} | Confidence: {bear_conf:.0f}%
4499
+ Thesis: {bear_reasoning}
4500
+ Key Risks: {bear_risks}
4501
+
4502
+ GROWTH ANALYST (Bull) says:
4503
+ Return: {bull_return:+.2f}% → ${bull_price:.2f} | Recommendation: {bull_rec} | Confidence: {bull_conf:.0f}%
4504
+ Thesis: {bull_reasoning}
4505
+ Key Catalysts: {bull_catalysts}
4506
+
4507
+ Assign probability weights to each scenario. Weigh not just valuation/financials but also
4508
+ the institutional & insider positioning (13F super-investor and Form-4 flows) and any news
4509
+ catalysts each analyst cited — say which specific arguments moved your weights.
4510
+ Constraints: p_bear ∈ [0.10, 0.65], p_bull ∈ [0.10, 0.65], p_neutral = 1 - p_bear - p_bull ≥ 0.05
4511
+
4512
+ Respond with ONLY this JSON:
4513
+ {{
4514
+ "p_bear": <float>,
4515
+ "p_bull": <float>,
4516
+ "p_neutral": <float>,
4517
+ "conviction": <float: 0.0-1.0, confidence in these weights>,
4518
+ "reasoning": "<2-3 sentences: which specific arguments moved your probabilities and why>",
4519
+ "risk_flags": ["<combined key risks from both cases>"],
4520
+ "override_ml": <boolean>
4521
+ }}"""
4522
+
4523
+
4524
+ def _emit_role(role, phase, entry, *, ret_key="expected_return"):
4525
+ """Stream one analyst's FULL result (verdict + reasoning) to stdout the instant it
4526
+ resolves, as a machine-parseable sentinel line. The SSE wrapper turns this into a
4527
+ live bubble so the debate fills in progressively instead of only at the end."""
4528
+ if not entry:
4529
+ return
4530
+ try:
4531
+ import json as _json
4532
+ _ret = entry.get(ret_key)
4533
+ print("@@CRUCIBLE_ROLE@@" + _json.dumps({
4534
+ "role": role,
4535
+ "phase": phase,
4536
+ "return_pct": round(float(_ret) * 100, 1) if _ret is not None else None,
4537
+ "recommendation": entry.get("recommendation"),
4538
+ "confidence": entry.get("confidence"),
4539
+ "reasoning": entry.get("reasoning", ""),
4540
+ }), flush=True)
4541
+ except Exception:
4542
+ pass
4543
+
4544
+
4545
  def analyze_llm_debate_yearly(
4546
  ticker,
4547
  current_price,
 
4574
  _llm_cache_key = f"llm_debate_yearly_{ticker}_{_date_str}" + ("_gclass" if class_note else "")
4575
  _llm_cache_file = CACHE_DIR / f"{_llm_cache_key}.json"
4576
  _llm_meta_file = CACHE_DIR / f"{_llm_cache_key}.meta.json"
4577
+ # The debate IS the product — an on-demand run should show the panel argue LIVE,
4578
+ # not replay a 4h-old cached transcript. Default to a fresh debate; opt back into
4579
+ # caching with CRUCIBLE_DEBATE_CACHE=1 (the quant/data caches are untouched).
4580
+ _debate_cache_on = os.getenv("CRUCIBLE_DEBATE_CACHE", "0") == "1"
4581
+ if _debate_cache_on and not no_cache and _llm_cache_file.exists() and _llm_meta_file.exists():
4582
  try:
4583
  _meta = json.loads(_llm_meta_file.read_text())
4584
  _age = (datetime.now() - datetime.fromisoformat(_meta["cached_at"])).total_seconds()
 
4691
  print(f" {'Gemini (Neutral)':<20} {rc}{neutral_result['expected_return']*100:+.1f}%{RESET} "
4692
  f"{neutral_result.get('recommendation','HOLD'):<11} "
4693
  f"conf:{neutral_result['confidence']*100:.0f}%")
4694
+ _emit_role("neutral", "opening", neutral_result)
4695
  else:
4696
  print(f" {'Gemini (Neutral)':<20} {YELLOW}parse failed (check verbose){RESET}")
4697
  except Exception as e:
 
4737
  rc = GREEN if bear_r1["expected_return"] > 0 else RED
4738
  print(f" {'Kimi (Bear)':<20} {rc}{bear_r1['expected_return']*100:+.1f}%{RESET} "
4739
  f"{bear_r1.get('recommendation','HOLD'):<11} conf:{bear_r1['confidence']*100:.0f}%")
4740
+ _emit_role("bear", "opening case", bear_r1)
4741
  except Exception as e:
4742
  print(f" {'Kimi (Bear)':<20} {RED}{str(e)[:60]}{RESET}")
4743
 
 
4750
  rc = GREEN if bull_r1["expected_return"] > 0 else RED
4751
  print(f" {'GPT (Bull)':<20} {rc}{bull_r1['expected_return']*100:+.1f}%{RESET} "
4752
  f"{bull_r1.get('recommendation','HOLD'):<11} conf:{bull_r1['confidence']*100:.0f}%")
4753
+ _emit_role("bull", "opening case", bull_r1)
4754
  except Exception as e:
4755
  print(f" {'GPT (Bull)':<20} {RED}{str(e)[:60]}{RESET}")
4756
  _ex2.shutdown(wait=True)
 
4814
  tag = f"{YELLOW}REVISED{RESET}" if changed else f"{DIM}held{RESET}"
4815
  print(f" {'Kimi (Bear)':<20} {rc}{bear_rebuttal['expected_return']*100:+.1f}%{RESET} "
4816
  f"{bear_rebuttal.get('recommendation','HOLD'):<11} {tag}")
4817
+ _emit_role("bear", "rebuttal", bear_rebuttal)
4818
  except Exception as e:
4819
  print(f" {'Kimi (Bear)':<20} {RED}{str(e)[:60]}{RESET}")
4820
 
 
4830
  tag = f"{YELLOW}REVISED{RESET}" if changed else f"{DIM}held{RESET}"
4831
  print(f" {'GPT (Bull)':<20} {rc}{bull_rebuttal['expected_return']*100:+.1f}%{RESET} "
4832
  f"{bull_rebuttal.get('recommendation','HOLD'):<11} {tag}")
4833
+ _emit_role("bull", "rebuttal", bull_rebuttal)
4834
  except Exception as e:
4835
  print(f" {'GPT (Bull)':<20} {RED}{str(e)[:60]}{RESET}")
4836
  _ex3.shutdown(wait=True)
 
4854
  _bl_price = _bl.get("predicted_price") or current_price * (1 + _bl["expected_return"])
4855
  try:
4856
  pm_synthesis = _call_claude_synthesis(
4857
+ _PM_SYNTHESIS_USER_TEMPLATE_YEARLY.format(
4858
  ticker=ticker, current_price=current_price, months=12,
4859
  neutral_return=_nr_ret, neutral_rec=_nr_rec,
4860
  neutral_conf=_nr_conf, neutral_reasoning=_nr_rsn,
 
4901
  f"p_bear={p_bear:.0%} p_bull={p_bull:.0%} p_neutral={p_neutral:.0%} "
4902
  f"→ {GREEN if final_return > 0 else RED}{final_return*100:+.1f}%{RESET}")
4903
  elif _bear_ret is not None and _bull_ret is not None:
4904
+ # PM call failed — degrade gracefully: weight each side by its OWN stated
4905
+ # confidence (not a flat 40/40) and keep a neutral anchor, so the number
4906
+ # still reflects who argued more convincingly.
4907
+ _bc = float((bear_final or {}).get("confidence", 0.5))
4908
+ _lc = float((bull_final or {}).get("confidence", 0.5))
4909
+ _tot = (_bc + _lc + 0.5) or 1.0
4910
+ p_bear = float(np.clip(_bc / _tot, 0.10, 0.65))
4911
+ p_bull = float(np.clip(_lc / _tot, 0.10, 0.65))
4912
+ p_neutral = max(1.0 - p_bear - p_bull, 0.05)
4913
  final_return = p_bear * _bear_ret + p_bull * _bull_ret
4914
+ final_confidence = float(np.mean([_bc, _lc]))
4915
+ pm_reasoning = (f"PM synthesis unavailable — confidence-weighted blend "
4916
+ f"(bear {p_bear:.0%} @ {_bear_ret*100:+.1f}%, bull {p_bull:.0%} @ {_bull_ret*100:+.1f}%).")
 
 
4917
  all_flags = _dedup_flags(
4918
  (bear_final or {}).get("risk_flags", []) + (bull_final or {}).get("risk_flags", [])
4919
  )
 
4959
 
4960
  final_predicted_price = current_price * (1 + final_return)
4961
 
4962
+ # Stream the PM's capstone verdict live (last bubble to fill in the UI).
4963
+ _emit_role("pm", "synthesis", {
4964
+ "expected_return": final_return,
4965
+ "recommendation": final_rec,
4966
+ "confidence": final_confidence,
4967
+ "reasoning": pm_reasoning,
4968
+ })
4969
+
4970
  # Display-compatible round dicts
4971
  _round1 = {}
4972
  if neutral_result: