File size: 8,819 Bytes
81ecaf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbeddca
 
 
 
 
 
 
 
 
 
 
 
81ecaf2
 
 
 
 
 
 
 
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
"""
AI-Powered Stock Ticker Analysis Dashboard
Premium dark financial dashboard with glassmorphism cards.
"""

import json
import re
import streamlit as st

from config import (
    DEFAULT_TICKERS,
    DEFAULT_MODEL,
    MODELS,
    CACHE_TTL,
    TIME_RANGES,
    DEFAULT_TIME_RANGE,
)
from data.fetcher import fetch_stock_data
from ai.analyzer import stream_ai_analysis
from ui.components import (
    inject_custom_css,
    build_candlestick_chart,
    render_ticker_card,
    render_analysis_display,
    render_analysis_carousel_modal,
)

# Page config - wide layout
st.set_page_config(
    page_title="StockAI — Ticker Analysis",
    page_icon="📈",
    layout="wide",
    initial_sidebar_state="expanded",
)

# Inject premium dark theme CSS
inject_custom_css()

# App header
st.markdown(
    '<div class="app-header">'
    '<span class="app-logo">📈 Stock<span>AI</span></span>'
    '</div>',
    unsafe_allow_html=True,
)

# Initialize session state
if "analysis_results" not in st.session_state:
    st.session_state.analysis_results = {}
if "analysis_raw" not in st.session_state:
    st.session_state.analysis_raw = {}
if "show_analysis_modal" not in st.session_state:
    st.session_state.show_analysis_modal = False
if "selected_ticker" not in st.session_state:
    st.session_state.selected_ticker = None
if "time_range" not in st.session_state:
    st.session_state.time_range = DEFAULT_TIME_RANGE


@st.cache_data(ttl=CACHE_TTL)
def get_cached_stock_data(tickers: tuple[str, ...], period_days: int):
    """Cache stock data fetches for 5 minutes."""
    return fetch_stock_data(list(tickers), period_days=period_days)


# --- SIDEBAR ---
with st.sidebar:
    st.markdown("### 📈 StockAI")
    st.markdown('<p style="font-size:0.7rem; color:#6B7280; text-transform:uppercase; letter-spacing:0.1em;">Tickers</p>', unsafe_allow_html=True)

    ticker_inputs = []
    for i in range(5):
        default = DEFAULT_TICKERS[i] if i < len(DEFAULT_TICKERS) else ""
        t = st.text_input(f"Ticker {i + 1}", value=default, key=f"ticker_{i}", label_visibility="collapsed")
        ticker_inputs.append(t.strip().upper() if t else "")

    tickers = [t for t in ticker_inputs if t]

    st.markdown("---")
    st.markdown('<p style="font-size:0.7rem; color:#6B7280; text-transform:uppercase; letter-spacing:0.1em;">AI Model</p>', unsafe_allow_html=True)
    model_choice = st.selectbox(
        "Model",
        options=list(MODELS.keys()),
        index=list(MODELS.keys()).index(DEFAULT_MODEL),
        key="model_select",
        label_visibility="collapsed",
    )

    st.markdown("---")
    run_analysis_btn = st.button("▶ Run Analysis", type="primary", use_container_width=True)
    refresh_btn = st.button("↺ Refresh Data", type="secondary", use_container_width=True)

if refresh_btn:
    get_cached_stock_data.clear()
    st.rerun()

# --- MAIN CONTENT ---
if not tickers:
    st.warning("Enter at least one ticker symbol in the sidebar.")
    st.stop()

period_days = TIME_RANGES.get(st.session_state.time_range, 90)

try:
    data = get_cached_stock_data(tuple(tickers), period_days)
except Exception as e:
    st.error(f"Failed to fetch data: {e}")
    st.stop()

valid_tickers = [t for t in tickers if data.get(t) and not data[t].get("error")]
if not valid_tickers:
    st.error("No valid data for any ticker. Check symbols or try again later.")
    st.stop()

# --- TOP ROW: 5 mini ticker cards ---
n_cols = max(1, min(5, len(valid_tickers)))
cols = st.columns(n_cols)
for i, t in enumerate(valid_tickers[:5]):
    with cols[i]:
        if render_ticker_card(t, data[t]["stats"], t == st.session_state.selected_ticker, f"tc_{t}"):
            st.session_state.selected_ticker = t
            st.rerun()

# Default selected ticker
if st.session_state.selected_ticker not in valid_tickers:
    st.session_state.selected_ticker = valid_tickers[0]
selected_ticker = st.session_state.selected_ticker

# --- CHART SECTION ---
ticker_data = data[selected_ticker]
df = ticker_data["df"]
stats = ticker_data["stats"]

st.markdown('<div class="chart-container">', unsafe_allow_html=True)

