-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
260 lines (207 loc) · 9.05 KB
/
app.py
File metadata and controls
260 lines (207 loc) · 9.05 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
"""
Streamlit Chat Interface — the primary demo surface.
The challenge spec calls for an "Autonomous Financial Advisor Chat Agent"
that answers any finance/portfolio question. This file provides that UI:
- Sidebar: portfolio dropdown + compact context (P&L, confidence, drivers)
+ collapsible "Full analysis" expander for audit.
- Main: chat window (history + input). Every user message is answered
using the Briefing as ground truth via src.chat.chat().
The heavy-lift reasoning (Phases 1-4) runs ONCE when a portfolio is
selected. Its output (a `Briefing`) is cached in session state and
reused as context for every chat turn — so follow-up questions are fast
and consistent.
Run:
streamlit run app.py
"""
from __future__ import annotations
import os
from pathlib import Path
# Load env before importing anything that reads env vars
from dotenv import load_dotenv
load_dotenv()
import streamlit as st
from main import analyse_portfolio
from src.chat import chat
from src.data_loader import DataLoader
from src.models import Briefing
from src.phase4_observability import trace_run
DATA_DIR = Path(__file__).parent / "data" / "json"
# -----------------------------------------------------------------------------
# Data loading (cached)
# -----------------------------------------------------------------------------
@st.cache_resource
def get_loader() -> DataLoader:
return DataLoader(DATA_DIR)
@st.cache_data(show_spinner=False)
def list_portfolios() -> dict[str, str]:
loader = get_loader()
return {
pid: f"{pid} — {p.user_name} ({p.portfolio_type})"
for pid, p in loader.load_all_portfolios().items()
}
# -----------------------------------------------------------------------------
# Page setup
# -----------------------------------------------------------------------------
st.set_page_config(
page_title="Financial Advisor Chat",
layout="wide",
initial_sidebar_state="expanded",
)
# -----------------------------------------------------------------------------
# Sidebar — portfolio picker + compact status + runtime info
# -----------------------------------------------------------------------------
st.sidebar.title("Financial Advisor")
st.sidebar.caption("Causal reasoning over Indian equity portfolios.")
portfolios = list_portfolios()
selected = st.sidebar.selectbox(
"Portfolio",
options=list(portfolios.keys()),
format_func=lambda pid: portfolios[pid],
index=1, # default to PORTFOLIO_002 (banking-heavy = richest demo)
)
# -----------------------------------------------------------------------------
# Run analysis when portfolio changes (session-scoped — re-runs only on change)
# -----------------------------------------------------------------------------
if st.session_state.get("current_portfolio") != selected:
with st.spinner(f"Analysing {selected}..."):
st.session_state.briefing = analyse_portfolio(get_loader(), selected)
st.session_state.current_portfolio = selected
b = st.session_state.briefing
opening = (
f"I've analysed **{b.portfolio.user_name}**'s portfolio "
f"for {b.market.context.date}.\n\n"
f"**Day P&L:** {b.analytics.total_pnl_percent:+.2f}% "
f"({b.analytics.total_pnl_inr:+,.0f} INR) \n"
f"**Primary driver:** {b.causal.primary_driver} \n"
f"**Confidence:** {b.confidence.overall:.2f}\n\n"
"Ask me anything — I have the full causal analysis in memory. For example:\n\n"
"- *Why did my portfolio move today?*\n"
"- *Show me any conflicts in today's signals*\n"
"- *What if I hadn't held banking?*\n"
"- *How risky is my portfolio?*\n"
"- *Tell me about HDFCBANK* (or any holding)\n"
"- *What is CAPM?* _(general finance — needs Gemini key)_"
)
st.session_state.messages = [{"role": "assistant", "content": opening}]
briefing: Briefing = st.session_state.briefing
# -----------------------------------------------------------------------------
# Sidebar — compact status
# -----------------------------------------------------------------------------
st.sidebar.divider()
pnl_col_a, pnl_col_b = st.sidebar.columns(2)
pnl_col_a.metric(
"Day P&L",
f"{briefing.analytics.total_pnl_percent:+.2f}%",
delta=f"{briefing.analytics.total_pnl_inr:+,.0f} INR",
)
pnl_col_b.metric("Confidence", f"{briefing.confidence.overall:.2f}")
st.sidebar.markdown(f"**Primary driver:** {briefing.causal.primary_driver}")
if briefing.market.active_macro_themes:
themes = briefing.market.active_macro_themes
shown = ", ".join(themes[:3])
if len(themes) > 3:
shown += f" _(+{len(themes)-3} more)_"
st.sidebar.caption(f"**Themes:** {shown}")
if briefing.analytics.concentration_risks:
st.sidebar.warning(
briefing.analytics.concentration_risks[0],
icon=":material/warning:",
)
# -----------------------------------------------------------------------------
# Sidebar — full analysis (collapsed by default)
# -----------------------------------------------------------------------------
with st.sidebar.expander("Full analysis", expanded=False):
st.markdown("**Causal chain** _(themes touching your portfolio)_")
impacts_by_sector: dict[str, list] = {}
for i in briefing.causal.stock_impacts:
impacts_by_sector.setdefault(i.sector, []).append(i)
for theme, sectors in briefing.causal.macro_to_sector.items():
hit = [s for s in sectors if s in impacts_by_sector]
if not hit:
continue
st.markdown(f"- **{theme}** → {', '.join(hit[:4])}")
if briefing.causal.stock_impacts:
st.markdown("**Top drivers**")
for i in briefing.causal.stock_impacts[:3]:
st.caption(
f"{i.ticker} · {i.day_change_pct:+.2f}% · "
f"contrib {i.pnl_contribution_pct:+.2f}pp · β={i.beta}"
)
if briefing.causal.counterfactuals:
st.markdown("**Counterfactuals**")
for cf in briefing.causal.counterfactuals:
st.caption(
f"{cf.scenario}: {cf.hypothetical_pnl_pct:+.2f}% "
f"(delta {cf.delta_pct:+.2f}pp)"
)
st.markdown("**Self-evaluation**")
c = briefing.confidence
st.caption(
f"data {c.data_completeness:.2f} · news {c.news_coverage:.2f} · "
f"signal {c.signal_strength:.2f} · conflict {c.conflict_penalty:.2f} · "
f"reasoning {c.reasoning_quality:.2f}"
)
# -----------------------------------------------------------------------------
# Sidebar — runtime indicators
# -----------------------------------------------------------------------------
st.sidebar.divider()
llm_on = os.getenv("USE_LLM", "true").lower() == "true" and bool(
os.getenv("GROQ_API_KEY")
)
langfuse_on = bool(os.getenv("LANGFUSE_PUBLIC_KEY") and os.getenv("LANGFUSE_SECRET_KEY"))
st.sidebar.markdown("**Runtime**")
st.sidebar.caption(
f"LLM: {'openai/gpt-oss-120b' if llm_on else 'keyword fallback (portfolio questions only)'}"
)
st.sidebar.caption(
f"Tracing: {'Langfuse + stderr JSON' if langfuse_on else 'stderr JSON only'}"
)
if not llm_on:
st.sidebar.caption(
"_Set `GROQ_API_KEY` + `USE_LLM=true` in `.env` to enable general finance Q&A._"
)
# -----------------------------------------------------------------------------
# Main — chat window
# -----------------------------------------------------------------------------
st.title("Financial Advisor Chat")
st.caption(
f"Context: **{briefing.portfolio.user_name}** · "
f"{briefing.portfolio.portfolio_type} · {briefing.market.context.date}"
)
# Render chat history
for msg in st.session_state.messages:
with st.chat_message(msg["role"]):
st.markdown(msg["content"])
# Show attribution footer on assistant messages when present
if msg["role"] == "assistant" and msg.get("meta"):
st.caption(msg["meta"])
# -----------------------------------------------------------------------------
# Chat input
# -----------------------------------------------------------------------------
if prompt := st.chat_input("Ask about your portfolio or any finance question..."):
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
with st.chat_message("assistant"):
with st.spinner("Thinking..."):
with trace_run(
name=f"chat_{selected}",
metadata={"portfolio_id": selected, "query": prompt[:120]},
):
response, used_llm, tin, tout, lat = chat(
prompt,
briefing,
history=st.session_state.messages[:-1],
)
st.markdown(response)
meta_caption = (
f"{tin}→{tout} tokens · {lat:.0f} ms · via Groq (openai/gpt-oss-120b)"
if used_llm
else "via keyword fallback · enable Gemini for broader answers"
)
st.caption(meta_caption)
st.session_state.messages.append({
"role": "assistant",
"content": response,
"meta": meta_caption,
})