Spaces:
Sleeping
Sleeping
File size: 11,622 Bytes
b38c914 |
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 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 |
{
"cells": [
{
"cell_type": "markdown",
"id": "d1ff97f3",
"metadata": {},
"source": [
"\n",
"\n",
"<table style=\"margin: 0; text-align: left; width:100%\">\n",
" <tr>\n",
" <td style=\"width: 150px; height: 150px; vertical-align: middle;\">\n",
" </td>\n",
" <td>\n",
" <h2 style=\"color:#ff7800;\">Important point - please read</h2>\n",
" <span style=\"color:#ff7800;\">This is the experiment to analyze the stocks based on the Benjamin Graham's The Intelligent Investor. This tool Analyze any stock symbol from the NSE (National Stock Exchange) or BSE (Bombay Stock Exchange) \n",
"This is just the learning purpose and no investment advice should be taken from this.\n",
" </span>\n",
" </td>\n",
" </tr>\n",
"</table>"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3f99eb40",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "c0943f71",
"metadata": {},
"outputs": [],
"source": [
"\n",
"from dotenv import load_dotenv\n",
"\n",
"load_dotenv(override=True)\n",
"\n",
"!uv add yfinance pandas\n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b86f232b",
"metadata": {},
"outputs": [],
"source": [
"# Install dependencies (only needed once in your env)\n",
"!uv add yfinance pandas\n",
"\n",
"# Import them\n",
"import yfinance as yf\n",
"import pandas as pd\n",
"\n",
"from IPython.display import Markdown, display"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "09368124",
"metadata": {},
"outputs": [],
"source": [
"# Example: Reliance Industries on NSE\n",
"stock_symbol = \"TCS.NS\" # You can change to TCS.NS, INFY.NS, etc."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "410494b4",
"metadata": {},
"outputs": [],
"source": [
"# LLM client setup (OpenAI + Groq via OpenAI-compatible API)\n",
"import os\n",
"from dotenv import load_dotenv\n",
"from openai import OpenAI\n",
"\n",
"load_dotenv(override=True)\n",
"\n",
"OPENAI_API_KEY = os.getenv(\"OPENAI_API_KEY\")\n",
"GROQ_API_KEY = os.getenv(\"GROQ_API_KEY\")\n",
"\n",
"openai_client = OpenAI(api_key=OPENAI_API_KEY) if OPENAI_API_KEY else None\n",
"# Groq uses OpenAI-compatible endpoint|\n",
"GROQ_BASE_URL = \"https://api.groq.com/openai/v1\"\n",
"groq_client = OpenAI(api_key=GROQ_API_KEY, base_url=GROQ_BASE_URL) if GROQ_API_KEY else None\n",
"\n",
"print(\n",
" f\"OpenAI: {'ON' if openai_client else 'OFF'} | Groq: {'ON' if groq_client else 'OFF'}\"\n",
")\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a5c38c6f",
"metadata": {},
"outputs": [],
"source": [
"# Helper: compute Benjamin Graham-style checks (simplified for public data)\n",
"# Note: True Graham analysis needs per-share earnings for multi-year periods and balance-sheet figures.\n",
"# We use yfinance fields as proxies and document assumptions.\n",
"import numpy as np\n",
"\n",
"\n",
"def compute_graham_checks(ticker: str):\n",
" T = yf.Ticker(ticker)\n",
"\n",
" # Price and trailing PE proxy\n",
" info = T.info if hasattr(T, \"info\") else {}\n",
" current_price = info.get(\"currentPrice\")\n",
" trailing_pe = info.get(\"trailingPE\")\n",
" forward_pe = info.get(\"forwardPE\")\n",
" peg_ratio = info.get(\"pegRatio\")\n",
" dividend_yield = info.get(\"dividendYield\") # fraction\n",
" roe = info.get(\"returnOnEquity\") # fraction\n",
" debt_to_equity = info.get(\"debtToEquity\") # percent\n",
" current_ratio = info.get(\"currentRatio\")\n",
" book_value = info.get(\"bookValue\") # per share\n",
" price_to_book = info.get(\"priceToBook\")\n",
" profit_margins = info.get(\"profitMargins\") # fraction\n",
"\n",
" # Conservative thresholds inspired by Graham (adjusted, simplified):\n",
" # - PE <= 15 (or <= 20 if growth) \n",
" # - PB <= 1.5 (or PE*PB <= 22.5) \n",
" # - Dividend present preferred \n",
" # - Current ratio >= 1.5 for industrials (approx) \n",
" # - D/E <= 1 (approx) \n",
" # - Stable profitability (we proxy using positive margin and ROE)\n",
"\n",
" pe_ok = trailing_pe is not None and trailing_pe <= 15\n",
" pb_ok = price_to_book is not None and price_to_book <= 1.5\n",
"\n",
" combo_ok = False\n",
" if (trailing_pe is not None) and (price_to_book is not None):\n",
" combo_ok = (trailing_pe * price_to_book) <= 22.5\n",
"\n",
" de_ok = (debt_to_equity is not None) and (debt_to_equity <= 100) # percent\n",
" cr_ok = (current_ratio is not None) and (current_ratio >= 1.5)\n",
" div_ok = (dividend_yield is not None) and (dividend_yield > 0)\n",
" profitability_ok = (\n",
" (profit_margins is not None and profit_margins > 0)\n",
" and (roe is not None and roe > 0)\n",
" )\n",
"\n",
" checks = {\n",
" \"price\": current_price,\n",
" \"trailing_pe\": trailing_pe,\n",
" \"price_to_book\": price_to_book,\n",
" \"pe_ok\": pe_ok,\n",
" \"pb_ok\": pb_ok,\n",
" \"pe_x_pb_ok\": combo_ok,\n",
" \"dividend_yield\": dividend_yield,\n",
" \"dividend_ok\": div_ok,\n",
" \"debt_to_equity_pct\": debt_to_equity,\n",
" \"debt_to_equity_ok\": de_ok,\n",
" \"current_ratio\": current_ratio,\n",
" \"current_ratio_ok\": cr_ok,\n",
" \"profit_margins\": profit_margins,\n",
" \"roe\": roe,\n",
" \"profitability_ok\": profitability_ok,\n",
" }\n",
"\n",
" total_pass = sum(\n",
" 1\n",
" for k in [\n",
" \"pe_ok\",\n",
" \"pb_ok\",\n",
" \"pe_x_pb_ok\",\n",
" \"dividend_ok\",\n",
" \"debt_to_equity_ok\",\n",
" \"current_ratio_ok\",\n",
" \"profitability_ok\",\n",
" ]\n",
" if checks[k]\n",
" )\n",
" checks[\"passes\"] = total_pass\n",
" checks[\"total_criteria\"] = 7\n",
" return checks\n",
"\n",
"\n",
"def format_checks_md(ticker: str, checks: dict) -> str:\n",
" yn = lambda b: \"✅\" if b else \"❌\"\n",
" lines = [f\"### Graham-style screen for `{ticker}`\"]\n",
" lines.append(\"- Price: \" + str(checks.get(\"price\")))\n",
" lines.append(\n",
" f\"- PE: {checks.get('trailing_pe')} | PB: {checks.get('price_to_book')} | PE×PB<=22.5: {yn(checks.get('pe_x_pb_ok'))}\"\n",
" )\n",
" lines.append(f\"- PE<=15: {yn(checks.get('pe_ok'))}\")\n",
" lines.append(f\"- PB<=1.5: {yn(checks.get('pb_ok'))}\")\n",
" lines.append(\n",
" f\"- Dividend yield: {checks.get('dividend_yield')} | Present: {yn(checks.get('dividend_ok'))}\"\n",
" )\n",
" lines.append(\n",
" f\"- D/E%: {checks.get('debt_to_equity_pct')} | <=100%: {yn(checks.get('debt_to_equity_ok'))}\"\n",
" )\n",
" lines.append(\n",
" f\"- Current ratio: {checks.get('current_ratio')} | >=1.5: {yn(checks.get('current_ratio_ok'))}\"\n",
" )\n",
" lines.append(\n",
" f\"- Profit margin: {checks.get('profit_margins')} | ROE: {checks.get('roe')} | Positive: {yn(checks.get('profitability_ok'))}\"\n",
" )\n",
" lines.append(\n",
" f\"- Score: {checks.get('passes')}/{checks.get('total_criteria')} criteria passed\"\n",
" )\n",
" return \"\\n\".join(lines)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7b1068f3",
"metadata": {},
"outputs": [],
"source": [
"# Run metrics and display\n",
"checks = compute_graham_checks(stock_symbol)\n",
"display(Markdown(format_checks_md(stock_symbol, checks)))\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e57d502a",
"metadata": {},
"outputs": [],
"source": [
"# LLM analysis using available provider(s)\n",
"\n",
"def analyze_with_llm(summary_markdown: str, provider: str = \"auto\",\n",
" openai_model: str = \"gpt-4o-mini\",\n",
" groq_model: str = \"llama-3.3-70b-versatile\") -> str:\n",
" sys_msg = (\n",
" \"You are a conservative value-investing analyst using Benjamin Graham principles. \"\n",
" \"Explain clearly which checks passed/failed, what that implies, and caveats about proxies. \"\n",
" \"Be concise and avoid recommendations; this is educational only.\"\n",
" )\n",
" user_msg = (\n",
" \"Analyze the following Graham-style checklist for a stock. \"\n",
" \"Summarize pass/fail, key drivers, and a short risk note.\\n\\n\" + summary_markdown\n",
" )\n",
"\n",
" def chat(client, model):\n",
" resp = client.chat.completions.create(\n",
" model=model,\n",
" messages=[\n",
" {\"role\": \"system\", \"content\": sys_msg},\n",
" {\"role\": \"user\", \"content\": user_msg},\n",
" ],\n",
" temperature=0.4,\n",
" max_tokens=400,\n",
" )\n",
" return resp.choices[0].message.content\n",
"\n",
" outputs = []\n",
" if provider in (\"auto\", \"openai\") and openai_client:\n",
" try:\n",
" outputs.append((\"OpenAI\", chat(openai_client, openai_model)))\n",
" except Exception as e:\n",
" outputs.append((\"OpenAI\", f\"Error: {e}\"))\n",
"\n",
" if provider in (\"auto\", \"groq\") and groq_client:\n",
" try:\n",
" outputs.append((\"Groq\", chat(groq_client, groq_model)))\n",
" except Exception as e:\n",
" outputs.append((\"Groq\", f\"Error: {e}\"))\n",
"\n",
" if not outputs:\n",
" return \"No LLM providers available. Set OPENAI_API_KEY and/or GROQ_API_KEY.\"\n",
"\n",
" merged = []\n",
" for name, out in outputs:\n",
" merged.append(f\"### {name} analysis\\n\\n\" + (out or \"\"))\n",
" return \"\\n\\n---\\n\\n\".join(merged)\n",
"\n",
"analysis = analyze_with_llm(format_checks_md(stock_symbol, checks))\n",
"display(Markdown(analysis))\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": ".venv",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.11"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|