-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
4715 lines (4545 loc) · 205 KB
/
Copy pathapp.py
File metadata and controls
4715 lines (4545 loc) · 205 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import html
import json
import os
from pathlib import Path
import streamlit as st
from equity_research import config
from equity_research.analysis import format_number
from equity_research.budget import available_budget_modes, budget_allows_paid_data
from equity_research.consensus_import import import_consensus_csv, write_consensus_csv_templates
from equity_research.contributor_tools import build_contribution_pack, save_contribution_pack
from equity_research.external_evidence import (
default_macro_source_settings,
external_evidence_stack_from_config,
)
from equity_research.idea_engine import build_payoff_model, expected_value
from equity_research.local_secrets import (
LocalSecretsManager,
save_validated_keys,
validate_provider_keys,
)
from equity_research.llm_vault import (
build_llm_profile,
delete_llm_profile_with_secret,
get_llm_preset,
list_llm_presets,
profile_to_provider,
save_llm_profile_with_secret,
test_llm_profile,
)
from equity_research.memory import IdeaMemoryStore
from equity_research.network_diagnostics import run_network_diagnostics
from equity_research.pipeline import ResearchResult, run_us_equity_research
from equity_research.market_implied import build_market_implied_expectations
from equity_research.providers import StooqPriceClient, build_consensus_provider
from equity_research.research_store import ResearchStore
from equity_research.research_profiles import event_identifier, research_profiles
from equity_research.rigor import build_calibration_report
from equity_research.sample_data import demo_result
from equity_research.sec_client import SecClient, SecClientError
from equity_research.storytelling import demo_cases
from equity_research.thesis_synthesis import provider_from_config
from equity_research.thesis_synthesis import UnavailableLlmProvider
st.set_page_config(
page_title="IC Copilot",
page_icon="",
layout="wide",
initial_sidebar_state="collapsed",
)
GITHUB_REPOSITORY_URL = "https://github.com/mwsp-code/IC-Copilot"
LIVE_DEMO_URL = "https://ic-copilot.streamlit.app/"
FEEDBACK_DISCUSSION_URL = "https://github.com/mwsp-code/IC-Copilot/discussions/5"
def _demo_case_runtime_metadata(case) -> dict[str, object]:
"""Normalize demo metadata across Streamlit hot-reload schema versions."""
return {
"content_version": getattr(case, "content_version", "") or "",
"refreshed_at": getattr(case, "refreshed_at", "") or "",
"research_profile": getattr(case, "research_profile", "") or "",
"budget_mode": getattr(case, "budget_mode", "") or "",
"enabled_layers": tuple(getattr(case, "enabled_layers", ()) or ()),
}
def _inject_global_styles() -> None:
st.markdown(
"""
<style>
[data-testid="stAppViewContainer"],
[data-testid="stMain"] {
overflow-x: hidden;
}
[data-testid="stHorizontalBlock"] > [data-testid="column"] {
min-width: 0;
}
[data-testid="stMarkdownContainer"] p,
[data-testid="stAlertContent"],
[data-testid="stMetricValue"],
[data-testid="stMetricLabel"] {
overflow-wrap: anywhere;
word-break: normal;
}
.stTabs [data-baseweb="tab-list"] {
max-width: 100%;
overflow-x: auto;
scrollbar-width: thin;
}
@media (max-width: 700px) {
.block-container {
padding-left: 1rem;
padding-right: 1rem;
}
[data-testid="stHorizontalBlock"] {
flex-direction: column;
gap: 0.6rem;
}
[data-testid="stHorizontalBlock"] > [data-testid="column"] {
width: 100%;
flex: 1 1 auto;
}
[data-testid="stMetric"] {
min-height: auto;
}
}
</style>
""",
unsafe_allow_html=True,
)
def main() -> None:
_inject_global_styles()
title_col, repo_col = st.columns([4, 1])
with title_col:
st.title("IC Copilot")
st.caption(
"Evidence-first equity research: source event -> business driver -> "
"financial impact -> valuation -> IC decision."
)
with repo_col:
st.link_button("View on GitHub", GITHUB_REPOSITORY_URL, use_container_width=True)
st.link_button("Give Feedback", FEEDBACK_DISCUSSION_URL, use_container_width=True)
demo_video = Path(__file__).resolve().parent / "docs" / "assets" / "demo" / "ic-copilot-aapl-demo.mp4"
if demo_video.exists():
with st.expander("Watch the 91-second AAPL research walkthrough"):
st.video(str(demo_video))
st.caption(
"Source event -> causal bridge -> peer evidence -> reverse DCF -> "
"Bull/Bear/Judge. Frozen illustrative research; not investment advice."
)
if "result" not in st.session_state:
st.session_state.result = demo_result("AAPL")
st.session_state.demo_mode = "AAPL"
if "network_diagnostics" not in st.session_state:
st.session_state.network_diagnostics = None
pending_demo_preset = st.session_state.pop("_pending_demo_preset", None)
if pending_demo_preset:
st.session_state.research_profile_selector = pending_demo_preset.get(
"research_profile", "deep_initiation"
)
st.session_state.budget_mode_selector = pending_demo_preset.get("budget_mode", "Premium")
with st.sidebar:
st.header("Research Run")
secrets_manager = LocalSecretsManager()
local_secret_status = secrets_manager.redacted_status(getattr(config, "_SYSTEM_ENV_KEYS", set()))
configured_secret_count = sum(
1 for item in local_secret_status
if item["configured"] and item["key"] != "SEC_USER_AGENT"
)
local_secret_backend = local_secret_status[0]["backend"] if local_secret_status else "unavailable"
if configured_secret_count:
st.caption(f"{configured_secret_count} saved provider key(s) configured via {local_secret_backend}.")
elif not secrets_manager.backend_available:
st.warning("OS keychain is unavailable. Install keyring support or use .env.local manually.")
cases = demo_cases()
demo_labels = [f"{case.ticker} - {case.title}" for case in cases]
st.subheader("Load Demo Gallery")
selected_demo = st.selectbox("Demo case", demo_labels, index=0)
selected_case = cases[demo_labels.index(selected_demo)]
case_metadata = _demo_case_runtime_metadata(selected_case)
case_content_version = str(case_metadata["content_version"])
case_refreshed_at = str(case_metadata["refreshed_at"])
case_research_profile = str(case_metadata["research_profile"])
case_budget_mode = str(case_metadata["budget_mode"])
case_enabled_layers = tuple(case_metadata["enabled_layers"])
freshness = (
f" Version: {case_content_version}; refreshed {case_refreshed_at}."
if case_content_version or case_refreshed_at else ""
)
st.caption(f"{selected_case.lesson} {selected_case.badge}; {selected_case.expected_runtime}.{freshness}")
if case_research_profile or case_budget_mode:
st.caption(
f"Demo preset: {case_research_profile or 'Current research profile'} | "
f"{case_budget_mode or 'Current budget mode'}."
)
if case_enabled_layers:
st.caption("Included layers: " + ", ".join(case_enabled_layers) + ".")
load_demo_clicked = st.button("Load Selected Demo", use_container_width=True)
ticker = st.text_input("Ticker", value=selected_case.ticker or "AAPL").upper().strip()
profile_options = research_profiles()
profile_ids = [item.profile_id for item in profile_options if not item.event_scoped]
profile_by_id = {item.profile_id: item for item in profile_options}
default_profile = config.RESEARCH_PROFILE if config.RESEARCH_PROFILE in profile_ids else "adaptive_ic"
selected_profile_id = st.radio(
"Research depth",
profile_ids,
index=profile_ids.index(default_profile),
format_func=lambda value: profile_by_id[value].label,
help="Fast screens one anomaly; Adaptive is the default analyst workflow; Deep builds a fuller initiation pack.",
key="research_profile_selector",
)
selected_profile = profile_by_id[selected_profile_id]
st.caption(
f"{selected_profile.quarter_depth} quarters, {selected_profile.annual_depth} annual reports, "
f"{selected_profile.call_depth} calls."
)
investigate_clicked = False
investigate_event_id = None
prior_result = st.session_state.get("result")
if prior_result and getattr(prior_result, "events", None):
event_options = prior_result.events[:20]
event_labels = {
event_identifier(item): f"{item.event_date or 'Date unknown'} | {item.title}"
for item in event_options
}
investigate_event_id = st.selectbox(
"Investigate an event",
list(event_labels),
format_func=lambda value: event_labels[value],
)
investigate_clicked = st.button("Investigate This Event", use_container_width=True)
budget_modes = available_budget_modes()
budget_mode = st.selectbox(
"Budget mode",
list(budget_modes),
index=list(budget_modes).index(config.BUDGET_MODE) if config.BUDGET_MODE in budget_modes else 1,
help=(
"Free uses official/keyless and manual sources. Lean adds low-cost LLM synthesis. "
"Stable/Premium allow paid provider slots when keys are configured."
),
key="budget_mode_selector",
)
sec_user_agent = st.text_input(
"SEC user agent",
value=os.getenv("SEC_USER_AGENT", config.DEFAULT_SEC_USER_AGENT),
)
st.subheader("Consensus Connection")
configured_alpha_key = config.ALPHAVANTAGE_API_KEY or _streamlit_secret("ALPHAVANTAGE_API_KEY")
configured_finnhub_key = config.FINNHUB_API_KEY or _streamlit_secret("FINNHUB_API_KEY")
configured_fmp_key = config.FMP_API_KEY or _streamlit_secret("FMP_API_KEY")
configured_fred_key = config.FRED_API_KEY or _streamlit_secret("FRED_API_KEY")
configured_bls_key = config.BLS_API_KEY or _streamlit_secret("BLS_API_KEY")
configured_bea_key = config.BEA_API_KEY or _streamlit_secret("BEA_API_KEY")
configured_census_key = config.CENSUS_API_KEY or _streamlit_secret("CENSUS_API_KEY")
configured_wisburg_key = config.WISBURG_API_KEY or _streamlit_secret("WISBURG_API_KEY")
configured_tiingo_key = config.TIINGO_API_KEY or _streamlit_secret("TIINGO_API_KEY")
configured_eodhd_key = config.EODHD_API_KEY or _streamlit_secret("EODHD_API_KEY")
llm_store = ResearchStore()
alpha_session_key = st.text_input(
"Alpha Vantage API key",
type="password",
key="alpha_session_key",
help="Used only in this Streamlit session. It is never written to SQLite or logs.",
placeholder="Already configured" if configured_alpha_key else "Free key",
).strip()
finnhub_session_key = st.text_input(
"Finnhub API key",
type="password",
key="finnhub_session_key",
help="Used only in this Streamlit session. It is never written to SQLite or logs.",
placeholder="Already configured" if configured_finnhub_key else "Free key",
).strip()
with st.expander("Saved key status"):
st.dataframe(
[
{
"Provider": item["label"],
"Configured": "Yes" if item["configured"] else "No",
"Source": item["source"],
}
for item in local_secret_status
],
hide_index=True,
use_container_width=True,
)
with st.expander("Additional sources"):
fmp_session_key = st.text_input(
"FMP API key",
type="password",
key="fmp_session_key",
help="Optional legacy provider. Used only in this Streamlit session.",
placeholder="Already configured" if configured_fmp_key else "Optional",
).strip()
tiingo_session_key = st.text_input(
"Tiingo API key",
type="password",
key="tiingo_session_key",
help="Session-only unless saved. Used for adjusted EOD prices, event windows, beta, and peer-return attribution.",
placeholder="Already configured" if configured_tiingo_key else "Optional market data key",
).strip()
eodhd_session_key = st.text_input(
"EODHD API key",
type="password",
key="eodhd_session_key",
help=(
"Session-only unless saved. The free plan supplies recent adjusted EOD prices for "
"event windows, peer reactions, market context, and reverse-implied expectations."
),
placeholder="Already configured" if configured_eodhd_key else "Optional EOD price key",
).strip()
enable_nasdaq = st.toggle(
"Nasdaq estimates (unofficial)",
value=config.ENABLE_NASDAQ_CONSENSUS,
)
enable_tradingview = st.toggle(
"TradingView targets (unofficial)",
value=config.ENABLE_TRADINGVIEW_CONSENSUS,
)
st.markdown("**Macro / external evidence**")
fred_session_key = st.text_input(
"FRED API key",
type="password",
key="fred_session_key",
help="Session-only. Enables FRED/ALFRED macro context when the toggle is on.",
placeholder="Already configured" if configured_fred_key else "Free key",
).strip()
bls_session_key = st.text_input(
"BLS API key",
type="password",
key="bls_session_key",
help="Optional session-only BLS key. BLS may allow limited no-key calls.",
placeholder="Already configured" if configured_bls_key else "Optional",
).strip()
bea_session_key = st.text_input(
"BEA API key",
type="password",
key="bea_session_key",
help="Session-only. BEA macro calls require a BEA key.",
placeholder="Already configured" if configured_bea_key else "Free key",
).strip()
census_session_key = st.text_input(
"Census API key",
type="password",
key="census_session_key",
help="Session-only. Census macro calls require a Census key.",
placeholder="Already configured" if configured_census_key else "Free key",
).strip()
global_macro_mode = st.toggle("Global macro mode", value=config.GLOBAL_MACRO_MODE)
enable_default_macro = st.toggle("Default official macro sources", value=config.ENABLE_DEFAULT_MACRO)
effective_fred_key_preview = fred_session_key or configured_fred_key
effective_bea_key_preview = bea_session_key or configured_bea_key
effective_census_key_preview = census_session_key or configured_census_key
macro_defaults = default_macro_source_settings(
ticker,
fred_api_key=effective_fred_key_preview,
bea_api_key=effective_bea_key_preview,
census_api_key=effective_census_key_preview,
enable_default_macro=enable_default_macro,
global_macro_mode=global_macro_mode,
)
enable_fred = st.toggle("FRED / ALFRED macro", value=macro_defaults["fred"])
enable_bls = st.toggle("BLS macro", value=macro_defaults["bls"])
enable_bea = st.toggle("BEA macro", value=macro_defaults["bea"])
enable_census = st.toggle("Census macro", value=macro_defaults["census"])
enable_treasury = st.toggle("Treasury / Fiscal Data macro", value=macro_defaults["treasury"])
enable_ofr = st.toggle("OFR financial stress", value=macro_defaults["ofr"])
enable_world_bank = st.toggle("World Bank macro", value=macro_defaults["world_bank"])
enable_imf = st.toggle("IMF macro", value=macro_defaults["imf"])
enable_gdelt = st.toggle("GDELT narrative saturation", value=config.ENABLE_GDELT)
refresh_macro_cache = st.toggle("Refresh macro cache", value=False)
wisburg_session_key = st.text_input(
"Wisburg API key",
type="password",
key="wisburg_session_key",
help="Session-only unless saved to the OS keychain. Used for external analyst/narrative context only.",
placeholder="Already configured" if configured_wisburg_key else "Optional",
).strip()
enable_wisburg = st.toggle("Wisburg research", value=config.ENABLE_WISBURG)
st.markdown("**IC Copilot / LLM synthesis**")
enable_llm = st.toggle(
"LLM thesis synthesis",
value=config.ENABLE_LLM_THESIS or budget_mode in {"Lean", "Stable", "Premium"},
help="Optional. Sends only curated excerpts and structured claims to the selected provider.",
)
presets = {preset.preset_id: preset for preset in list_llm_presets()}
profiles = llm_store.list_llm_profiles()
selection = llm_store.get_llm_selection()
profile_labels = {"": "None"}
profile_labels.update({
profile.profile_id: (
f"{profile.display_name} ({profile.provider_preset}, {profile.model})"
+ (" - key saved" if profile.key_configured else " - no key")
)
for profile in profiles
})
profile_ids = list(profile_labels)
primary_default = selection.get("primary_profile_id") or config.LLM_PRIMARY_PROFILE_ID
secondary_default = selection.get("secondary_profile_id") or config.LLM_SECONDARY_PROFILE_ID
if not primary_default:
first_configured = next((profile.profile_id for profile in profiles if profile.key_configured), "")
primary_default = first_configured or (profiles[0].profile_id if profiles else "")
primary_profile_id = st.selectbox(
"Primary LLM",
profile_ids,
index=profile_ids.index(primary_default) if primary_default in profile_ids else 0,
format_func=lambda value: profile_labels[value],
)
secondary_profile_id = st.selectbox(
"Secondary reader",
profile_ids,
index=profile_ids.index(secondary_default) if secondary_default in profile_ids else 0,
format_func=lambda value: profile_labels[value],
)
enable_secondary_review = st.toggle(
"Secondary review for Research-Ready+",
value=bool(selection.get("enable_secondary", config.ENABLE_SECONDARY_LLM_REVIEW)),
)
secondary_min_stage = st.selectbox(
"Secondary minimum stage",
["Research-Ready", "High-Conviction"],
index=0 if selection.get("secondary_min_stage", config.SECONDARY_LLM_MIN_STAGE) != "High-Conviction" else 1,
)
language_policy = st.selectbox(
"Language policy",
["bilingual_audit", "english_only"],
index=0 if selection.get("language_policy", config.LLM_LANGUAGE_POLICY) != "english_only" else 1,
)
if st.button("Save LLM Selection", use_container_width=True):
llm_store.save_llm_selection(
primary_profile_id,
secondary_profile_id,
enable_secondary_review,
secondary_min_stage,
language_policy,
)
st.success("Saved LLM primary/secondary selection.")
with st.expander("Provider Vault"):
saved_rows = [
{
"Name": profile.display_name,
"Preset": profile.provider_preset,
"Model": profile.model,
"Base URL": profile.base_url or "n/a",
"Key": "Configured" if profile.key_configured else "Missing",
"Last test": profile.last_test_status,
}
for profile in profiles
]
if saved_rows:
st.dataframe(saved_rows, hide_index=True, use_container_width=True)
preset_id = st.selectbox(
"Provider preset",
list(presets),
index=list(presets).index("deepseek") if "deepseek" in presets else 0,
format_func=lambda value: presets[value].label,
)
preset = get_llm_preset(preset_id)
profile_name = st.text_input("Profile name", value=f"{preset.label} primary").strip()
profile_model = st.text_input("Model", value=preset.default_model).strip()
profile_base_url = st.text_input(
"Base URL",
value=preset.default_base_url,
placeholder="Required for custom, Qwen, and Kimi OpenAI-compatible endpoints",
).strip()
profile_api_key = st.text_input(
"API key",
type="password",
key="llm_profile_api_key",
placeholder="Saved to OS keychain only",
).strip()
profile_action_cols = st.columns(2)
if profile_action_cols[0].button("Save Provider Profile", use_container_width=True):
try:
saved_profile = save_llm_profile_with_secret(
llm_store,
secrets_manager,
display_name=profile_name,
provider_preset=preset_id,
model=profile_model,
base_url=profile_base_url,
api_key=profile_api_key,
)
st.success(f"Saved {saved_profile.display_name}.")
except Exception as exc:
st.error(f"Could not save LLM profile: {exc}")
if profile_action_cols[1].button("Test Unsaved Profile", use_container_width=True):
try:
candidate = build_llm_profile(
display_name=profile_name,
provider_preset=preset_id,
model=profile_model,
base_url=profile_base_url,
key_configured=bool(profile_api_key),
)
status = test_llm_profile(candidate, manager=secrets_manager, api_key=profile_api_key)
st.info(f"{status.status}: {status.message}")
except Exception as exc:
st.error(f"Could not test LLM profile: {exc}")
if profiles:
delete_id = st.selectbox(
"Delete saved profile",
[profile.profile_id for profile in profiles],
format_func=lambda value: profile_labels.get(value, value),
)
if st.button("Delete Selected LLM Profile", use_container_width=True):
delete_llm_profile_with_secret(llm_store, secrets_manager, delete_id)
st.warning("Deleted selected LLM profile and its keychain secret.")
entered_keys = {
"ALPHAVANTAGE_API_KEY": alpha_session_key,
"FINNHUB_API_KEY": finnhub_session_key,
"FMP_API_KEY": fmp_session_key,
"FRED_API_KEY": fred_session_key,
"BEA_API_KEY": bea_session_key,
"CENSUS_API_KEY": census_session_key,
"WISBURG_API_KEY": wisburg_session_key,
"TIINGO_API_KEY": tiingo_session_key,
"EODHD_API_KEY": eodhd_session_key,
"SEC_USER_AGENT": sec_user_agent,
}
key_cols = st.columns(3)
if key_cols[0].button("Test Keys", use_container_width=True):
with st.spinner("Testing provider keys..."):
st.session_state.key_validation_results = validate_provider_keys(entered_keys)
if key_cols[1].button("Save Valid Keys", use_container_width=True):
with st.spinner("Testing and saving valid keys..."):
results = validate_provider_keys(entered_keys)
st.session_state.key_validation_results = results
try:
outcome = save_validated_keys(secrets_manager, entered_keys, results)
config.refresh_runtime_secrets()
st.success(
f"Saved {len(outcome['saved'])} key(s). "
"Restart the app if a running workflow already captured old settings."
)
except Exception as exc:
st.error(f"Could not save keys to OS keychain: {exc}")
if key_cols[2].button("Clear Saved Keys", use_container_width=True):
secrets_manager.delete_many()
config.refresh_runtime_secrets()
st.warning("Cleared saved local keys from the OS keychain.")
if st.session_state.get("key_validation_results"):
st.dataframe(
[
{"Provider": item.label, "Status": item.status, "Message": item.message}
for item in st.session_state.key_validation_results
],
hide_index=True,
use_container_width=True,
)
effective_alpha_key = alpha_session_key or configured_alpha_key
effective_finnhub_key = finnhub_session_key or configured_finnhub_key
effective_fmp_key = (fmp_session_key or configured_fmp_key) if budget_allows_paid_data(budget_mode) else ""
effective_fred_key = fred_session_key or configured_fred_key
effective_bls_key = bls_session_key or configured_bls_key
effective_bea_key = bea_session_key or configured_bea_key
effective_census_key = census_session_key or configured_census_key
effective_wisburg_key = wisburg_session_key or configured_wisburg_key
effective_tiingo_key = tiingo_session_key or configured_tiingo_key
effective_eodhd_key = eodhd_session_key or configured_eodhd_key
primary_profile = llm_store.get_llm_profile(primary_profile_id)
secondary_profile = llm_store.get_llm_profile(secondary_profile_id)
llm_provider = profile_to_provider(primary_profile, secrets_manager, enabled=enable_llm)
if enable_llm and primary_profile_id and llm_provider is None:
llm_provider = UnavailableLlmProvider(
primary_profile.provider_preset if primary_profile else "selected_profile",
primary_profile.model if primary_profile else "unknown",
"Selected primary LLM profile is unavailable. Check that its API key and base URL are saved.",
)
elif llm_provider is None:
llm_provider = provider_from_config(enabled=enable_llm)
secondary_llm_provider = profile_to_provider(
secondary_profile,
secrets_manager,
enabled=enable_llm and enable_secondary_review,
)
external_provider = external_evidence_stack_from_config(
fred_api_key=effective_fred_key,
enable_fred=enable_fred,
bls_api_key=effective_bls_key,
enable_bls=enable_bls,
bea_api_key=effective_bea_key,
enable_bea=enable_bea,
census_api_key=effective_census_key,
enable_census=enable_census,
enable_treasury=enable_treasury,
enable_ofr=enable_ofr,
enable_world_bank=enable_world_bank,
enable_imf=enable_imf,
enable_gdelt=enable_gdelt,
wisburg_api_key=effective_wisburg_key,
enable_wisburg=enable_wisburg,
enable_default_macro=enable_default_macro,
global_macro_mode=global_macro_mode,
refresh_cache=refresh_macro_cache,
)
configured_sources = sum(bool(value) for value in (
effective_alpha_key, effective_finnhub_key, effective_fmp_key,
enable_nasdaq, enable_tradingview,
))
configured_market_sources = sum(bool(value) for value in (
effective_tiingo_key,
effective_eodhd_key,
))
configured_external_sources = sum(bool(value) for value in (
enable_fred, enable_bls, enable_bea, enable_census, enable_treasury,
enable_ofr, enable_world_bank, enable_imf, enable_gdelt, enable_wisburg,
))
if configured_sources:
st.success(f"{configured_sources} consensus source(s) enabled.")
else:
st.warning("No consensus source is enabled. SEC research will still run.")
if (fmp_session_key or configured_fmp_key) and not budget_allows_paid_data(budget_mode):
st.info(
"FMP is saved/configured but disabled in this budget mode. "
"Choose Stable or Premium to use FMP targets, estimates, surprises, and point-in-time snapshots."
)
if configured_market_sources:
st.success(f"{configured_market_sources} paid market data source(s) enabled for price attribution.")
run_network_check = st.button("Run Network Diagnostics", use_container_width=True)
test_connection = st.button("Test Consensus Sources", use_container_width=True)
run_clicked = st.button("Run Live Research", type="primary", use_container_width=True)
st.caption("US equities MVP. HK support can plug into the same pipeline later.")
if load_demo_clicked:
st.session_state.result = demo_result(selected_case.ticker)
st.session_state.demo_mode = selected_case.ticker
st.session_state._pending_demo_preset = {
"research_profile": "deep_initiation" if case_budget_mode == "Premium" else default_profile,
"budget_mode": case_budget_mode or budget_mode,
}
st.rerun()
if run_network_check:
with st.spinner("Running network diagnostics from the Streamlit process..."):
st.session_state.network_diagnostics = run_network_diagnostics(timeout_seconds=8)
if st.session_state.network_diagnostics:
report = st.session_state.network_diagnostics
with st.sidebar.expander("Network Diagnostics", expanded=True):
st.caption(f"Class: {report.network_class}")
st.caption(report.summary)
if report.runtime_context:
st.caption(f"Python: {report.runtime_context.get('python_executable', 'Unknown')}")
st.caption(f"PID: {report.runtime_context.get('pid', 'Unknown')}")
for action in report.suggested_actions[:4]:
st.write(f"- {action}")
rows = [
{
"Provider": probe.provider,
"Check": probe.check_type,
"Host": probe.endpoint_host,
"Status": probe.status,
"Class": probe.failure_class,
"Fix": probe.suggested_fix,
}
for probe in report.probes
]
st.dataframe(rows, hide_index=True, use_container_width=True)
if test_connection:
if not configured_sources:
st.sidebar.error("Enter a free provider key or enable an unofficial fallback.")
elif not ticker:
st.sidebar.error("Enter a ticker first.")
else:
with st.spinner(f"Testing consensus sources for {ticker}..."):
package = build_consensus_provider(
alpha_vantage_key=effective_alpha_key,
finnhub_key=effective_finnhub_key,
fmp_key=effective_fmp_key,
enable_nasdaq=enable_nasdaq,
enable_tradingview=enable_tradingview,
enable_yahoo=False,
).fetch_package(ticker)
if package.status == "Unavailable":
st.sidebar.error("No enabled source returned usable consensus data.")
elif package.status.startswith("Partial"):
st.sidebar.warning(package.status)
else:
st.sidebar.success("Official consensus data is available.")
for status in package.provider_statuses:
st.sidebar.caption(f"{status.provider}: {status.status}")
for gap in package.data_gaps:
st.sidebar.caption(gap)
if (run_clicked or investigate_clicked) and ticker:
st.session_state.demo_mode = None
effective_profile = "investigate_event" if investigate_clicked else selected_profile_id
try:
with st.spinner(f"Running research workflow for {ticker}..."):
store = ResearchStore()
if configured_sources:
provider = build_consensus_provider(
store=store,
alpha_vantage_key=effective_alpha_key,
finnhub_key=effective_finnhub_key,
fmp_key=effective_fmp_key,
enable_nasdaq=enable_nasdaq,
enable_tradingview=enable_tradingview,
enable_yahoo=False,
)
st.session_state.result = run_us_equity_research(
ticker,
sec_client=SecClient(user_agent=sec_user_agent),
price_client=StooqPriceClient(
store=store,
tiingo_key=effective_tiingo_key,
eodhd_key=effective_eodhd_key,
),
consensus=provider,
external_evidence_provider=external_provider,
llm_provider=llm_provider,
secondary_llm_provider=secondary_llm_provider,
enable_secondary_llm_review=enable_secondary_review,
secondary_llm_min_stage=secondary_min_stage,
llm_language_policy=language_policy,
budget_mode=budget_mode,
store=store,
research_profile=effective_profile,
investigate_event_id=investigate_event_id if investigate_clicked else None,
)
else:
st.session_state.result = run_us_equity_research(
ticker,
sec_client=SecClient(user_agent=sec_user_agent),
price_client=StooqPriceClient(
store=store,
tiingo_key=effective_tiingo_key,
eodhd_key=effective_eodhd_key,
),
external_evidence_provider=external_provider,
llm_provider=llm_provider,
secondary_llm_provider=secondary_llm_provider,
enable_secondary_llm_review=enable_secondary_review,
secondary_llm_min_stage=secondary_min_stage,
llm_language_policy=language_policy,
budget_mode=budget_mode,
store=store,
research_profile=effective_profile,
investigate_event_id=investigate_event_id if investigate_clicked else None,
)
except SecClientError as exc:
retained = st.session_state.get("result")
retained_label = (
f" The previously loaded {retained.identity.ticker} result remains visible below."
if retained is not None else ""
)
st.error(
f"Live SEC research could not complete: {exc}{retained_label} "
"This is a source-access failure, not a finding about the company."
)
except Exception as exc: # pragma: no cover - UI guardrail
st.exception(exc)
st.stop()
result: ResearchResult | None = st.session_state.result
if result is None:
st.info("Enter a US ticker and run the workflow.")
return
demo_mode = st.session_state.get("demo_mode")
if demo_mode:
st.info(
f"Viewing the frozen {demo_mode} Deep Initiation demo. "
"Choose Run Live Research to refresh sources with your configured providers."
)
render_header(result)
tabs = st.tabs(
[
"IC Story",
"Evidence Trail",
"Causal Bridge",
"Market & Expectations",
"Work Orders",
"Raw Data",
]
)
with tabs[0]:
render_ic_copilot(result)
with tabs[1]:
render_research_radar(result)
render_management_sources(result)
render_validated_claims_and_source_plan(result)
with tabs[2]:
render_research_modes(result)
render_causal_thesis_graphs(result)
render_company_model_workspace(result)
render_idea_factory(result)
render_idea_scorer(result)
with tabs[3]:
render_earnings_surprise_proxy(result)
render_market_implied_expectations(result)
render_recent_market_context(result)
render_price_move_attribution(result)
render_market_capture_readiness(result)
with tabs[4]:
render_evidence_work_order(result)
render_research_questions(result)
render_thesis_monitor(result)
with tabs[5]:
render_memo(result)
def _streamlit_secret(name: str) -> str:
try:
return str(st.secrets.get(name, "")).strip()
except Exception:
return ""
def render_header(result: ResearchResult) -> None:
identity = result.identity
top_score = result.ideas[0].score.total if result.ideas and result.ideas[0].score else 0
capture = (
result.ideas[0].market_capture.category
if result.ideas and result.ideas[0].market_capture
else "Unknown"
)
_wrapped_metric_grid([
("Company", identity.name.title()),
("CIK", identity.cik),
("Top Idea Score", f"{top_score}/100" if top_score else "n/a"),
("Market Capture", capture),
])
def render_story_first(result: ResearchResult) -> None:
demo_case = getattr(result, "demo_case", None)
if demo_case:
st.info(
f"Demo gallery: **{demo_case.title}**. {demo_case.lesson} "
f"Runtime: {demo_case.expected_runtime}; network required: {'yes' if demo_case.network_required else 'no'}; "
f"version: {demo_case.content_version or 'Unversioned'}; refreshed: {demo_case.refreshed_at or 'Unknown'}."
)
one_pager = getattr(result, "ic_one_pager", None)
brief = result.thesis_brief
st.markdown("### IC Story")
_wrapped_metric_grid([
("Verdict", one_pager.verdict if one_pager else brief.verdict),
("Stage", one_pager.stage if one_pager else brief.stage),
("Direction", one_pager.direction if one_pager else brief.direction),
("Decision", one_pager.decision if one_pager and one_pager.decision else "Research next"),
("Rank", one_pager.rank_eligibility if one_pager else "n/a"),
])
if one_pager:
st.write(one_pager.thesis)
if one_pager.next_best_action:
st.success(f"Next action: {one_pager.next_best_action}")
profile = getattr(result, "research_profile", None)
history = getattr(result, "historical_research", None)
if profile and history:
_wrapped_metric_grid([
("Research Profile", profile.label),
("Quarter History", f"{history.analyzed_quarters}/{history.requested_quarters}"),
("Annual History", f"{history.analyzed_annual_reports}/{history.requested_annual_reports}"),
("Call History", f"{history.analyzed_calls}/{history.requested_calls}"),
])
if history.adaptive_deepening_reasons:
st.caption("Adaptive deepening: " + ", ".join(history.adaptive_deepening_reasons) + ".")
st.caption(
f"Discovered before parsing: {history.discovered_quarters} quarterly filings, "
f"{history.discovered_annual_reports} annual reports, and {history.discovered_calls} calls."
)
render_pipeline_progress(result)
render_story_cards(result)
render_bull_bear_judge(result)
with st.expander("Formula transparency", expanded=False):
render_formula_traces(result)
render_contributor_surface(result)
def _wrapped_metric_grid(items: list[tuple[str, object]]) -> None:
cards = []
for label, value in items:
safe_label = html.escape(str(label))
safe_value = html.escape(str(value or "Unknown"))
cards.append(
'<div style="min-height:92px;border:1px solid rgba(128,128,128,0.32);border-radius:8px;'
'padding:0.85rem;overflow-wrap:anywhere;word-break:normal;">'
f'<div style="font-size:0.78rem;color:#9aa0aa;margin-bottom:0.4rem;">{safe_label}</div>'
f'<div style="font-size:1.12rem;line-height:1.3;font-weight:650;letter-spacing:0;">{safe_value}</div>'
'</div>'
)
st.markdown(
'<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:0.75rem;'
'width:100%;margin-bottom:0.75rem;">' + "".join(cards) + '</div>',
unsafe_allow_html=True,
)
def render_pipeline_progress(result: ResearchResult) -> None:
progress = getattr(result, "run_progress", None)
if not progress or not progress.stages:
return
st.markdown("#### Research Pipeline")
st.caption(progress.summary)
status_icon = {
"Passed": "[OK]",
"Partial": "[..]",
"Blocked": "[!]",
"Skipped": "[-]",
"Unavailable": "[?]",
}
cols = st.columns(len(progress.stages))
for col, stage in zip(cols, progress.stages):
col.markdown(f"**{status_icon.get(stage.status, '[?]')} {stage.label}**")
col.caption(stage.status)
with st.expander("Pipeline details", expanded=False):
st.dataframe(
[
{
"Stage": stage.label,
"Status": stage.status,
"Summary": stage.summary,
"Evidence": "; ".join(stage.evidence),
"Blockers": "; ".join(stage.blockers),
"Next action": stage.next_action,
}
for stage in progress.stages
],
use_container_width=True,
hide_index=True,
)
def render_story_cards(result: ResearchResult) -> None:
cards = getattr(result, "story_cards", [])
if not cards:
return
st.markdown("#### Story Cards")
for idx in range(0, len(cards), 2):
cols = st.columns(2)
for card, col in zip(cards[idx:idx + 2], cols):
with col.container(border=True):
st.markdown(f"**{card.title}**")
st.caption(card.status)
st.write(card.body or card.summary)
if card.next_action:
st.caption(f"Next: {card.next_action}")
if card.evidence:
with st.expander("Show evidence", expanded=False):
render_evidence_drawers(card.evidence)
def render_evidence_drawers(drawers) -> None:
for drawer in drawers:
st.markdown(f"**{drawer.label}**")
st.write(drawer.claim)
meta = [
f"Source: {drawer.source or 'Unknown'}",
f"Tier: {drawer.source_tier if drawer.source_tier is not None else 'Unknown'}",
f"Section: {drawer.section or 'Unknown'}",
f"Period: {drawer.period or 'Unknown'}",
f"Metric: {drawer.metric or 'n/a'}",
f"Value: {drawer.value or 'n/a'}",
f"Formula: {drawer.formula or 'n/a'}",
f"Parser: {drawer.parser_status or 'Unknown'}",
f"Confidence: {drawer.confidence or 'Unknown'}",
]
st.caption(" | ".join(meta))
if drawer.url:
st.caption(drawer.url)
if drawer.excerpt:
st.code(drawer.excerpt[:700])
def render_bull_bear_judge(result: ResearchResult) -> None:
panel = getattr(result, "bull_bear_judge", None)
if not panel:
return
st.markdown("#### Bull / Bear / Judge")
cols = st.columns(3)
with cols[0].container(border=True):
st.markdown("**Bull case**")
st.write(panel.bull_case)
with cols[1].container(border=True):
st.markdown("**Bear case**")
st.write(panel.bear_case)
with cols[2].container(border=True):
st.markdown("**Judge accepts**")
for item in panel.judge_accepts[:5]:
st.write(f"- {item}")
if panel.still_unproven:
st.markdown("**Still unproven**")
for item in panel.still_unproven[:5]:
st.write(f"- {item}")
if panel.resolution_plan:
st.markdown("**How the app will try to resolve open items**")
st.dataframe(
[
{
"Type": item.issue_type,
"Status": item.status,
"What it means": item.issue,
"Triggering evidence": item.evidence,
"App action": item.app_action,
"User action": item.user_action,
"Blocks": item.blocking_scope,
"Automatic": "Yes" if item.auto_resolvable else "No",
}
for item in panel.resolution_plan
],
use_container_width=True,
hide_index=True,
)
def render_formula_traces(result: ResearchResult) -> None:
traces = getattr(result, "formula_traces", [])
if not traces:
st.info("No formula traces are attached to this run.")