# Chart header: ticker, price, change, time range pills
col_title, col_pills = st.columns([3, 1])
with col_title:
    return_pct = stats["return_pct"]
    arrow = "▲" if return_pct >= 0 else "▼"
    color = "#10B981" if return_pct >= 0 else "#EF4444"
    period_label = st.session_state.time_range
    st.markdown(
        f"### {selected_ticker} — Price Chart  "
        f"${stats['current_price']:.2f}  "
        f'<span style="color:{color};">{arrow} {return_pct:+.2f}% ({period_label})</span>',
        unsafe_allow_html=True,
    )
with col_pills:
    pill_cols = st.columns(len(TIME_RANGES))
    for i, (label, _) in enumerate(TIME_RANGES.items()):
        with pill_cols[i]:
            if st.button(label, key=f"tr_{label}", type="primary" if st.session_state.time_range == label else "secondary"):
                st.session_state.time_range = label
                st.rerun()

show_bollinger = st.checkbox("☐ Bollinger Bands", value=False, key="bb_toggle")
show_volume = st.checkbox("☐ Show Volume", value=True, key="vol_toggle")

fig = build_candlestick_chart(df, selected_ticker, show_ma=True, show_bollinger=show_bollinger, show_volume=show_volume)
st.plotly_chart(fig, use_container_width=True)

st.markdown('</div>', unsafe_allow_html=True)

# --- BOTTOM ROW: 60/40 split ---
col_metrics, col_ai = st.columns([0.6, 0.4])

with col_metrics:
    st.markdown("#### Key Metrics")
    m1, m2 = st.columns(2)
    with m1:
        st.metric("Current", f"${stats['current_price']:.2f}", None)
        st.metric("52W Low", f"${stats['low_52w']:.2f}", None)
        rsi = stats.get("rsi")
        st.metric("RSI (14)", f"{rsi:.1f}" if rsi is not None else "N/A", None)
    with m2:
        st.metric("52W High", f"${stats['high_52w']:.2f}", None)
        vol = stats.get("avg_volume", 0)
        vol_str = f"{vol/1e6:.1f}M" if vol >= 1e6 else f"{vol/1e3:.0f}K"
        st.metric("Avg Volume", vol_str, None)
        st.metric(f"{st.session_state.time_range} Return", f"{stats['return_pct']:+.2f}%", None)

with col_ai:
    st.markdown("#### 🤖 AI Analysis")

    trigger_from_ai = st.session_state.pop("_trigger_analysis", False)
    if run_analysis_btn or trigger_from_ai:
        full_response = ""
        with st.spinner(f"Analyzing **{selected_ticker}**..."):
            for token in stream_ai_analysis(selected_ticker, stats, model_choice):
                full_response += token

        st.session_state.analysis_raw[selected_ticker] = full_response
        raw = full_response.strip()
        if raw.startswith("```"):
            raw = re.sub(r"^```(?:json)?\s*", "", raw)
            raw = re.sub(r"\s*```$", "", raw)
        try:
            parsed = json.loads(raw)
            st.session_state.analysis_results[selected_ticker] = parsed
        except json.JSONDecodeError:
            if selected_ticker in st.session_state.analysis_results:
                del st.session_state.analysis_results[selected_ticker]

    has_any_analysis = bool(st.session_state.analysis_results or st.session_state.analysis_raw)
    if selected_ticker in st.session_state.analysis_results:
        render_analysis_display(st.session_state.analysis_results[selected_ticker])
    elif selected_ticker in st.session_state.analysis_raw:
        with st.expander("⚠️ Raw response (JSON parse failed)", expanded=True):
            st.text(st.session_state.analysis_raw[selected_ticker])
    else:
        st.info("Click **Run Analysis** to generate insights.")
        if st.button("▶ Run Analysis", key="ai_run_btn", type="primary", use_container_width=True):
            st.session_state._trigger_analysis = True
            st.rerun()

    if has_any_analysis:
        if st.button("📊 View AI Analysis", type="secondary", use_container_width=True):
            st.session_state.show_analysis_modal = True

# Analysis modal
if st.session_state.get("show_analysis_modal") and has_any_analysis:
    def on_dismiss():
        st.session_state.show_analysis_modal = False

    if hasattr(st, "dialog"):
        @st.dialog("AI Analysis — Switch Between Tickers", width="large", on_dismiss=on_dismiss)
        def analysis_modal():
            render_analysis_carousel_modal(
                st.session_state.analysis_results,
                st.session_state.analysis_raw,
                on_close=on_dismiss,
            )

        analysis_modal()
    else:
        st.markdown("#### AI Analysis — Switch Between Tickers")
        render_analysis_carousel_modal(
            st.session_state.analysis_results,
            st.session_state.analysis_raw,
            on_close=on_dismiss,
        )

st.markdown("---")
st.caption("Data via yfinance • AI via OpenRouter • 5-min cache")