A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.
Add stock portfolio analysts
cyberholicse025be9507e3
diff --git a/README.md b/README.mdindex 8180c68..a3d1f9e 100644--- a/README.md+++ b/README.md@@ -49,6 +49,7 @@ Intelligent ai agents for various automation tasks.- [**Multi-Agent Research Assistant (AG2)**](./ai_agents/multi_agent_research_assistant_ag2) — Production-grade multi-agent research pipeline using AG2 (formerly AutoGen). Three specialists collaborate under GroupChat with LLM-driven speaker selection to research any topic and produce a structured Markdown report.- [**Self-Reflective Agentic RAG**](./ai_agents/agentic_rag_system) — LangGraph-driven RAG system that grades retrieved context for relevance and sufficiency, rewrites the query if needed, and only generates an answer once the context passes validation — reducing hallucinations through an iterative retrieval loop.- [**Agentic SQL Search**](./ai_agents/agentic_sql_search) — Natural language to SQL agent powered by Gemma 4. Ask plain-English questions about an e-commerce database and the agent writes, executes, and explains the SQL query — with full reasoning transparency in the Streamlit UI.+- [**Stock Portfolio Analyst**](./ai_agents/stock_portfolio_analyst) — AI-powered portfolio analysis agent built with Agno and DeepSeek-V4-Flash. Takes ticker symbols, share counts, and purchase prices, fetches live market data via YFinance, and generates a streaming report covering P&L, concentration risk, valuation flags, and rebalancing recommendations.### 📸 OCRdiff --git a/ai_agents/stock_portfolio_analyst/.env.example b/ai_agents/stock_portfolio_analyst/.env.examplenew file mode 100644index 0000000..78b5611--- /dev/null+++ b/ai_agents/stock_portfolio_analyst/.env.example@@ -0,0 +1 @@+NVIDIA_API_KEY=your_nvidia_api_key_herediff --git a/ai_agents/stock_portfolio_analyst/.gitignore b/ai_agents/stock_portfolio_analyst/.gitignorenew file mode 100644index 0000000..c93f225--- /dev/null+++ b/ai_agents/stock_portfolio_analyst/.gitignore@@ -0,0 +1,20 @@+# Environment+.env++# Virtual environment+.venv/+venv/+__pycache__/+*.pyc++# uv+.python-version+uv.lock++# IDE+.vscode/+.idea/++# OS+.DS_Store+Thumbs.dbdiff --git a/ai_agents/stock_portfolio_analyst/README.md b/ai_agents/stock_portfolio_analyst/README.mdnew file mode 100644index 0000000..5f0c542--- /dev/null+++ b/ai_agents/stock_portfolio_analyst/README.md@@ -0,0 +1,135 @@+# 📈 Stock Portfolio Analyst++> **Powered by [DeepSeek-V4-Flash](https://build.nvidia.com/deepseek-ai/deepseek-v4-flash) via NVIDIA API — fast, cost-efficient reasoning for real-time financial analysis**++++## Overview++An AI-powered portfolio analysis agent that evaluates stock holdings using live market data. Enter your tickers, share counts, and average purchase prices, and the agent fetches real-time pricing and fundamentals via YFinance, searches for recent news via DuckDuckGo, and generates a comprehensive portfolio review — streamed live in the UI as it builds.++The report covers P&L per position, portfolio-level metrics, concentration and valuation risk flags, sector breakdown, and specific rebalancing recommendations.++## Features++- **Live Market Data:** Fetches real-time prices, fundamentals, and analyst ratings via YFinance for every holding+- **P&L Calculations:** Unrealized gain/loss per position (absolute and percentage) plus portfolio totals+- **Risk Assessment:** Flags concentration risk (positions > 20%), valuation extremes (P/E > 40), and negative news sentiment+- **Sector Breakdown:** Visualizes portfolio weight across sectors to identify diversification gaps+- **Rebalancing Recommendations:** Specific, data-driven suggestions on what to trim, hold, or add+- **Streaming Output:** Analysis streams in real time as the agent works through each holding+- **Pre-loaded Example Portfolio:** A 7-stock portfolio is ready to analyze on first launch+- **Quick Question Buttons:** One-click common analysis queries in the sidebar++## Tech Stack++**Framework & Tools:**+- [Agno](https://docs.agno.com/): Agent framework orchestrating tool use and LLM reasoning+- [YFinanceTools](https://docs.agno.com/): Live stock prices, fundamentals, analyst recommendations, company news+- [DuckDuckGoTools](https://docs.agno.com/): Real-time web search for market context and headlines+- [CalculatorTools](https://docs.agno.com/): Precise P&L and concentration calculations++**Model:**+- **[DeepSeek-V4-Flash](https://build.nvidia.com/deepseek-ai/deepseek-v4-flash)** (`deepseek-ai/deepseek-v4-flash`) — fast and cost-efficient reasoning via the NVIDIA API++**UI:**+- [Gradio](https://www.gradio.app/): Interactive web interface with streaming markdown output++## Prerequisites++- Python 3.10 or higher+- [uv](https://docs.astral.sh/uv/) (recommended) or pip+- An [NVIDIA API key](https://build.nvidia.com/) (free tier available)++## Installation++### 1. Clone the Repository++```bash+git clone https://github.com/Sumanth077/Hands-On-AI-Engineering.git+cd Hands-On-AI-Engineering/ai_agents/stock_portfolio_analyst+```++### 2. Set Up Environment Variables++```bash+cp .env.example .env+```++Open `.env` and add your NVIDIA API key:++```env+NVIDIA_API_KEY=your_nvidia_api_key_here+```++Get your API key at [build.nvidia.com](https://build.nvidia.com/).++### 3. Install Dependencies++```bash+uv sync+```++## Usage++```bash+uv run python app.py+```++Navigate to `http://localhost:7860` in your browser.++1. **Edit the portfolio table** — update tickers, share counts, and average purchase prices+2. **Type a question** or leave it blank for a full portfolio review+3. Click **Analyze Portfolio** — the report streams in real time as the agent fetches data+4. Use the **Quick Question** buttons for common one-click analyses+5. Click **Reset** to restore the example portfolio++## How It Works++```+User Portfolio Input+ │+ ▼+ YFinanceTools ← live price, fundamentals, analyst ratings per ticker+ │+ ▼+ DuckDuckGoTools ← recent news and market context+ │+ ▼+ CalculatorTools ← P&L, weight, concentration calculations+ │+ ▼+ DeepSeek-V4-Flash ← synthesizes data into structured markdown report+ │+ ▼+ Streamed Report ← Summary · Holdings · Risk Flags · Rebalancing+```++## Project Structure++```text+stock_portfolio_analyst/+├── app.py # Gradio UI and streaming interface+├── agent.py # Agno agent, DeepSeek-V4-Flash model, tool config, prompt+├── assets/+│ └── demo.png # App screenshot+├── .env.example # API key template+├── pyproject.toml # Project dependencies (uv)+└── README.md+```++## Disclaimer++This tool is for educational and informational purposes only. Nothing in this application constitutes financial advice. Always consult a qualified financial advisor before making investment decisions.++## Contributing++Contributions are welcome! Please feel free to submit a Pull Request.++## License++This project is licensed under the MIT License. See the [LICENSE](../../LICENSE) file for details.++---++[⬆ Back to Top](#-stock-portfolio-analyst)diff --git a/ai_agents/stock_portfolio_analyst/agent.py b/ai_agents/stock_portfolio_analyst/agent.pynew file mode 100644index 0000000..2ce466f--- /dev/null+++ b/ai_agents/stock_portfolio_analyst/agent.py@@ -0,0 +1,126 @@+"""+Stock Portfolio Analyst — Agno agent powered by DeepSeek-V4-Flash.++Tools:+ • YFinanceTools — live prices, fundamentals, analyst ratings, company news+ • DuckDuckGoTools — broader market context and recent headlines+ • CalculatorTools — precise P&L and concentration calculations+"""++import os+from dotenv import load_dotenv+from agno.agent import Agent+from agno.models.openai.like import OpenAILike+from agno.tools.yfinance import YFinanceTools+from agno.tools.duckduckgo import DuckDuckGoTools+from agno.tools.calculator import CalculatorTools++load_dotenv()++MODEL_ID = "deepseek-ai/deepseek-v4-flash"+NVIDIA_BASE_URL = "https://integrate.api.nvidia.com/v1"++INSTRUCTIONS = """You are an expert financial analyst and portfolio manager.+Your job is to analyze a stock portfolio comprehensively using live market data.++WORKFLOW — follow this order exactly:+1. For EACH holding, use YFinance to fetch:+ - Current stock price+ - Key fundamentals: P/E ratio, P/B ratio, EPS, market cap, sector, industry+ - 52-week high/low range+ - Analyst recommendations summary++2. CALCULATE for each position:+ - Current market value = shares × current price+ - Cost basis = shares × average purchase price+ - Unrealized P&L = current value - cost basis+ - Unrealized P&L % = ((current price - avg cost) / avg cost) × 100+ - Position weight = (current value / total portfolio value) × 100++3. CALCULATE portfolio-level metrics:+ - Total portfolio value+ - Total cost basis+ - Total unrealized P&L and P&L %+ - Sector breakdown and weights++4. Use DuckDuckGo to search for any significant recent news on the holdings.++5. Use Calculator to verify key calculations.++6. IDENTIFY risks:+ - Concentration risk: any position > 20% of total portfolio+ - Valuation risk: P/E > 40 or negative P/E+ - Sentiment risk: recent negative news or analyst downgrades+ - Sector concentration: > 50% in one sector++OUTPUT FORMAT — return a structured markdown report with these sections:++## 📊 Portfolio Summary+A summary table: Total Value, Total Cost, Total P&L, Total P&L%++## 📋 Holdings Analysis+A detailed table with columns:+Ticker | Sector | Shares | Avg Cost | Current Price | Value | P&L | P&L% | Weight%++## 📈 Top Performers & Laggards+Best and worst performing positions with brief commentary.++## ⚠️ Risk Assessment+Bullet list of identified risks with severity (HIGH / MEDIUM / LOW).++## 🔄 Rebalancing Recommendations+Specific, actionable suggestions: what to trim, what to add, what to hold.++## 📰 Recent News Highlights+Key headlines relevant to the portfolio holdings.++Be precise, data-driven, and actionable. Always fetch live data — never estimate prices."""+++agent = Agent(+ model=OpenAILike(+ id=MODEL_ID,+ api_key=os.getenv("NVIDIA_API_KEY"),+ base_url=NVIDIA_BASE_URL,+ ),+ tools=[+ YFinanceTools(+ enable_stock_price=True,+ enable_stock_fundamentals=True,+ enable_key_financial_ratios=True,+ enable_analyst_recommendations=True,+ enable_company_news=True,+ enable_historical_prices=True,+ enable_technical_indicators=True,+ ),+ DuckDuckGoTools(),+ CalculatorTools(),+ ],+ instructions=INSTRUCTIONS,+ markdown=True,+)+++def format_prompt(holdings: list[dict], question: str) -> str:+ """Format holdings into a markdown table and append the user's question."""+ rows = "\n".join(+ f"| {h['ticker']} | {h['shares']} | ${h['avg_cost']:.2f} |"+ for h in holdings+ )+ table = f"| Ticker | Shares | Avg Cost (USD) |\n|--------|--------|----------------|\n{rows}"++ question = question.strip() or (+ "Provide a comprehensive portfolio analysis: P&L per position, "+ "portfolio-level metrics, concentration and valuation risks, "+ "and specific rebalancing recommendations."+ )++ return f"Analyze the following stock portfolio:\n\n{table}\n\nQuestion: {question}"+++def run_analysis(holdings: list[dict], question: str):+ """Generator — yields streaming text chunks of the analysis report."""+ prompt = format_prompt(holdings, question)+ for chunk in agent.run(prompt, stream=True):+ if chunk.content:+ yield chunk.contentdiff --git a/ai_agents/stock_portfolio_analyst/app.py b/ai_agents/stock_portfolio_analyst/app.pynew file mode 100644index 0000000..7472a16--- /dev/null+++ b/ai_agents/stock_portfolio_analyst/app.py@@ -0,0 +1,186 @@+"""+Stock Portfolio Analyst — Gradio UI+Run: python app.py or gradio app.py+"""++import pandas as pd+import gradio as gr+from agent import run_analysis, MODEL_ID++# ── Default example portfolio ──────────────────────────────────────────────────+DEFAULT_PORTFOLIO = [+ ["AAPL", 10, 150.00],+ ["MSFT", 5, 300.00],+ ["NVDA", 8, 450.00],+ ["GOOGL", 3, 140.00],+ ["AMZN", 4, 180.00],+ ["TSLA", 6, 200.00],+ ["META", 7, 320.00],+]++QUICK_QUESTIONS = [+ "Full analysis: P&L, risk, and rebalancing recommendations",+ "Which positions should I trim or exit?",+ "What are my biggest concentration and valuation risks?",+ "How is my portfolio diversified across sectors?",+]+++# ── Helpers ────────────────────────────────────────────────────────────────────++def parse_portfolio(df) -> list[dict]:+ """Parse a Gradio Dataframe into a list of holding dicts."""+ holdings = []+ if not isinstance(df, pd.DataFrame):+ return holdings+ for _, row in df.iterrows():+ try:+ ticker = str(row.iloc[0]).strip().upper()+ shares = float(row.iloc[1])+ avg_cost = float(row.iloc[2])+ if ticker and ticker not in ("", "NAN", "NONE") and shares > 0 and avg_cost > 0:+ holdings.append({"ticker": ticker, "shares": shares, "avg_cost": avg_cost})+ except (ValueError, TypeError):+ continue+ return holdings+++def analyze(portfolio_df, question):+ """Generator — streams the analysis report into the Markdown output."""+ holdings = parse_portfolio(portfolio_df)++ if not holdings:+ yield "⚠️ Please add at least one valid holding (ticker, shares, avg cost) before analyzing."+ return++ tickers = ", ".join(h["ticker"] for h in holdings)+ yield f"*Fetching live data for {tickers} and running analysis...*\n\n"++ report = ""+ try:+ for chunk in run_analysis(holdings, question or ""):+ report += chunk+ yield report+ except Exception as e:+ yield f"❌ Analysis error: {e}"+++def reset():+ return (+ pd.DataFrame(DEFAULT_PORTFOLIO, columns=["Ticker (e.g. AAPL)", "Shares Owned", "Avg Purchase Price ($)"]),+ "",+ "*Your analysis will appear here once you click Analyze Portfolio.*",+ )+++# ── Gradio UI ──────────────────────────────────────────────────────────────────++with gr.Blocks(+ theme=gr.themes.Soft(),+ title="Stock Portfolio Analyst — DeepSeek-V4-Flash",+ css="""+ .model-badge {+ display: inline-block;+ background: #1a1a2e;+ color: #00d4ff;+ padding: 2px 10px;+ border-radius: 12px;+ font-size: 0.78em;+ font-weight: 600;+ letter-spacing: 0.03em;+ }+ .footer-note { text-align: center; opacity: 0.55; font-size: 0.82em; margin-top: 8px; }+ """,+) as demo:++ # ── Header ──+ gr.Markdown(f"""+ # 📈 Stock Portfolio Analyst+ <span class="model-badge">⚡ DeepSeek-V4-Flash</span>+ Powered by **Agno** · **YFinance** · **DuckDuckGo**++ Enter your holdings, ask a question (or leave blank for a full review), and hit **Analyze**.+ The agent fetches live market data, calculates P&L per position, and generates a structured report — streamed in real time.+ """)++ gr.Markdown("---")++ with gr.Row(equal_height=False):++ # ── Left column: inputs ──+ with gr.Column(scale=2):+ gr.Markdown("### 📋 Your Stock Holdings")+ gr.Markdown(+ "Click any cell to edit. "+ "**Ticker** = stock symbol (e.g. AAPL), "+ "**Shares** = number of shares you own, "+ "**Avg Cost** = your average purchase price in USD."+ )+ portfolio_table = gr.Dataframe(+ headers=["Ticker (e.g. AAPL)", "Shares Owned", "Avg Purchase Price ($)"],+ datatype=["str", "number", "number"],+ row_count=(8, "dynamic"),+ col_count=(3, "fixed"),+ interactive=True,+ value=pd.DataFrame(+ DEFAULT_PORTFOLIO,+ columns=["Ticker (e.g. AAPL)", "Shares Owned", "Avg Purchase Price ($)"],+ ),+ label="",+ )++ gr.Markdown("### 💬 Analysis Question")+ question_input = gr.Textbox(+ placeholder="Leave blank for a full portfolio review, or ask something specific...",+ label="",+ lines=2,+ )++ gr.Markdown("**Quick Questions:**")+ with gr.Row():+ btn1 = gr.Button(QUICK_QUESTIONS[0], size="sm")+ btn2 = gr.Button(QUICK_QUESTIONS[1], size="sm")+ with gr.Row():+ btn3 = gr.Button(QUICK_QUESTIONS[2], size="sm")+ btn4 = gr.Button(QUICK_QUESTIONS[3], size="sm")++ gr.Markdown("---")+ with gr.Row():+ analyze_btn = gr.Button("🔍 Analyze Portfolio", variant="primary", scale=3)+ reset_btn = gr.Button("🔄 Reset", variant="secondary", scale=1)++ # ── Right column: output ──+ with gr.Column(scale=3):+ gr.Markdown("### 📊 Analysis Report")+ output = gr.Markdown(+ value="*Your analysis will appear here once you click Analyze Portfolio.*",+ height=680,+ )++ # ── Footer ──+ gr.Markdown(+ f"""<div class="footer-note">+ Model: <strong>DeepSeek-V4-Flash</strong> (deepseek-ai/deepseek-v4-flash) via NVIDIA API | + Framework: Agno | Market Data: YFinance | + This is not financial advice.+ </div>""",+ )++ # ── Event wiring ──+ for btn, q in zip([btn1, btn2, btn3, btn4], QUICK_QUESTIONS):+ btn.click(fn=lambda q=q: q, outputs=question_input)++ analyze_btn.click(+ fn=analyze,+ inputs=[portfolio_table, question_input],+ outputs=output,+ )++ reset_btn.click(+ fn=reset,+ outputs=[portfolio_table, question_input, output],+ )+++if __name__ == "__main__":+ demo.launch()diff --git a/ai_agents/stock_portfolio_analyst/assets/demo.png b/ai_agents/stock_portfolio_analyst/assets/demo.pngnew file mode 100644index 0000000..5d6fef4Binary files /dev/null and b/ai_agents/stock_portfolio_analyst/assets/demo.png differdiff --git a/ai_agents/stock_portfolio_analyst/pyproject.toml b/ai_agents/stock_portfolio_analyst/pyproject.tomlnew file mode 100644index 0000000..7bdd9b3--- /dev/null+++ b/ai_agents/stock_portfolio_analyst/pyproject.toml@@ -0,0 +1,15 @@+[project]+name = "stock-portfolio-analyst"+version = "0.1.0"+description = "AI-powered stock portfolio analyst using DeepSeek-V4-Flash, Agno, and YFinance"+readme = "README.md"+requires-python = ">=3.10"+dependencies = [+ "agno>=1.3.0",+ "openai>=1.0.0",+ "yfinance>=0.2.50",+ "ddgs>=0.5.0",+ "gradio>=5.0.0",+ "pandas>=2.0.0",+ "python-dotenv>=1.1.1",+]