# StockFinancia > AI-powered stock analysis platform that fuses technical indicators, options flow, fundamental data, news sentiment, insider transactions, and quantitative models into a single composite PulseScore — with a conversational AI assistant, a discovery feed, a custom screener, and a per-user alerts system on top. StockFinancia helps retail investors make better-informed decisions by aggregating and interpreting multi-source financial data through a research-backed scoring system. Free, self-hosted, no third-party tracking. ## What it does - **PulseScore (1–10)**: Composite signal that fuses technicals, options sentiment, fundamentals, news sentiment, insider transactions, and earnings events into one actionable score. Verdicts: Strong Buy / Buy / Hold / Caution / Sell. 14 sub-signals across seven categories (Technicals, Volume, Volatility, Options, Fundamentals, Events, Insiders) with per-signal weight contributions shown. - **Technical analysis**: RSI-14, MACD, EMA-50/200 (golden/death cross), Bollinger Bands, Keltner Channels, Stochastic %K/%D, OBV, ADX, ATR across a 60-day window. - **Options flow**: Put/Call Ratio, max pain price, unusual call/put activity from the nearest expiry. - **Fundamentals**: Quarterly revenue, earnings, free cash flow, financial health scoring from SEC filings via Yahoo Finance. - **Events**: Earnings countdown (earnings proximity triggers a risk penalty), analyst consensus, 60-day relative strength vs SPY. - **News sentiment**: Latest headlines scored by VADER NLP (lexicon-based, trained on financial text). - **Insider transactions**: Form 4 buys/sells from the last 90 days with cluster-buying detection (2+ distinct insiders = strong bullish signal). Insider %-of-shares held also fed into the score. - **Congressional trading disclosures**: House and Senate STOCK Act Periodic Transaction Reports (PTRs) scraped daily from disclosures.house.gov and efdsearch.senate.gov. Each stock card shows up to 30 recent trades with chamber, representative name, transaction type (Purchase / Sale), date, and dollar-range. The Discover page surfaces the top-traded tickers across both chambers over the past 60 days. - **Outcome tracking**: Every PulseScore is snapshotted and resolved at +7, +30, and +90 days against actual closing prices. Accuracy stats are computed per user, per ticker, per verdict, and per signal category. ## Discover, Screener, AI Chat, Alerts - **Discover page**: A browseable feed surfaced to every signed-in user (no watchlist required). Six sections: top PulseScores, biggest 1-day movers, insider cluster buying, bullish stocks reporting earnings within 7 days, House STOCK Act most-traded tickers (last 60 days), and Senate STOCK Act most-traded tickers (last 60 days). Powered by a nightly 03:30 UTC scan of a curated ~200-ticker large-cap universe and daily Congress trade scrapes. - **Custom Filter (stock screener)**: A tab inside Discover that filters the same universe by PulseScore range, verdict (Strong Buy / Buy / Hold / Caution / Sell), sector, RSI ceiling, earnings within N days, and insider signal. Returns sorted matches with one-click add-to-watchlist. - **PulseChat (AI assistant)**: Floating chat button on every page opens a streaming side panel. When opened from inside a stock card, the conversation is auto-grounded in that ticker's current snapshot (PulseScore, RSI, MACD histogram, EMA-50/200, insider signal, options PCR, earnings proximity, top 14 signals). The assistant cites real numbers from the snapshot rather than hallucinating. 20 messages per user per day. Runs on a self-hosted llama3.2:3b instance on the cluster. - **Alerts**: Nightly 03:45 UTC scan diffs each user's watchlist tickers against the previous day's snapshot and emits events for: verdict changes (Hold → Buy etc.), insider cluster buying, earnings within 7 days, RSI < 25 or > 75. Bell icon in the nav shows unseen count; clicking opens an inbox timeline. Per-user preferences select which trigger types fire. - **Email digest**: Opt-in. Off by default. Each user picks daily (07:00 UTC) or weekly (Mondays 07:00 UTC) cadence in Settings → Notifications. Sent via Resend; no email is sent when there are no new events. ## Paper Trading Portfolio - **Pretend-buy** any tracked stock with a custom share count. Entry price is locked at the current market price. - **Live unrealised P&L** computed against current prices for every open position. - **Sell** to close a position; the realised P&L locks into a permanent history table. - All trades and history are per-user; visible on the Portfolio page (top-level nav). ## Quantitative models (admin) - **Monte Carlo simulation**: 1000 GBM price paths for a selected ticker with P5/P25/P50/P75/P95 percentile bands plus VaR and CVaR (Expected Shortfall, Basel III coherent risk measure). - **Signal feature importance**: Logistic regression on resolved 30-day snapshots to identify which signals genuinely predict correct outcomes. - **Market regime detection**: 20-day rolling return classifier — bull (>+3%), bear (<-3%), sideways. - **Portfolio correlation heatmap**: Pairwise Pearson correlations on daily log returns for all tracked tickers. - **Signal backtest engine**: Paper-trades all resolved PulseScore verdicts and produces an equity curve, Sharpe ratio, max drawdown, and per-verdict breakdown. - **Weight optimizer**: Coordinate descent optimizer that nudges signal category weights to maximize 30-day accuracy on resolved historical outcomes. Walk-forward optimization runs monthly. ## Per-stock risk panel - Beta vs SPY, annualized volatility, 1-year max drawdown, Sharpe ratio (4% risk-free), ATR-14 - **Hurst exponent** (R/S analysis): H > 0.55 = trending (momentum signals reliable), H < 0.45 = mean-reverting (contrarian signals reliable), H ≈ 0.5 = random walk - **Kelly criterion**: Half-Kelly position sizing computed from the user's own resolved 30-day win rate and average payoff ratio ## Data sources - Price / OHLCV / fundamentals / news: Yahoo Finance via yfinance (15-min cache for prices, 24h for fundamentals) - Insider transactions: Form 4 filings via yfinance (24h cache, 90-day window) - Benchmark: S&P 500 (SPY) for beta and relative strength calculations - Outcomes: Resolved nightly at 02:00 UTC by fetching actual closing prices - Universe: Nightly scan over a curated ~200-ticker large-cap list at 03:30 UTC; the table powers Discover, Custom Filter, and the alert engine - Congressional trades: House PTRs from disclosures.house.gov and Senate PTRs from efdsearch.senate.gov; scraped daily via a dedicated Kubernetes CronJob, stored in a `congress_trades` PostgreSQL table ## Authentication StockFinancia requires account registration. Optional TOTP two-factor authentication is supported. The API uses JWT bearer tokens. All analysis endpoints require authentication. Admin endpoints require an admin-role JWT. ## API base - REST API at `https://stockfinancia.com/api/` - Public: `GET /api/health`, `GET /api/preview/{ticker}` - Authenticated: - Stock data: `GET /api/stocks/{ticker}/data|feel|pulse|risk|news|options|financials|events|insiders|congress|accuracy|kelly` - Watchlist: `GET/POST /api/stocks`, `DELETE /api/stocks/{ticker}` - Discover: `GET /api/discover` - Screener: `POST /api/screener/run`, `GET /api/screener/sectors` - PulseChat: `POST /api/chat` (Server-Sent Events stream), `GET /api/chat/usage` - Alerts: `GET /api/alerts`, `GET /api/alerts/unseen_count`, `POST /api/alerts/mark_seen`, `GET/PATCH /api/alerts/prefs` - Paper trading: `POST /api/paper/buy`, `GET /api/paper/portfolio`, `POST /api/paper/trades/{id}/sell`, `DELETE /api/paper/trades/{id}` - Auth: `POST /api/auth/register|login`, `GET/POST /api/auth/2fa/*`, `POST /api/auth/change-password` - Admin: `GET /api/admin/stats|accuracy|montecarlo/{ticker}|regime/{ticker}|correlations|signal_importance|backtest/equity` ## Tech stack - **Frontend**: React 18, Recharts, Vite. 12 themes (8 dark, 4 light). Responsive nav with hamburger collapse on mobile. - **Backend**: FastAPI (Python 3.11), SQLAlchemy, PostgreSQL. APScheduler for nightly jobs (snapshots, outcome resolution, universe scan, alert scan, email digest, monthly weight optimizer). - **ML / quant**: scikit-learn (logistic regression for signal importance), numpy, pandas. - **LLM**: Self-hosted Ollama (`llama3.2:3b`) running on a Jetson Orin Nano in the same cluster — reached over in-cluster DNS, never sends data off-cluster. - **Email**: Resend transactional API for the opt-in daily/weekly digest. - **Infrastructure**: Kubernetes (K3s), ArgoCD GitOps, Jenkins CI, Longhorn storage, Let's Encrypt TLS, MetalLB. ## Privacy and data ownership - 100% self-hosted on a home-lab Kubernetes cluster. - No analytics SDKs, no third-party tracking, no data sold or shared. - Watchlist, snapshot history, paper portfolio, alert inbox, and accuracy data live in a single PostgreSQL instance under your own infrastructure. - The AI assistant runs on a local LLM — prompts and signal snapshots never leave the cluster.