""" AI analysis module using OpenRouter API. Builds prompts from stock stats and streams responses via OpenAI SDK. """ import os from typing import Generator, Optional from openai import OpenAI from dotenv import load_dotenv import streamlit as st from config import OPENROUTER_BASE_URL, MODELS load_dotenv() def _get_api_key() -> Optional[str]: """Get OpenRouter API key from Streamlit secrets or .env.""" try: return st.secrets.get("OPENROUTER_API_KEY") except Exception: pass return os.getenv("OPENROUTER_API_KEY") def _build_prompt(ticker: str, stats: dict) -> str: """Build the analysis prompt from stock statistics.""" rsi_str = f"{stats['rsi']:.1f}" if stats.get("rsi") is not None else "N/A" return f"""You are an expert quantitative analyst. Analyze the following 3-month stock data. TICKER: {ticker} PERIOD: {stats.get('start_date', 'N/A')} to {stats.get('end_date', 'N/A')} KEY STATISTICS: - Current Price: USD {stats.get('current_price', 0):.2f} - 3-Month Return: {stats.get('return_pct', 0):.2f}% - Volatility (std dev): {stats.get('volatility', 0):.2f}% - 52-Week High: USD {stats.get('high_52w', 0):.2f} | Low: USD {stats.get('low_52w', 0):.2f} - Avg Daily Volume: {stats.get('avg_volume', 0):,} - RSI (14-day): {rsi_str} - Price vs 50-day MA: {stats.get('ma_signal', 'N/A')} PRICE SUMMARY (weekly closes): {stats.get('weekly_price_table', 'N/A')} Return ONLY valid JSON in this exact structure, no other text. Use "USD X" format for all prices, never use dollar signs. {{ "summary": "2-3 sentence plain-text summary. No dollar signs - write prices as USD 407 not $407", "trend": "Bullish / Bearish / Neutral", "confidence": "Low / Medium / High", "sections": {{ "trend_analysis": "paragraph text, no special chars", "key_levels": "paragraph text", "pattern_recognition": "paragraph text", "risk_factors": "paragraph text", "short_term_outlook": "paragraph text" }}, "quick_stats": {{ "signal": "Buy / Sell / Hold", "target_price": "USD 420", "stop_loss": "USD 385", "time_horizon": "2-3 weeks" }} }} """ def stream_ai_analysis( ticker: str, stats: dict, model_key: str = "Claude 3.5 Sonnet", ) -> Generator[str, None, None]: """ Stream AI analysis from OpenRouter. Yields tokens for st.write_stream. Raises ValueError on API key missing; yields error message on API failure. """ api_key = _get_api_key() if not api_key: yield "⚠️ **API key not found.** Add `OPENROUTER_API_KEY` in Space Settings → Repository secrets (or `.env` locally)." return model_id = MODELS.get(model_key, MODELS["Claude 3.5 Sonnet"]) prompt = _build_prompt(ticker, stats) try: client = OpenAI( base_url=OPENROUTER_BASE_URL, api_key=api_key, ) stream = client.chat.completions.create( model=model_id, messages=[{"role": "user", "content": prompt}], stream=True, ) for chunk in stream: if chunk.choices and chunk.choices[0].delta.content: yield chunk.choices[0].delta.content except Exception as e: err_msg = str(e).lower() if "rate" in err_msg or "429" in err_msg: yield "⚠️ **Rate limit exceeded.** Please wait a moment and try again." elif "401" in err_msg or "unauthorized" in err_msg: yield "⚠️ **Invalid API key.** Check your OpenRouter credentials." else: yield f"⚠️ **API error:** {str(e)}"