Download src/streamlit_app.py from margotbtn/finsight: direct link, hf CLI and curl.
- Browser
- Download file 6.71 kB
-
https://huggingface.co/spaces/margotbtn/finsight/resolve/main/src/streamlit_app.py
- Command line
-
hf download hf://spaces/margotbtn/finsight/src/streamlit_app.py
-
curl -L -o streamlit_app.py https://huggingface.co/spaces/margotbtn/finsight/resolve/main/src/streamlit_app.py
6.71 kB
| """ | |
| FinSight — Market Intelligence Agent | |
| Streamlit interface for Hugging Face Spaces deployment. | |
| """ | |
| import asyncio | |
| import os | |
| import queue | |
| import sys | |
| import threading | |
| import streamlit as st | |
| # --------------------------------------------------------------------------- | |
| # Page config | |
| # --------------------------------------------------------------------------- | |
| st.set_page_config( | |
| page_title="FinSight — Market Intelligence Agent", | |
| page_icon="📈", | |
| layout="wide", | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Data initialisation (runs once per app process, streamed to UI) | |
| # --------------------------------------------------------------------------- | |
| def _init_flag() -> dict: | |
| """Shared mutable flag so init only runs once across reruns.""" | |
| return {"done": False} | |
| def _run_init(log_queue: queue.Queue) -> None: | |
| """Run data init in a background thread, forwarding print output to the queue.""" | |
| root = os.path.dirname(os.path.abspath(__file__)) | |
| if root not in sys.path: | |
| sys.path.insert(0, root) | |
| # Redirect stdout so print() calls from generate_db / ingest_news appear in the UI | |
| class _QueueWriter: | |
| def write(self, s: str) -> None: | |
| stripped = s.rstrip("\n") | |
| if stripped: | |
| log_queue.put(stripped) | |
| def flush(self) -> None: | |
| pass | |
| old_stdout = sys.stdout | |
| sys.stdout = _QueueWriter() # type: ignore[assignment] | |
| try: | |
| from data.generate_db import main as gen_main | |
| from data.ingest_news import main as news_main | |
| gen_main() | |
| news_main() | |
| except Exception as exc: | |
| log_queue.put(f"ERROR during init: {exc}") | |
| finally: | |
| sys.stdout = old_stdout | |
| log_queue.put(None) # sentinel | |
| def init_data() -> None: | |
| """Show a streaming status box while data is being initialised.""" | |
| flag = _init_flag() | |
| if flag["done"]: | |
| return | |
| log_queue: queue.Queue = queue.Queue() | |
| thread = threading.Thread(target=_run_init, args=(log_queue,), daemon=True) | |
| thread.start() | |
| with st.status("Initialising market data…", expanded=True) as status: | |
| had_error = False | |
| while True: | |
| try: | |
| line = log_queue.get(timeout=600) | |
| except queue.Empty: | |
| status.update(label="Init timed out.", state="error") | |
| break | |
| if line is None: | |
| if had_error: | |
| status.update(label="Init finished with errors — see log above.", state="error") | |
| else: | |
| status.update(label="Market data ready!", state="complete") | |
| flag["done"] = True | |
| break | |
| if line.startswith("ERROR"): | |
| had_error = True | |
| st.write(line) | |
| thread.join(timeout=5) | |
| # Trigger at startup; instant no-op on subsequent Streamlit reruns | |
| init_data() | |
| # --------------------------------------------------------------------------- | |
| # Sidebar | |
| # --------------------------------------------------------------------------- | |
| with st.sidebar: | |
| st.title("⚙️ Configuration") | |
| api_key = st.text_input( | |
| "Anthropic API Key", | |
| type="password", | |
| placeholder="sk-ant-...", | |
| help="Your key is used only for this request and never stored.", | |
| value=st.session_state.get("api_key", ""), | |
| ) | |
| if api_key: | |
| st.session_state["api_key"] = api_key | |
| st.divider() | |
| st.markdown( | |
| """ | |
| **How it works** | |
| 1. Enter your [Anthropic API key](https://console.anthropic.com/) | |
| 2. Type an investment question | |
| 3. The agent calls two MCP tools: | |
| - 📊 **SQL** — prices, RSI, MACD, P/E… | |
| - 📰 **RAG** — semantic news search | |
| 4. Claude synthesises a structured analysis | |
| **Covered tickers** | |
| AAPL MSFT NVDA GOOGL META AMZN TSLA AMD | |
| INTC CRM JPM GS BAC V MA JNJ PFE UNH | |
| ABBV XOM CVX WMT KO MCD SPY | |
| """ | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Main | |
| # --------------------------------------------------------------------------- | |
| st.title("📈 FinSight — Market Intelligence Agent") | |
| st.caption("AI-powered stock analysis · technical indicators + financial news · powered by Claude") | |
| st.divider() | |
| EXAMPLE_QUESTIONS = [ | |
| "Is NVIDIA a good buy right now?", | |
| "Compare AAPL, MSFT and GOOGL on momentum", | |
| "What's the market sentiment around Tesla?", | |
| "Should I buy JPMorgan or Goldman Sachs?", | |
| ] | |
| with st.expander("Example questions"): | |
| for q in EXAMPLE_QUESTIONS: | |
| if st.button(q, key=q): | |
| st.session_state["question_input"] = q | |
| question = st.text_area( | |
| "Your question", | |
| placeholder="e.g. Is NVIDIA a good buy right now?", | |
| value=st.session_state.get("question_input", ""), | |
| height=80, | |
| ) | |
| run_btn = st.button("Analyse", type="primary", disabled=not question) | |
| # --------------------------------------------------------------------------- | |
| # Run agent | |
| # --------------------------------------------------------------------------- | |
| if run_btn: | |
| api_key = st.session_state.get("api_key", "") | |
| if not api_key: | |
| st.error("Please enter your Anthropic API key in the sidebar.") | |
| st.stop() | |
| if not question.strip(): | |
| st.warning("Please enter a question.") | |
| st.stop() | |
| from agent import run_agent_stream | |
| st.divider() | |
| col_log, col_result = st.columns([1, 2]) | |
| with col_log: | |
| st.subheader("Activity") | |
| log_placeholder = st.empty() | |
| with col_result: | |
| st.subheader("Analysis") | |
| result_placeholder = st.empty() | |
| # Run the async agent in a background thread, ferry events via a queue | |
| event_queue: queue.Queue = queue.Queue() | |
| def _run() -> None: | |
| async def _collect() -> None: | |
| async for event in run_agent_stream(question, api_key): | |
| event_queue.put(event) | |
| asyncio.run(_collect()) | |
| event_queue.put(None) # sentinel | |
| thread = threading.Thread(target=_run, daemon=True) | |
| thread.start() | |
| log_lines: list[str] = [] | |
| while True: | |
| try: | |
| event = event_queue.get(timeout=120) | |
| except queue.Empty: | |
| st.error("Timed out waiting for a response.") | |
| break | |
| if event is None: | |
| break | |
| if event["type"] == "log": | |
| log_lines.append(event["text"]) | |
| log_placeholder.code("\n".join(log_lines), language=None) | |
| elif event["type"] == "result": | |
| result_placeholder.markdown(event["text"]) | |
| thread.join(timeout=5) | |