Skill: daveanandraj/ai-stock-watchdog (version 2.2.0)

--- name: ai-stock-watchdog slug: ai-stock-watchdog displayName: AI stock watchdog description: "Daily monitoring for Indian equity holdings (NSE/BSE) using a documented severity rubric. Silent by default — only surfaces Sev-1 events (governance, cash flow, promoter/pledge, surveillance, earnings, flows). Includes quarterly checks, segment view for conglomerates, and guidance tracking." version: 2.2.0 type: skill license: MIT-0 author: daveanandraj homepage: https://github.com/daveanandraj/indian-stock-monitor-clawhub repository: https://github.com/daveanandraj/indian-stock-monitor-clawhub category: finance tags: - finance - investing - india - nse - bse - portfolio - alerts - earnings - monitoring - promoter-pledge - cash-flow invocation: triggers: - "check my stocks" - "stock morning brief" - "portfolio check" - "anything I should know about my holdings" - "I bought" - "I sold" - "add to portfolio" - "update my portfolio" - "trim" - "exit" - "set up stock monitor" - "scan my holdings" - "portfolio health check" - "how's my portfolio" fileTypes: - "image/png" - "image/jpeg" metadata: openclaw: requires: tools: - WebSearch - Read - Write - Edit - AskUserQuestion optional: - mcp__scheduled-tasks__create_scheduled_task env: [] binaries: [] dataFiles: - portfolio.json - competitors.json - severity-rubric.md - sources.md stateDir: state/ outputDir: alerts/ compatibility: platforms: - openclaw - claude-code - codex - copilot disclaimer: Informational only. NOT investment advice. The author is not a SEBI-registered investment advisor. Stock investments are subject to market risk. --- # AI stock watchdog v2 > Daily monitoring for NSE/BSE holdings against `severity-rubric.md`. **Silence by default** — notify only when a Sev-1 rule fires or the portfolio-health rules say so. Results depend on available sources and search quality; verify material facts yourself. ## Skill directory convention All data files live in the **same directory as this SKILL.md file**, referred to as `{SKILL_DIR}`. Resolve it to the actual absolute path at runtime. Files: - `{SKILL_DIR}/portfolio.json` — holdings, watchlist, preferences, holding periods - `{SKILL_DIR}/competitors.json` — sector peers + conglomerate segment mapping - `{SKILL_DIR}/severity-rubric.md` — Sev-1/2/3 classification rules - `{SKILL_DIR}/sources.md` — data sources with search query templates - `{SKILL_DIR}/state/last-run.json` — alerts sent, results calendar, management guidance tracker, suppression log - `{SKILL_DIR}/alerts/{YYYY-MM-DD}-*.md` — archived alerts - `{SKILL_DIR}/state/portfolio-backup-{TS}.json` — auto-backups --- # Routing — pick which workflow to run | User message contains... | Run | |---|---| | portfolio.json `_first_run: true`, OR "set up stock monitor" / "start monitoring" | **Onboarding Workflow** | | "I bought", "I sold", "add to portfolio", "trim", "exit", "update my portfolio", broker screenshot | **Portfolio Update Workflow** | | "check my stocks", "morning brief", "scan", "anything I should know", scheduled run | **Daily Monitoring Workflow** | | "portfolio health check", "how's my portfolio", "concentration risk" | **Portfolio Health Check** (then optionally Daily Monitoring) | | Ambiguous | Ask the user which they want | --- # Onboarding Workflow (first run) portfolio.json starts with `_first_run: true` and empty holdings. Detect on first invocation. NEVER skip — always offer setup. ## Onboard-1 — Greet & explain Greet warmly. Explain in plain language: 1. It watches your Indian stocks every weekday morning. 2. It ONLY pings you when something genuinely critical happens — promoter selling, governance failures, cash flow deterioration, surveillance moves, big earnings misses. 3. It does deep quarterly analysis: not just headline numbers, but cash flow quality, segment trends, and whether management delivered what they promised. 4. Most days you'll hear nothing — that's the design. ## Onboard-2 — Capture holdings Use AskUserQuestion (if available) OR ask in chat: > "How would you like to share your portfolio?" > 1. **Drop a screenshot** of my broker app (Zerodha, Groww, Upstox, Angel One, etc.) > 2. **Describe in text** (e.g., "50 shares of XYZ at avg 1500, 10 shares of ABC at 2900") > 3. **Skip for now** Follow Update Workflow (Update-2+) for processing. ## Onboard-3 — Capture preferences Ask: 1. **Investment horizon** → short-term (<3 months) / medium-term (3–12 months) / long-term (1+ year) 2. **Alert sensitivity** → critical only (recommended) / critical + high / daily digest 3. **Delivery** → notify only on critical (recommended) / daily one-liner / live dashboard 4. **Positive signals** → include good news in alerts? (yes / no — default no, silence-first) Save into `portfolio.json` → `preferences`. ## Onboard-4 — Set up the daily schedule Offer daily schedule for the Daily Monitoring Workflow every weekday at 8:30 AM IST. - **If [REDACTED_SECRET] is available**: use it with cron `30 8 * * 1-5`. This tool only creates a time-based cron trigger — no shell access. - **If unavailable**: tell the user to trigger manually ("check my stocks") or set their own reminder. ## Onboard-5 — Baseline scan Offer: "Want me to do a first-look scan now? I'll check the last 7 days of news, filings, promoter activity, and surveillance status for your holdings." If yes, run Daily Monitoring Workflow once. If no, confirm setup done. ## Onboard-6 — Mark complete Set `_first_run: false` in portfolio.json. Save. --- # Portfolio Update Workflow The user never edits portfolio.json. They describe changes or drop screenshots. ## Update-1 — Detect intent - **Buy**: "I bought 50 shares at 1620", "picked up XYZ today" - **Sell / Trim / Exit**: "sold all my XYZ", "trimmed 20 of ABC", "booked profit on PQR" - **Bulk update**: screenshot + "update my holdings" - **Watchlist**: "add XYZ to watchlist" - **Correction**: "my avg for XYZ is actually 1640" ## Update-2 — Gather information ### Screenshot path Read image using vision. Extract: ticker/company name, quantity, average buy price, broker. Common layouts: - **Zerodha Kite**: Instrument | Qty | Avg. cost | LTP | Cur. val | P&L - **Groww**: ticker, qty, "Avg. ₹X", "Invested ₹Y" - **Upstox / Angel One / ICICI Direct / Kotak Neo / other brokers**: similar tabular **CRUCIAL**: Before computing diff, ASK: *"Is this your complete portfolio, or just additions/changes?"* Default: layer onto existing. Never silently remove based on absence. If truncated (scroll indicator, "+N more"), ask to scroll and re-upload. ### Text path Parse natural language: - Resolve company name → NSE ticker. If ambiguous, ASK. Many Indian company names map to multiple tickers (e.g., a group name may have 5+ listed entities). Always confirm before assuming. - "all" / "exited" → full sell - "trimmed 20" → subtract from current - "I now hold 30" → set, don't add - Missing price on buy → ASK. Never fabricate. ### Sector & segment inference (when adding a new ticker) 1. Look up `competitors.json` → `ticker_to_sector`. If found, use it. 2. If not found, check `sector_peers`. 3. If still not found, web search "{TICKER} NSE sector industry". 4. For conglomerates (check `conglomerate_segments` key in competitors.json), also note the segment mapping for the ticker if it exists. 5. ADD the mapping to `competitors.json`. Never leave sector blank. ### Record holding start date When adding a new stock, record `buy_date: "{YYYY-MM-DD}"` in portfolio.json. This is used for: - STCG vs LTCG awareness (365-day boundary for equity) - Holding period context in alerts ## Update-3 — Read current portfolio Read `{SKILL_DIR}/portfolio.json`. Compute proposed new state. ## Update-4 — Show diff & confirm (mandatory) NEVER write without explicit confirmation: ``` Proposed portfolio update: ✱ ADD {TICKER_A} qty: 10 avg: ₹2,900 sector: {sector} ✏ UPDATE {TICKER_B} qty: 50→75 avg: ₹1,620→₹1,607 (weighted) ✗ REMOVE {TICKER_C} (full exit) Concentration check: {TICKER_A} would be 28% of portfolio — within limits. Summary: +1 new, 1 increased, 1 exit. Net 2 holdings. Apply? (yes / no / edit) ``` Wait for explicit confirmation. ## Update-5 — Backup, then write 1. Copy current portfolio.json to `{SKILL_DIR}/state/portfolio-backup-{YYYY-MM-DD-HHMMSS}.json` 2. Write new portfolio.json preserving structure 3. Update `competitors.json` → `ticker_to_sector` for new tickers 4. Confirm: "Portfolio updated. {N} holdings, {M} on watchlist. Backup saved." ## Update-6 — Weighted average (adding to existing) ``` new_avg = ((old_qty × old_avg) + (new_qty × new_price)) / (old_qty + new_qty) ``` Show the calculation. If user states explicit avg, use theirs. ## Update-7 — Edge cases - **Sell to zero**: REMOVE entirely. - **Sell more than held**: STOP, ask. - **Sell stock not in portfolio**: STOP, ask. - **Stock split / bonus**: adjust qty × ratio, avg ÷ ratio. CONFIRM. - **Renamed/merged tickers**: confirm with user. - **F&O / MF / ETF**: not supported — tell user. - **Buy without price**: ASK. ## Update-8 — Post-update offer - New holding → "Want a quick first-look scan of {TICKER}?" - New sector → "Added {sector} peers to monitoring." - Full exit → confirm only. If held >1 year: "Note: this was a long-term holding — gains qualify for LTCG (10% above ₹1.25 lakh)." --- # Portfolio Health Check Run this before daily monitoring OR when user asks "how's my portfolio" / "portfolio health check". This catches structural risks the daily scan doesn't. ## Health-1 — Concentration risk - Any single stock >30% of invested value → FLAG as concentration risk - Any single sector >40% of invested value → FLAG as sector overweight - Report: "Your portfolio has {N} holdings across {M} sectors. Largest position: {TICKER} at {X}% of invested value." ## Health-2 — Correlation check - If 3+ holdings in same sector, note: "You have high {sector} correlation. A sector-wide event would hit {X}% of your portfolio." - If 2+ holdings in same promoter group (Tata group, Adani group), note the group concentration. ## Health-3 — Liquidity check - If any held stock has average daily volume <₹5 crore, flag: "Exit may be difficult for {TICKER} — average daily volume is only ₹{X} crore." ## Health-4 — Holding period tracker - For each stock, compute days held since `buy_date`. - Flag stocks approaching LTCG boundary (between 300–365 days): "Note: {TICKER} held for {N} days. LTCG threshold in {365-N} days — trimming before would mean STCG (20%)." - Stocks held >365 days: note "LTCG eligible" in any exit recommendations. ## Health-5 — Unrealized P&L awareness If current price data is available from scan: - Flag stocks with >30% unrealized loss held >180 days: "You're sitting on a {X}% unrealized loss on {TICKER} for {N} days. This may be anchoring bias." - Flag stocks with >50% unrealized gain: "Consider whether {TICKER}'s position size (now {X}% of portfolio due to appreciation) warrants a trim." --- # Daily Monitoring Workflow You apply this skill's rubric to Indian equities. Job: **silence by default**. Only surface when a Sev-1 trigger matches `severity-rubric.md` (plus the notify rules below). False positives erode trust faster than missed noise. ## Step 1 — Setup & portfolio health - Read `{SKILL_DIR}/portfolio.json`. If `_first_run: true` OR holdings empty → route to Onboarding. - Pull every ticker in `holdings`. - Look up each ticker's sector and segment mapping in `competitors.json`. Build peer set. - Read `{SKILL_DIR}/state/last-run.json` for alert history and management guidance tracker. - Note today's date in IST. - Run Portfolio Health Check (Health-1 through Health-3 only — skip Health-4/5 in automated mode unless concentration risk found). ## Step 2 — India market calendar check Before stock-level scanning, check: ### 2a. Is today a market holiday? If NSE is closed today (Republic Day, Holi, Diwali, etc.), skip the scan. Update state with "market_holiday" and exit. ### 2b. Macro events today/this week Quick search for: - RBI MPC decision (if this is an MPC week) → impacts all bank/NBFC holdings - Union Budget (if Feb 1 window) → impacts everything - GST Council meeting → impacts FMCG, cement, auto - F&O monthly expiry (last Thursday) → note elevated volatility context ### 2c. Pre-market global cues Search: US close (Dow/Nasdaq/S&P), GIFT Nifty, Brent crude, USD/INR, US 10Y yield, India VIX. Only flag if global shock directly maps to a holding: - Crude up >5% with oil & gas / refining stocks held → flag (for diversified refiners, note that GRM benefits while petchem margins may compress) - USD/INR sharp move (>1%) with IT / pharma export stocks → flag tailwind/headwind - US 10Y yield spike >20bps → FII outflow risk, flag for all holdings ## Step 3 — Per-stock daily scan For each held ticker, run in parallel: ### 3a. Exchange announcements (last 24h) Search: `site:nseindia.com "{COMPANY_NAME}" announcement`, `site:bseindia.com "{COMPANY_NAME}"`. Look for: results dates, board meetings, auditor changes, KMP exits, credit rating actions, pledge disclosures, SAST/PIT filings, corporate governance reports, scheme of arrangement. ### 3b. News scan (last 24h) - `"{COMPANY_NAME}" news` last 1 day — prefer Moneycontrol / ET / Reuters / Mint / Business Standard - `"{COMPANY_NAME}" SEBI` last 7 days - `"{COMPANY_NAME}" ED CBI "income tax" raid` last 30 days (only if NEW) - `"{COMPANY_NAME}" downgrade` last 7 days - `"{COMPANY_NAME}" fraud whistleblower "forensic audit"` last 90 days (only if NEW) ### 3c. Promoter & institutional activity **Promoter holding & pledge (check against latest quarterly shareholding pattern):** - Search: `"{COMPANY_NAME}" promoter holding` or `"{TICKER}" shareholding pattern` - Compare with previous quarter stored in state. Flag per severity-rubric.md Section A. - If near a quarterly filing deadline (21 days post quarter-end), actively look for fresh filing. **Insider trading disclosures (last 7 days):** - Search: `"{TICKER}" insider trading SAST PIT disclosure site:nseindia.com` - Flag KMP sales, especially pre-results. **Block/bulk deals (last 24h):** - Search: `"{TICKER}" block deal bulk deal` - Decode: is the seller a promoter entity, FII, PE fund, or retail? Promoter selling = Sev-1. **FII/MF holding changes (when quarterly data available):** - Compare latest quarter vs previous from Trendlyne or Screener. - FII cut >2pp = Sev-1. MF net selling >0.5% = Sev-2. ### 3d. Surveillance & price action - GSM/ASM status: search `"{TICKER}" GSM ASM surveillance`. Cache 7 days. - F&O ban list (if near expiry week): check NSE F&O ban page. - 52-week low yesterday? Flag if on >2x average volume. - Volume vs 20-day average — flag if >3x with negative move. ### 3e. Sector & peer activity (per unique sector, last 24h) For each sector: - Did any peer announce results, guidance, or material news? - Did a sector regulator issue anything? (RBI for banks, USFDA for pharma, TRAI for telecom, PNGRB for gas) - Cross-map peer concerns: 2+ peer Sev-1 in 7 days = industry stress trigger. ### 3f. Upcoming results check - Has the company announced next results date? Track in `state/last-run.json → results_calendar`. - If results declared in last 24h → trigger Quarterly Deep-Dive (Step 5). - If results due within 7 days → note "results watch" (no alert, but heightened sensitivity). ### 3g. Conglomerate segment check (for multi-business companies) If the ticker is flagged as a conglomerate in `competitors.json → conglomerate_segments`: - Look up the segment definitions and `key_metrics` for each segment in the data file. - Search for segment-specific news using those key metrics (e.g., refining margins for O2C segments, subscriber data for telecom segments, store count for retail segments). - A segment turning loss-making or cross-subsidy pattern = Sev-1. ## Step 4 — Severity classification Classify each signal against `severity-rubric.md`. Apply context modifiers: - Peer-relative adjustment (sector-wide fall reduces individual severity) - Horizon adjustment (short-term → elevate price triggers; long-term → demote price, elevate fundamental) - Position size adjustment (>25% of portfolio → elevate Sev-2 to Sev-1) - Market regime adjustment (broad correction → raise price thresholds) **Suppression rule**: If already alerted on same `signal_id` in last 14 days, suppress. ## Step 5 — Quarterly Deep-Dive (when results are out) Quarterly deep-dive should cover cash flow quality and segment trends, not only headline PAT and EPS vs consensus. ### 5a. Headline numbers Pull from BSE/NSE filing, Screener, or Trendlyne: - Revenue: YoY %, QoQ % - EBITDA: absolute, margin (bps change QoQ and YoY) - PAT: YoY %, QoQ % - EPS vs consensus ### 5b. Cash flow quality check (most underrated — catches manipulation) Pull cash flow statement (Screener cash flow tab or filing): - **CFO vs PAT**: compute CFO/PAT ratio. Below 0.5x for 2+ quarters = Sev-1. - **CFO trend**: is CFO growing in line with PAT? If PAT up 20% but CFO flat = red flag. - **Free cash flow**: CFO minus capex. Negative FCF for 3+ quarters in a non-capex-cycle company = Sev-2. - **Working capital changes**: large working capital build draining CFO = Sev-1 if receivables/inventory growing >2x revenue. ### 5c. Balance sheet quality - **Net debt**: QoQ change. Debt increasing while profits grow = fund-flow mismatch. - **Debt maturity**: >30% maturing within 12 months with weak CFO = refinancing risk. - **Interest coverage**: EBITDA/interest expense. Below 1.5x = Sev-1. - **Contingent liabilities**: compare vs previous year. Sharp jump = potential hidden risk. - **Related party transactions**: jumped >50% YoY without proportionate revenue = Sev-1. - **Trade receivables**: absolute growth and days outstanding. Over 90 days = collection risk. - **Inventory days**: rising faster than revenue = demand slowdown or channel stuffing. ### 5d. Segment-wise analysis (critical for conglomerates) For companies with multiple reported segments (refer to `conglomerate_segments` in competitors.json for segment definitions): - Revenue and EBIT per segment vs previous quarter and same quarter last year. - Any segment turned EBIT-negative? → Sev-1. - Cross-subsidization pattern: profitable segment margin declining while loss-making segment scales → flag. - Use `key_metrics` from the conglomerate_segments data to know which numbers to pull for each segment. ### 5e. Vs consensus Pull consensus from Trendlyne or Moneycontrol: - Revenue miss >15% = Sev-1. Miss 10–15% = Sev-2. - PAT miss >25% = Sev-1. Miss 15–25% = Sev-2. - Margin miss >200 bps = Sev-2. Miss >400 bps = Sev-1. ### 5f. Concall analysis Locate transcript (Screener Documents tab or company IR): 1. **Guidance tracking**: what did management guide last quarter? Extract specific numbers (revenue growth %, margin target, capex plan, order book target). Compare with actuals. If missed >30% of guided number → management credibility drops. Record in `state/last-run.json → guidance_tracker`. 2. **Forward guidance**: extract new guidance numbers. Store for next quarter comparison. 3. **Tone analysis**: compare language with previous 2 concalls. "Confident/strong" → "cautious/watchful" = Sev-2 (Sev-1 if combined with earnings miss). 4. **Specific red flag phrases**: "challenging environment", "one-off", "non-recurring" (used 2+ quarters = it's recurring), "right-sizing", "restructuring charges", "deferred revenue recognition". 5. **Analyst pushback**: if multiple analysts question the same metric (receivables, related party, cash flow) — that's smart money flagging something. 6. **Duration/access**: significantly shorter concall or fewer questions taken = management avoiding scrutiny. ### 5g. Banking-specific quarterly checks (for bank / NBFC holdings) - **NIM (Net Interest Margin)**: QoQ bps change. Compression >10 bps = note. >20 bps = Sev-2. - **CASA ratio**: declining = higher cost of funds ahead. - **GNPA / NNPA**: absolute and ratio. Any uptick = note. Sharp uptick from a low base = Sev-2. - **Slippage ratio**: fresh slippages as % of opening standard advances. Rising = Sev-2. - **Credit cost**: provisions as % of average advances. - **CD ratio (Credit-Deposit)**: above 80% = aggressive lending. Above 85% = risk flag. - **PCR (Provision Coverage Ratio)**: declining = less buffer for future shocks. - If the bank has undergone a recent merger, also track: merged book integration, loan-to-deposit ratio normalization, PSL compliance, and synergy realization. ### 5h. Build verdict - **One-line verdict**: ACCUMULATE / HOLD / WATCH / EXIT BIAS - **Why** (3 bullets max) - **Counter-view** (1 bullet — always include) - **Action**: specific for this week, based on user's horizon - **Management credibility**: HIGH / MEDIUM / LOW (based on guidance delivery history) ## Step 6 — Quarterly for peers Same as Step 5 but summarized: one paragraph per peer (QoQ delta + concall tone). Sector-level read: "Industry trend: {strong / mixed / weak / deteriorating}." Surface ONLY if it changes the read on a held stock. ## Step 7 — Decide whether to notify Notify only if: 1. ≥1 Sev-1 trigger on a held stock not flagged in last 14 days, OR 2. ≥2 Sev-1 triggers across peers in same sector within 7 days (industry stress), OR 3. Quarterly deep-dive concluded EXIT BIAS or WATCH, OR 4. Portfolio health found >30% concentration in a stock with any Sev-2+ signal. Otherwise — update state and exit silently. EXCEPTION: if `delivery` = `daily_brief`, always post a one-liner: "All clear — no Sev-1 across {N} holdings as of {time}." ## Step 8 — Notification format Save to `{SKILL_DIR}/alerts/{YYYY-MM-DD}-alert.md` AND surface in chat: ``` 🔴 STOCK ALERT — {date} {TICKER} — {one-line headline} Severity: Sev-1 | Category: {rubric section} | Sector: {sector} What happened: {2-3 lines, factual, with specific numbers} Why it matters for YOU ({horizon} holder, avg ₹{avg_price}, {N} shares): - {bullet 1 — direct portfolio impact} - {bullet 2 — what this historically leads to} Suggested action: {Hold / Watch closely / Trim / Exit bias} Confidence: {High / Medium / Low} Management credibility: {High / Medium / Low} (based on {N} quarters tracked) Sources: - [Title](URL) - [Title](URL) Counter-view: {one line — what could make this NOT critical} Portfolio impact: This holding is {X}% of your portfolio. {If concentrated: "Given your concentrated position, consider this signal with extra weight."} ``` If multiple stocks triggered, repeat per ticker. Group by severity. ## Step 9 — State update Update `{SKILL_DIR}/state/last-run.json`: - `last_run_date`: today's date - `alerts_sent`: append any new alerts with signal_id and timestamp - `results_calendar`: update upcoming/past results dates - `guidance_tracker`: store management guidance numbers for forward comparison - `promoter_holding_history`: store latest promoter holding % and pledge % per ticker - `institutional_holding_history`: FII %, DII %, MF holding % per ticker - `management_credibility`: running score per company based on guidance vs actual - `surveillance_check`: last checked date, any active GSM/ASM entries --- # Hard rules 1. NEVER provide buy/sell as financial advice. Frame as "based on rubric, signal suggests…" Remind: informational only, not SEBI-registered. 2. NEVER hallucinate. If can't verify via a source, say "could not verify — check directly." 3. ALWAYS cite sources at the bottom of any alert with markdown links. 4. NEVER repeat an alert already sent in last 14 days for the same signal_id. 5. Default to silence. Most days have nothing to say. 6. NEVER write portfolio.json without showing diff and getting explicit confirmation. 7. ALWAYS back up portfolio.json before writing. 8. If `_first_run: true` or holdings empty → route to Onboarding. 9. Indian markets only — NSE & BSE. All times in IST. 10. For short-term holders: elevate block deals, volume anomalies, 52W low, F&O ban signals. 11. For long-term holders: elevate cash flow quality, governance, promoter pledge, management credibility signals. Demote single-day price moves. 12. NEVER ignore cash flow quality. A company reporting growing profits with declining/negative operating cash flow is the single most common pattern before Indian accounting frauds. 13. For conglomerates: always do segment-level analysis. Consolidated numbers can hide a dying segment behind a thriving one. 14. Track management guidance and hold them accountable. Two consecutive quarters of missing own guidance = downgrade credibility rating. # Manual invocation User can trigger ad-hoc: - "Check my stocks" - "Stock morning brief" - "Run portfolio scan" - "Portfolio health check" - "How's my portfolio" - "Anything I should know about my holdings?" In ad-hoc mode, run same workflow but if nothing critical, give a one-liner: "All clear — no Sev-1 triggers across {N} holdings as of {time}." rather than total silence.

path: CHANGELOG.md
content: # Changelog

All notable changes to this skill are documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this skill adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [2.2.0] — 2026-05-04

### Changed
- Display name updated to **AI stock watchdog** on ClawHub listing (slug remains `indian-stock-monitor`)
- All user-facing references (README, SKILL.md heading, severity-rubric, sources, LICENSE, data file comments) updated to "AI stock watchdog"
- Removed mistakenly created separate `ai-stock-watchdog` skill from ClawHub

## [2.1.1] — 2026-05-03

### Changed
- Toned down marketing language in SKILL.md, README.md, manifest.json, and severity-rubric.md (removed unverifiable claims; descriptions now state what the skill does and its limits)
- Rubric philosophy and section headers no longer imply guaranteed predictive power
- `sources.md`: removed named-company callouts in section titles (kept topic-based headings)

## [2.1.0] — 2026-05-03

### Changed
- Removed all agent-specific references — skill is now fully agent-agnostic (works with OpenClaw, Claude Code, Codex, Copilot)
- Removed hardcoded stock names from methodology — SKILL.md uses generic placeholders; specific stocks are reference data in competitors.json only
- Updated install instructions to follow ClawHub conventions (`openclaw skills install`)
- Compatibility section now lists platforms generically instead of version-pinning to a specific LLM
- Examples use "Agent" instead of model-specific names
- Emptied ticker_to_sector for clean first-run state

## [2.0.0] — 2026-05-03

### Added — Methodology overhaul based on 20-year Indian market advisor perspective

**Promoter & insider monitoring (new — highest-impact addition):**
- Full QoQ promoter holding tracking against quarterly shareholding patterns
- Promoter pledge escalation detection with tiered thresholds (5pp jump, 50% crossed, 75% margin-call territory)
- Encumbrance (pledge + non-disposal undertaking) combined tracking
- Insider trading (SAST/PIT) disclosure monitoring for KMP pre-results selling
- Lender pledge invocation detection

**Cash flow quality analysis (new — catches manipulation):**
- CFO vs PAT ratio tracking over quarters (below 0.5x for 2+ quarters = Sev-1)
- CFO trend divergence from PAT trend (growing profits with flat/declining cash flow)
- Trade receivable / inventory growth vs revenue divergence
- Working capital cycle deterioration detection
- Tax rate anomaly detection

**Conglomerate segment analysis (new — critical for Reliance, L&T, ITC):**
- Segment-level revenue and EBIT tracking per quarter
- Cross-subsidization pattern detection (profitable segment funding loss-making)
- Full segment mapping for Reliance (O2C, Jio, Retail, E&P, New Energy), HDFC Bank (Retail, Wholesale, Treasury), L&T, and ITC
- Segment-specific peer comparison and regulatory watch
- Sum-of-parts awareness

**Management credibility tracking (new):**
- Guidance extraction from concalls — store specific numbers
- Forward comparison: did management deliver what they promised?
- Credibility score (HIGH/MEDIUM/LOW) based on guidance delivery over quarters
- Two consecutive misses = automatic credibility downgrade

**Portfolio health check (new):**
- Concentration risk detection (>30% single stock, >40% single sector)
- Sector correlation warnings (3+ stocks in same sector)
- Promoter group concentration check
- Liquidity risk flagging (low-volume stocks)
- STCG vs LTCG holding period tracking (365-day boundary)
- Unrealized P&L awareness (anchor bias detection)

**India market calendar awareness (new):**
- RBI MPC week detection
- Union Budget window
- GST Council meeting
- F&O monthly/quarterly expiry volatility context
- Result season windows
- Market holiday detection

**Positive signal tracking (new — opt-in):**
- Promoter open market buying (strong conviction signal)
- Buyback announcements
- Credit rating upgrades
- GSM/ASM exit
- Major contract wins
- Institutional (PE/sovereign fund) stake pickup

**Banking-specific quarterly analysis (new — for HDFC Bank, ICICI, etc.):**
- NIM tracking (QoQ bps change)
- CASA ratio trend
- GNPA/NNPA and slippage ratio
- Credit cost
- CD ratio (Credit-Deposit) with risk thresholds
- Provision coverage ratio (PCR) trend
- Post-merger integration metrics for HDFC Bank

### Changed
- Severity rubric expanded from 4 sections to 10, with context modifiers (peer-relative, horizon-adjusted, position-size-weighted, market-regime-aware)
- Quarterly deep-dive now covers cash flow statement, balance sheet quality, segment analysis, related party transactions, contingent liabilities, auditor emphasis of matter — not just P&L headline numbers
- Sources expanded with SEBI adjudication, shareholding pattern filings, sector-specific data sources, India market calendar links, and copy-paste search query templates
- Competitors.json restructured with conglomerate segment mapping, sector regulator mapping, and expanded peer lists
- All examples rewritten with realistic Reliance + HDFC Bank scenarios
- Notification format now includes management credibility score, portfolio concentration context, and holding-period-specific impact

### Security
- Removed `mcp__workspace__bash` from all tool references (v1.0.1 change carried forward)
- `mcp__scheduled-tasks__create_scheduled_task` remains optional-only

## [1.0.1] — 2026-05-03

### Security
- Removed `mcp__workspace__bash` (unused, flagged in OpenClaw review)
- Moved scheduled-tasks to optional with graceful fallback

## [1.0.0] — 2026-05-01

### Added
- Initial release
- Daily monitoring workflow for NSE/BSE
- Conversational portfolio management (text + screenshot)
- First-run onboarding
- Severity rubric (Sev-1/2/3)
- Quarterly workflow with QoQ/YoY comparison
- Sector peer monitoring
- Auto-backup of portfolio.json
- Alert suppression (14-day window)
- Support for 7+ broker screenshot formats
- 30+ sector peer mappings

### Out of scope (deliberately)
- F&O / derivatives
- Mutual funds / ETFs
- US/global stocks
- Trade execution

## Roadmap (planned)

### [2.1.0] — possible additions
- Beneish M-Score (earnings manipulation probability scoring)
- Piotroski F-Score tracking over quarters
- Trendlyne / Screener API integration (if APIs become available)
- Telegram / WhatsApp notification adapters
- Interactive HTML dashboard artifact
- Concall transcript caching for faster repeat comparisons

### [2.2.0] — under consideration
- Multi-portfolio support (separate "core" and "tactical" books)
- Tax-optimized trim suggestions (STCG vs LTCG aware rebalancing)
- Indexed peer-relative valuation (P/E, P/B, EV/EBITDA vs sector median)
- Custom severity rubric weights per user


path: PUBLISH.md
content: # Publishing to ClawHub — Step-by-step

> **Important context:** This guide is assembled from web-search summaries of ClawHub's documentation, not from direct firsthand verification. Before submitting, run through the **verification checklist at the bottom** against the live official docs (https://github.com/openclaw/clawhub and https://docs.openclaw.ai). The format may have changed since this skill was written.

## Prerequisites

| Requirement | Status |
|---|---|
| GitHub account at least one week old | You handle this |
| ClawHub CLI installed | `npm install -g @openclaw/clawhub-cli` (verify package name in current docs) |
| Logged in to ClawHub via CLI | `clawhub login` (uses GitHub OAuth) |
| Skill folder ready | ✓ This folder |

## Step 1 — Verify CLI version and login

```bash
cd "indian-stock-monitor-clawhub"

# Confirm CLI is installed and check version
clawhub --cli-version

# See full command list (useful reference)
clawhub --help

# Log in if you haven't already (opens browser for GitHub OAuth)
clawhub login
clawhub whoami
```

Note: as of CLI v0.8.0 there is no separate `validate` subcommand — validation runs at publish time. To preview what `publish` accepts:

```bash
clawhub publish --help
```

Common things ClawHub will check at publish time:
- `name` must be lowercase-kebab-case
- `version` must be valid semver
- `category` must be one of ClawHub's known categories
- `license` must be in their allowlist

## Step 2 — Update author and repository fields

Open `SKILL.md` and replace the placeholders in the YAML frontmatter:

```yaml
author: your-name-here          # → your GitHub handle or display name
homepage: https://github.com/your-org/indian-stock-monitor   # → your actual repo
repository: https://github.com/your-org/indian-stock-monitor # → your actual repo
```

Do the same in `manifest.json` (`author`, `homepage`, `repository`).

## Step 3 — Push to GitHub (if not already)

ClawHub typically requires a public GitHub repo to publish from:

```bash
cd "indian-stock-monitor-clawhub"
git init
git add .
git commit -m "Initial release v1.0.0"
git branch -M main
git remote add origin https://github.com/your-org/indian-stock-monitor.git
git push -u origin main
```

Tag the release:

```bash
git tag v1.0.0
git push origin v1.0.0
```

## Step 4 — Publish to ClawHub

CLI v0.8.0 takes a single positional path argument plus required flags. **Note**: even though `SKILL.md` has `version: 1.0.0` in its frontmatter, CLI v0.8.0 still requires `--version` as an explicit flag.

**Listing title on clawhub.ai:** The CLI sets the skill card title from **`--name`**, or else from **`TitleCase(folder basename)`**. It does **not** read `displayName` from `SKILL.md`. This repo folder is `indian-stock-monitor-clawhub`, so omitting `--name` produces the wrong title (“Indian Stock Monitor Clawhub”). Always pass:

`--name "AI stock watchdog"`

```bash
cd "indian-stock-monitor-clawhub"
clawhub publish "$(pwd)" \
  --slug ai-stock-watchdog \
  --name "AI stock watchdog" \
  --version 2.2.0
```

Use `$(pwd)` (absolute path) if `clawhub publish .` fails with “SKILL.md required” (known quirk with `.` in some setups).

To see all flags upfront before publishing:
```bash
clawhub publish --help
```

If `clawhub publish --help` lists optional flags you want to set, the typical pattern is:

```bash
clawhub publish . \
  --tags latest \
  --changelog "Initial release: daily NSE/BSE watchdog with conversational portfolio management"
```

(There is **no** `clawhub skill publish` or `clawhub package publish` in v0.8.0 — both were wrong in earlier drafts of this doc.)

### Bulk / sync alternative
If you have multiple skills in your workdir and want ClawHub to find new/updated ones automatically:

```bash
clawhub sync --dry-run    # preview
clawhub sync              # publish all changed skills
```

## Step 5 — Verify the listing

After publish completes, ClawHub will show a URL like `https://clawhub.ai/your-username/ai-stock-watchdog`. Visit it and check:
- Description renders correctly
- README is shown
- Examples are visible
- Install command is shown
- Tags and category are correct

## Step 6 — Anyone can now install

```bash
clawhub install your-username/ai-stock-watchdog
```

…which installs into their `./skills/` directory.

---

# Verification Checklist (read before submitting)

Run through these against the **live official ClawHub docs** before publishing. The format below is my best-effort reconstruction from web search — the live spec is authoritative.

## Frontmatter fields — verify these are real and correctly named
- [ ] `name` — required, kebab-case
- [ ] `slug` — required, kebab-case (verify if `slug` is the real field name vs `id`)
- [ ] `displayName` — verify field name (might be `display_name` or `title`)
- [ ] `description` — required
- [ ] `version` — required, semver
- [ ] `type: skill` — verify "skill" is a valid value (vs "agent", "plugin")
- [ ] `license: MIT-0` — verify accepted license values
- [ ] `category: finance` — verify "finance" is a valid category (vs "personal-finance", "investing", etc.)
- [ ] `tags` — verify array vs comma-string format
- [ ] `invocation.triggers` — verify this is the correct field name and structure
- [ ] `metadata.openclaw.requires.tools` — verify this nested structure is correct
- [ ] `compatibility.platforms` — verify platform names are valid
- [ ] `compatibility.platforms` — verify platform names

## Required files
- [ ] `SKILL.md` ✓
- [ ] `README.md` ✓
- [ ] `LICENSE` ✓ (MIT-0)
- [ ] `examples/` ✓ (3 examples included)
- [ ] `CHANGELOG.md` ✓
- [ ] `manifest.json` — verify if ClawHub uses this OR derives everything from SKILL.md frontmatter

## Optional but recommended
- [ ] Screenshots / demo GIF in README
- [ ] Test fixtures (verify if ClawHub has a test convention)
- [ ] Quality check: README explains what it does, who it's for, install steps

## File extension allowlist
ClawHub publishes only "text-based" files (per a `textFiles.ts` allowlist). Files in this skill:
- [x] `.md` — text
- [x] `.json` — text
- [x] `LICENSE` (no ext) — verify if accepted

## Security & quality
- [ ] No personal data in repo (verified — empty portfolio, empty ticker_to_sector)
- [ ] All external API calls clearly described in SKILL.md (web search only — no hardcoded API keys)
- [ ] No bundled binaries
- [ ] No network endpoints owned by you that could go down

## Things ClawHub may reject for that I'm not 100% certain about
- The skill uses [REDACTED_SECRET] (declared as optional). ClawHub may reject skills that require host-specific MCP tools. The `mcp__workspace__bash` tool was removed in v1.0.1.
- The "{SKILL_DIR}" path convention I used in SKILL.md is a workaround for path portability. ClawHub may have a different convention (e.g., `${SKILL_PATH}` or relative paths).
- Examples are included as `.md` walkthroughs. ClawHub may prefer an `examples.json` schema.

**If validation fails for any of the above, the fix is usually a small frontmatter rename — not a structural change to the skill itself.**

---

# Security note

In late January 2026, ClawHub had to remove ~2,400 typosquatted skills that were distributing malware. The registry has since added VirusTotal scanning. Two implications:

1. **Be careful what you publish under your name** — your reputation is on the line.
2. **Use a clearly distinctive slug** — `ai-stock-watchdog` is fine; avoid anything that could be confused with another popular skill.
3. **Sign your commits and use 2FA on GitHub** — ClawHub's review checks GitHub account integrity.

---

# Where to verify everything in this guide

Authoritative sources:
- ClawHub repo: https://github.com/openclaw/clawhub
- Skill format spec: https://github.com/openclaw/clawhub/blob/main/docs/skill-format.md
- CLI reference: https://github.com/openclaw/clawhub/blob/main/docs/cli.md
- OpenClaw skills guide: https://docs.openclaw.ai/tools/skills
- ClawHub web: https://clawhub.ai

If any field name in this skill's `SKILL.md` frontmatter doesn't match what you find in those docs, rename in `SKILL.md` and re-run `clawhub skill validate .`.


path: README.md
content: # AI stock watchdog

A daily watchdog for your Indian equity holdings (NSE/BSE). Optional scheduled run; you can also trigger scans manually. Stays silent unless a **Sev-1** rule in `severity-rubric.md` fires.

> The rubric weights governance, promoter/pledge and insider activity, cash flow quality, earnings vs consensus, surveillance, and sector regulation. It is **not** investment advice — always verify from primary sources.

## What makes v2 different

v1 focused on news and filings. v2 adds structured checks (see table):

| Capability | v1 | v2 |
|---|---|---|
| Promoter holding & pledge tracking | Basic pledge check | Full QoQ comparison, encumbrance tracking, insider selling detection, pledge liquidation alerts |
| Cash flow quality analysis | Not present | CFO/PAT ratio tracking, working capital cycle, receivable/inventory divergence — catches window dressing |
| Segment-level analysis | Not present | Conglomerate drill-down with per-segment peers and key metrics |
| Management credibility | Not tracked | Guidance vs delivery scoring over quarters |
| Portfolio health | Not present | Concentration risk, sector correlation, STCG/LTCG awareness, anchor bias detection |
| India market calendar | Not present | RBI MPC, Budget, F&O expiry, result season awareness |
| Positive signals | Not present | Promoter buying, buybacks, credit upgrades, contract wins |
| Banking-specific metrics | Basic | NIM, CASA, GNPA/NNPA, slippage ratio, credit cost, CD ratio, PCR |
| Severity context | Static | Peer-relative, horizon-adjusted, position-size-weighted, market-regime-aware |

## What it watches for

The skill classifies every signal against a severity rubric and only surfaces **Sev-1 critical** events:

| Category | Examples |
|---|---|
| **Promoter signals** | Holding decline >2pp QoQ, pledge >50%, open market sale by promoter, KMP insider selling pre-results |
| **Governance shocks** | Auditor resignation/qualification, SEBI/ED/CBI action, forensic audit, CEO/CFO exit, related party transaction spike |
| **Cash flow manipulation** | CFO negative while PAT positive, CFO/PAT <0.5x for 2+ quarters, receivables growing 2x revenue |
| **Capital structure stress** | Credit downgrade ≥2 notches, interest coverage <1.5x, debt maturity wall, pledge invocation |
| **Earnings shock** | Revenue/PAT >20–25% below consensus, EBITDA margin compression >300bps, guidance cut >15% |
| **Concall red flags** | Demand weakness, capex cut, declining order book, tone shift + missed guidance |
| **Surveillance flags** | GSM Stage 2+, ASM Long-term, T2T, trading suspension |
| **Sector regulation** | RBI PCA, USFDA Warning Letter, govt ban/duty change, TRAI tariff order |
| **Short-term triggers** | Promoter block deal ≥1% equity, 7%+ single-day fall on 3x volume, 52W low on heavy volume |
| **Conglomerate segment** | Segment EBIT turned negative, cross-subsidization pattern, subsidiary IPO cancelled |

Full rubric: see `severity-rubric.md`.

## How you use it

Everything is conversational. You never edit any JSON.

### First time
Say *"set up stock monitor"* and the skill walks you through:
1. Share your holdings (screenshot or text)
2. Investment horizon (short / medium / long term)
3. Alert sensitivity (critical-only recommended)
4. Optional daily scheduled scan

### Ongoing
- **Update holdings**: *"I bought 10 shares of XYZ at 1265"*, *"sold all my ABC"*, *"trimmed 20 of PQR"*, or drop a broker screenshot
- **Manual scan**: *"check my stocks"*, *"morning brief"*, *"anything I should know?"*
- **Portfolio health**: *"portfolio health check"*, *"how's my portfolio"*

### Alert format
On a Sev-1 hit:

```
🔴 STOCK ALERT — {date}

{TICKER} — {one-line headline}
Severity: Sev-1 | Category: {category} | Sector: {sector}

What happened: [factual, with specific numbers]

Why it matters for YOU ({horizon} holder, avg ₹{price}, {N} shares — {X}% of portfolio):
- [portfolio-specific impact]
- [historical pattern context]

Suggested action: WATCH CLOSELY
Confidence: Medium-High
Management credibility: MEDIUM (missed guidance)

Sources:
- [Title](URL)

Counter-view: [what could make this NOT critical]

Portfolio impact: {X}% of your capital.
```

On quiet days: **nothing**. Silence is the feature.

## Supported brokers (screenshot extraction)
Zerodha Kite, Groww, Upstox, Angel One, ICICI Direct, Kotak Neo, and most others with a clear holdings table.

## Out of scope
- F&O / derivatives (cash equities only)
- Mutual funds / ETFs
- US/global stocks
- Direct trade execution

## Install

### Via ClawHub (recommended)
```bash
openclaw skills install ai-stock-watchdog
```
Then say *"set up stock monitor"* in any supported agent.

### Manual
Copy this folder into your agent's skills directory and say *"set up stock monitor"*.

## Files

| File | Purpose |
|---|---|
| `SKILL.md` | Full workflow and methodology |
| `portfolio.json` | Your holdings (managed by skill) |
| `competitors.json` | Sector peers + conglomerate segments + regulator mapping |
| `severity-rubric.md` | Sev-1/2/3 rules with context modifiers |
| `sources.md` | Data sources with search query templates |
| `manifest.json` | Skill metadata |
| `state/last-run.json` | Alert history, guidance tracker, suppression log |
| `alerts/` | Archived alerts |
| `examples/` | Worked example scenarios |

## Disclaimer
**This skill is informational only and is NOT investment advice.** It surfaces signals against a transparent rubric you can read and customise. All buy/sell decisions are yours. The author is not a SEBI-registered investment advisor. Stock investments are subject to market risk. Past performance is not indicative of future returns.

## License
MIT-0 — see `LICENSE`.


path: competitors.json
content: {
  "_comment": "Sector peers, conglomerate segment mapping, and ticker-to-sector index. Managed by AI stock watchdog skill.",
  "sector_peers": {
    "IT Services": ["TCS", "INFY", "HCLTECH", "WIPRO", "TECHM", "LTIM", "PERSISTENT", "COFORGE", "MPHASIS"],
    "Private Banks": ["HDFCBANK", "ICICIBANK", "AXISBANK", "KOTAKBANK", "INDUSINDBK", "IDFCFIRSTB", "FEDERALBNK", "BANDHANBNK"],
    "PSU Banks": ["SBIN", "BANKBARODA", "CANBK", "PNB", "UNIONBANK", "INDIANB", "BANKINDIA"],
    "NBFC": ["BAJFINANCE", "BAJAJFINSV", "CHOLAFIN", "SHRIRAMFIN", "M&MFIN", "LICHSGFIN", "MANAPPURAM", "MUTHOOTFIN", "POONAWALLA"],
    "Oil & Gas - Upstream": ["ONGC", "OIL"],
    "Oil & Gas - Refining & Petchem": ["RELIANCE", "IOC", "BPCL", "HPCL", "MRPL", "CHENNPETRO"],
    "Oil & Gas - Distribution": ["GAIL", "IGL", "MGL", "GUJGASLTD", "ATGL"],
    "Auto OEM": ["MARUTI", "M&M", "TATAMOTORS", "BAJAJ-AUTO", "EICHERMOT", "HEROMOTOCO", "TVSMOTOR", "ASHOKLEY"],
    "Auto Ancillaries": ["BOSCHLTD", "MOTHERSON", "BHARATFORG", "EXIDEIND", "AMARAJABAT", "SUNDRMFAST", "ENDURANCE"],
    "Cement": ["ULTRACEMCO", "SHREECEM", "AMBUJACEM", "ACC", "DALBHARAT", "RAMCOCEM", "JKCEMENT", "BIRLACEMENTS"],
    "FMCG": ["HINDUNILVR", "ITC", "NESTLEIND", "BRITANNIA", "DABUR", "MARICO", "GODREJCP", "TATACONSUM", "COLPAL", "EMAMILTD"],
    "Pharma - Large Cap": ["SUNPHARMA", "DRREDDY", "CIPLA", "DIVISLAB", "LUPIN", "AUROPHARMA", "TORNTPHARM", "ZYDUSLIFE"],
    "Pharma - Mid Cap": ["ALKEM", "IPCALAB", "GLENMARK", "BIOCON", "NATCOPHARM", "LAURUSLABS"],
    "Metals - Steel": ["TATASTEEL", "JSWSTEEL", "SAIL", "JINDALSTEL", "NMDC"],
    "Metals - Non-ferrous": ["HINDALCO", "VEDL", "NATIONALUM", "HINDCOPPER"],
    "Power - Generation": ["NTPC", "POWERGRID", "TATAPOWER", "ADANIPOWER", "JSWENERGY", "NHPC"],
    "Power - Renewable": ["ADANIGREEN", "TATAPOWER", "NHPC", "SJVN", "IREDA"],
    "Telecom": ["BHARTIARTL", "RELIANCE", "IDEA", "TATACOMM"],
    "Realty": ["DLF", "GODREJPROP", "OBEROIRLTY", "PRESTIGE", "BRIGADE", "MACROTECH", "PHOENIXLTD", "SOBHA"],
    "Consumer Durables": ["TITAN", "HAVELLS", "VOLTAS", "CROMPTON", "WHIRLPOOL", "DIXON", "BAJAJELEC", "BLUESTARLT"],
    "Chemicals": ["PIDILITIND", "SRF", "AARTIIND", "DEEPAKNTR", "NAVINFLUOR", "PIIND", "CLEAN", "ATUL"],
    "Capital Goods": ["LT", "SIEMENS", "ABB", "BEL", "BHEL", "CUMMINSIND", "THERMAX", "KAYNES"],
    "Defence": ["HAL", "BEL", "BDL", "MAZDOCK", "COCHINSHIP", "GRSE"],
    "Insurance - Life": ["SBILIFE", "HDFCLIFE", "ICICIPRULI", "LICI", "MAXFIN"],
    "Insurance - General": ["ICICIGI", "STARHEALTH", "NIACL"],
    "Asset Management": ["HDFCAMC", "NAM-INDIA", "UTIAMC", "ABSLAMC", "ANGELONE"],
    "Logistics": ["CONCOR", "BLUEDART", "DELHIVERY", "TCI", "MAHLOG", "ALLCARGO"],
    "Hospitality": ["INDHOTEL", "EIHOTEL", "CHALET", "LEMONTREE"],
    "Aviation": ["INDIGO", "SPICEJET", "AIRPORTAUTH"],
    "Paints": ["ASIANPAINT", "BERGEPAINT", "KANSAINER", "AKZOINDIA", "INDIGOPNTS"],
    "Retail": ["DMART", "TRENT", "SHOPERSTOP", "VMART", "RELIANCE"],
    "Digital / Internet": ["ZOMATO", "PAYTM", "NYKAA", "POLICYBZR", "CARTRADE", "RELIANCE"],
    "Conglomerate": ["RELIANCE", "ITC", "LT", "GRASIM", "ADANIENT", "TATACHEM", "GODREJIND"]
  },
  "conglomerate_segments": {
    "RELIANCE": {
      "segments": {
        "O2C (Oil-to-Chemicals)": {
          "description": "Refining (Jamnagar — world's largest single-site) + Petrochemicals (polymers, polyester, elastomers)",
          "key_metrics": ["Singapore GRM", "petchem spreads (PE, PP, PVC)", "refining throughput", "crude-product spread"],
          "peers_for_segment": ["IOC", "BPCL", "HPCL", "MRPL"],
          "regulatory_watch": ["oil ministry pricing", "export duty on petroleum products", "windfall tax"]
        },
        "Digital Services (Jio)": {
          "description": "Jio Platforms — telecom (JioMobile), broadband (JioFiber), digital apps ecosystem",
          "key_metrics": ["subscriber count", "ARPU", "data per subscriber", "JioFiber adds", "churn rate"],
          "peers_for_segment": ["BHARTIARTL", "IDEA"],
          "regulatory_watch": ["TRAI tariff orders", "spectrum auction", "5G rollout mandates"]
        },
        "Retail": {
          "description": "Reliance Retail — physical stores + digital commerce across grocery, fashion, electronics, pharma",
          "key_metrics": ["store count", "revenue per sqft", "same-store sales growth", "digital commerce %", "footfall"],
          "peers_for_segment": ["DMART", "TRENT", "SHOPERSTOP", "VMART"],
          "regulatory_watch": ["FDI policy in retail", "ONDC platform"]
        },
        "Oil & Gas (E&P)": {
          "description": "Upstream exploration — KG-D6 block gas production, CBM",
          "key_metrics": ["KG-D6 gas production volume", "gas realization price", "APM gas pricing"],
          "peers_for_segment": ["ONGC", "OIL"],
          "regulatory_watch": ["APM gas price revision (semi-annual)", "gas marketing freedom"]
        },
        "New Energy": {
          "description": "Solar (gigafactory), green hydrogen, battery storage, carbon fiber",
          "key_metrics": ["capex commitment vs spend", "capacity commissioning timelines", "partnership announcements"],
          "peers_for_segment": ["ADANIGREEN", "TATAPOWER"],
          "regulatory_watch": ["PLI scheme for solar/battery", "green hydrogen policy"]
        }
      },
      "sum_of_parts_note": "Reliance trades at a holding company discount/premium to the sum of segment values. Track SOTP vs CMP periodically."
    },
    "HDFCBANK": {
      "segments": {
        "Retail Banking": {
          "description": "Retail loans (home, auto, personal, credit cards), CASA deposits, branch banking",
          "key_metrics": ["retail loan growth %", "CASA ratio", "retail NPA", "credit card spends", "branch count"],
          "peers_for_segment": ["ICICIBANK", "AXISBANK", "KOTAKBANK"]
        },
        "Wholesale Banking": {
          "description": "Corporate loans, trade finance, cash management, investment banking",
          "key_metrics": ["wholesale book growth", "corporate NPA", "large exposure concentration"],
          "peers_for_segment": ["ICICIBANK", "AXISBANK", "SBIN"]
        },
        "Treasury": {
          "description": "Investment portfolio (G-Secs, bonds), forex, derivatives trading",
          "key_metrics": ["treasury income volatility", "modified duration of bond portfolio", "MTM gains/losses"],
          "peers_for_segment": ["ICICIBANK", "SBIN", "KOTAKBANK"]
        }
      },
      "merger_integration_note": "Post-HDFC Ltd merger (Jul 2023): track merged book integration, LDR (loan-to-deposit ratio) normalization from elevated levels, PSL compliance, branch conversion of HDFC Ltd offices, and synergy realization in operating costs. The merged entity has a significantly different balance sheet profile than standalone HDFC Bank."
    },
    "LT": {
      "segments": {
        "Infrastructure Projects": {
          "description": "EPC across buildings, transportation, heavy civil, power, water",
          "key_metrics": ["order inflow", "order book", "execution pace (revenue vs book)", "margin trend"],
          "peers_for_segment": ["ENGINERSIN", "NBCC", "KEC"]
        },
        "IT & Technology Services": {
          "description": "LTIMindtree + L&T Technology Services",
          "key_metrics": ["constant currency growth", "deal TCV", "attrition", "margin"],
          "peers_for_segment": ["TCS", "INFY", "HCLTECH"]
        },
        "Financial Services": {
          "description": "L&T Finance (NBFC)",
          "key_metrics": ["AUM growth", "NPA", "cost-to-income"],
          "peers_for_segment": ["BAJFINANCE", "CHOLAFIN"]
        }
      }
    },
    "ITC": {
      "segments": {
        "Cigarettes": {
          "description": "India's dominant cigarette manufacturer — Gold Flake, Classic, Navy Cut",
          "key_metrics": ["volume growth", "realization per stick", "EBIT margin", "excise duty impact"],
          "regulatory_watch": ["GST on cigarettes", "excise duty in Budget", "plain packaging regulations"]
        },
        "FMCG - Others": {
          "description": "Aashirvaad, Sunfeast, Bingo, Yippee, Engage, Fiama, Savlon",
          "key_metrics": ["revenue growth", "EBIT margin trend (from losses to profit)", "market share in key categories"],
          "peers_for_segment": ["HINDUNILVR", "BRITANNIA", "DABUR"]
        },
        "Hotels": {
          "description": "ITC Hotels (being demerged) — luxury to mid-market",
          "key_metrics": ["RevPAR", "occupancy", "room additions"],
          "peers_for_segment": ["INDHOTEL", "EIHOTEL", "CHALET"]
        },
        "Agri Business": {
          "description": "Leaf tobacco, soya, wheat, spices — B2B commodity trading",
          "key_metrics": ["revenue (volatile)", "margin (low but steady)"]
        },
        "Paperboards & Packaging": {
          "description": "PSPB — paperboards, specialty papers, packaging",
          "key_metrics": ["realization per tonne", "capacity utilization"]
        }
      }
    }
  },
  "ticker_to_sector": {},
  "sector_regulators": {
    "Private Banks": ["RBI"],
    "PSU Banks": ["RBI"],
    "NBFC": ["RBI"],
    "Insurance - Life": ["IRDAI"],
    "Insurance - General": ["IRDAI"],
    "Asset Management": ["SEBI"],
    "Telecom": ["TRAI", "DoT"],
    "Pharma - Large Cap": ["USFDA", "CDSCO", "DCGI"],
    "Pharma - Mid Cap": ["USFDA", "CDSCO", "DCGI"],
    "Oil & Gas - Upstream": ["DGH", "MoPNG"],
    "Oil & Gas - Refining & Petchem": ["MoPNG"],
    "Oil & Gas - Distribution": ["PNGRB"],
    "Power - Generation": ["CERC", "CEA"],
    "Power - Renewable": ["MNRE", "CERC"],
    "Aviation": ["DGCA"],
    "Realty": ["RERA (state-level)"],
    "Metals - Steel": ["Ministry of Steel"],
    "Defence": ["MoD", "DPP/DAP"]
  }
}


path: examples/01-first-run-onboarding.md
content: # Example 1 — First-run onboarding with Reliance + HDFC Bank

A new user installs the skill and sets up monitoring for two holdings.

## User
> set up stock monitor

## Agent (using the skill)
> Welcome. Here's what this skill does in a nutshell:
>
> 1. It watches your Indian stocks every weekday morning.
> 2. It ONLY pings you when something genuinely critical happens — promoter selling shares, governance failures, cash flow deterioration, surveillance moves, big earnings misses.
> 3. When results come out, it does a deep-dive: not just headline PAT, but cash flow quality, segment trends, and whether management delivered what they promised.
> 4. Most days you'll hear nothing. That's the design.
>
> Want to set it up now? How would you like to share your portfolio?
>
> 1. **Drop a screenshot** of your broker app (Zerodha, Groww, Upstox, Angel One, etc.)
> 2. **Describe in text** (e.g., "10 Reliance at 2900, 50 HDFC Bank at 1620")
> 3. **Skip for now**

## User
> 10 Reliance at avg 1265, 50 HDFC Bank at avg 1620

## Agent
> ```
> Proposed portfolio update:
>
>   ✱ ADD   RELIANCE   qty: 10    avg: ₹1,265   sector: Conglomerate (O2C + Digital + Retail + E&P + New Energy)
>   ✱ ADD   HDFCBANK   qty: 50    avg: ₹1,620   sector: Private Banks (post-merger entity)
>
>   Invested value: ₹12,650 + ₹81,000 = ₹93,650
>   Concentration: HDFCBANK 86.5% / RELIANCE 13.5%
>   ⚠ Note: HDFCBANK is 86.5% of portfolio — that's highly concentrated in a single stock.
>
> Net result: 2 holdings across 2 sectors.
> ```
>
> Apply? (yes / no / edit)

## User
> yes

## Agent
> ✓ Portfolio updated. Backup saved.
>
> A few setup questions:
>
> 1. **Investment horizon**: short-term (<3 months) / medium-term (3–12 months) / long-term (1+ year)?
> 2. **Alert sensitivity**: critical only (recommended) / critical + high / daily digest?
> 3. **Include positive signals** (promoter buying, credit upgrades, contract wins)? yes / no
> 4. **Set up daily 8:30 AM IST scan?** (recommended)

## User
> long-term, critical only, yes for positive signals, yes for daily

## Agent
> ✓ Preferences saved: long-term horizon, critical-only alerts, positive signals enabled.
> ✓ Daily scan scheduled — Mon–Fri at 8:30 AM IST.
>
> Two things to know about your holdings:
> - **RELIANCE** is a conglomerate — I'll track 5 segments separately: O2C (refining + petchem), Jio (Digital Services), Retail, E&P, and New Energy. Consolidated numbers alone don't tell the real story.
> - **HDFCBANK** is post-merger with HDFC Ltd — I'll track merger integration metrics (LDR normalization, branch conversion, PSL compliance) alongside standard banking KPIs.
>
> Want a first-look scan now to flag anything from the last 7 days?


path: examples/02-screenshot-update.md
content: # Example 2 — Portfolio update with STCG/LTCG awareness

The user partially exits one holding and adds to another.

## User
> sold 5 Reliance at 1350, bought 25 more HDFC Bank at 1580

## Agent (using the skill)
> ```
> Proposed portfolio update:
>
>   ✏ TRIM    RELIANCE   qty: 10 → 5     avg: ₹1,265 (unchanged)
>                        Sold 5 at ₹1,350 → realized gain ₹425 (₹85/share × 5)
>                        Holding period: 47 days → STCG applicable (20% tax)
>
>   ✏ ADD TO  HDFCBANK   qty: 50 → 75    avg: ₹1,620 → ₹1,607 (weighted)
>                        Calculation: ((50 × 1620) + (25 × 1580)) / 75 = ₹1,606.67
>
>   Updated concentration:
>     HDFCBANK: ₹1,20,525 (95.0%) ← ⚠ extremely concentrated
>     RELIANCE: ₹6,325 (5.0%)
>
>   Total invested: ₹1,26,850
> ```
>
> ⚠ **Concentration warning**: HDFCBANK is now 95% of your portfolio. Any bank-specific event (RBI action, NIM compression, asset quality deterioration) would hit nearly your entire invested capital. Consider diversifying.
>
> Apply? (yes / no / edit)

## User
> yes, I know about the concentration

## Agent
> ✓ Portfolio updated. Backup saved.
>
> Note on the RELIANCE trim:
> - Held for 47 days → **Short-term capital gains** apply (20% flat on equity).
> - LTCG threshold is 365 days. Had you held ~318 more days, gains above ₹1.25 lakh would have been taxed at 12.5% instead.
>
> Want me to scan HDFCBANK for anything in the last 7 days given you've increased your position?


path: examples/03-sev1-alert.md
content: # Example 3 — Multi-signal alert: HDFC Bank governance + Reliance segment check

The daily scan fires at 8:30 AM IST. Most days, nothing. This day, two signals.

## Trigger
Scheduled daily scan fires.

## What the skill does (silently)
1. Reads portfolio.json — 2 holdings: RELIANCE (5 shares), HDFCBANK (75 shares)
2. Portfolio health: HDFCBANK at 95% concentration — flag noted
3. Market calendar: Not an MPC week, no budget, no expiry week
4. Global cues: Brent crude up 3.2% overnight → note for Reliance O2C (mild positive for GRM, but not Sev-1 level)
5. Per-stock scan begins

### HDFCBANK findings:
- Exchange filing: Chairman resigned, board commissioned external law firm review
- News: Q4 NIM compressed 15 bps QoQ to 3.44%, NII grew only 3.2% YoY
- Cash flow: CFO healthy at 1.1x PAT — no manipulation flag
- Promoter holding: stable (no HDFC entity sold post-merger)
- Severity classification: Chairman exit + legal review = Sev-1 governance trigger
- Context modifier: 95% portfolio concentration → ELEVATE urgency

### RELIANCE findings:
- News: Jio added 8.2M subscribers in Q4, ARPU up ₹3 QoQ to ₹206
- O2C: Singapore GRM at $6.2/bbl (stable), petchem spreads tightening slightly
- Retail: 680 new stores in Q4, revenue/sqft up 4%
- No Sev-1 triggers. Jio/Retail numbers are Sev-1 POSITIVE (logged, included since user opted in).

## What the user sees

> 🔴 STOCK ALERT — 2026-05-01
>
> **HDFCBANK — Governance red flag at the top + NIM pressure**
> Severity: Sev-1 | Category: Governance / Trust Collapse | Sector: Private Banks
>
> **What happened:**
> Atanu Chakraborty, part-time Chairman and Independent Director, resigned effective 18 March 2026. Keki Mistry appointed interim Chairman for 3 months. The board has commissioned external law firms (domestic and international) to review the contents of his resignation letter — an unusual step that signals the board believes the resignation may contain material concerns requiring independent investigation.
>
> Separately, Q4 FY26 results show NIM compressed 15 bps QoQ to 3.44%. NII grew only 3.2% YoY — the weakest growth since the HDFC Ltd merger. Post-merger LDR remains elevated at 104%, pressuring deposit mobilization costs.
>
> **Why it matters for YOU (long-term holder, avg ₹1,607, 75 shares — 95% of portfolio):**
> - Chairman exit + board-level legal review is an early-warning governance signal. In Indian banking history, board-level upheavals preceded regulatory interventions at Yes Bank, ICICI Bank (2018), and DHFL.
> - NIM compression in a rising/stable rate environment suggests the merged book's cost of funds is structurally higher than standalone HDFC Bank.
> - **Critical**: This stock is 95% of your portfolio. Any further deterioration disproportionately impacts your entire capital.
>
> **Suggested action:** WATCH CLOSELY. Do not add to position.
> Escalation triggers to EXIT BIAS:
> - Adverse findings from law firm review
> - No permanent chairman announced by mid-June 2026
> - NIM compression continues in Q1 FY27 (below 3.35%)
> - Any RBI observation in the annual inspection report
>
> **Confidence:** Medium-High
> **Management credibility:** MEDIUM (guided "NIM normalization by H2 FY26" — did not deliver)
>
> **Sources:**
> - [HDFC Bank Q4 FY26 Results — Business Standard](https://www.business-standard.com/companies/quarterly-results/)
> - [HDFC Bank Chairman resignation filing — BSE](https://www.bseindia.com/corporates/ann.html)
>
> **Counter-view:** Resignations can happen for personal/policy reasons. Franchise quality, asset quality (GNPA 1.33%), and deposit franchise remain strong. Legal review could be precautionary governance best practice.
>
> **Portfolio impact:** This is 95% of your invested capital. Given extreme concentration, even Sev-2 signals on this stock warrant your attention.

---

> 🟢 POSITIVE NOTE — 2026-05-01
>
> **RELIANCE — Jio + Retail momentum continues**
>
> Jio added 8.2M net subscribers in Q4 FY26, ARPU up ₹3 QoQ to ₹206 (street expected ₹204). Reliance Retail opened 680 stores, revenue per sqft improved 4% YoY. O2C segment stable with Singapore GRM at $6.2/bbl.
>
> No action needed. Logged for context. This holding is only 5% of your portfolio.

## What happens next
- HDFCBANK alert archived to `alerts/2026-05-01-alert.md`
- `state/last-run.json` updated with signal IDs, management credibility scores, and guidance tracker
- Same HDFCBANK governance signal suppressed for 14 days
- Promoter holding/pledge data stored for QoQ comparison next quarter


path: manifest.json
content: {
  "name": "ai-stock-watchdog",
  "displayName": "AI stock watchdog",
  "version": "2.2.0",
  "description": "Daily monitoring for Indian equity holdings (NSE/BSE) using a documented severity rubric. Silent by default — surfaces Sev-1 events only. Quarterly checks, conglomerate segment view, guidance tracking. Informational only.",
  "author": "daveanandraj",
  "license": "MIT-0",
  "homepage": "https://github.com/daveanandraj/indian-stock-monitor-clawhub",
  "repository": "https://github.com/daveanandraj/indian-stock-monitor-clawhub",
  "keywords": [
    "stocks",
    "investing",
    "india",
    "nse",
    "bse",
    "portfolio",
    "alerts",
    "earnings",
    "fundamentals",
    "monitoring",
    "promoter-pledge",
    "cash-flow-analysis",
    "governance",
    "conglomerate"
  ],
  "type": "skill",
  "entryPoint": "SKILL.md",
  "requires": {
    "tools": [
      "WebSearch",
      "Read",
      "Write",
      "Edit",
      "AskUserQuestion"
    ],
    "optional": [
      "mcp__scheduled-tasks__create_scheduled_task"
    ]
  },
  "dataFiles": [
    "portfolio.json",
    "competitors.json",
    "severity-rubric.md",
    "sources.md"
  ],
  "stateDir": "state/",
  "outputDir": "alerts/",
  "compatibility": {
    "platforms": ["openclaw", "claude-code", "codex", "copilot"]
  },
  "categories": ["finance", "personal-productivity", "monitoring"],
  "disclaimer": "Informational only. NOT investment advice. The author is not a SEBI-registered investment advisor. Stock investments are subject to market risk."
}


path: portfolio.json
content: {
  "_comment": "Managed by AI stock watchdog skill. Do not edit by hand — use the skill to update holdings. On first run, the skill detects this empty state and walks you through onboarding.",
  "_first_run": true,
  "holdings": [],
  "watchlist": [],
  "preferences": {
    "horizon": null,
    "alert_threshold": null,
    "delivery": null,
    "positive_signals": false,
    "timezone": "Asia/Kolkata",
    "currency": "INR"
  }
}


path: severity-rubric.md
content: # Severity Rubric — AI stock watchdog v2

The skill MUST stay silent unless a Sev-1 trigger is hit. Sev-2 only lands in the optional dashboard. Sev-1 = "the user should see this within hours."

**Core philosophy**: The rubric gives high weight to promoter/pledge and insider changes, governance and regulatory action, cash flow quality vs reported profit, and sector-wide shocks. Ordering and thresholds are a design choice, not a guarantee of outcomes.

---

## Sev-1 — CRITICAL (Notify the user immediately)

### A. Promoter & insider signals (high weight in this rubric)

**Promoter holding decline:**
- Promoter holding dropped >2 percentage points in latest quarterly shareholding pattern (QoQ)
- Promoter holding dropped below 50% (control threshold) for the first time
- Promoter sold via open market (not OFS/block) — ANY amount is a red flag
- Promoter entity reclassified out of promoter group

**Promoter pledge escalation:**
- Pledge increased >5 percentage points QoQ
- Total pledge crossed 50% of promoter holding (liquidation risk territory)
- Pledge crossed 75% (imminent margin call risk)
- Pledge + encumbrance (non-disposal undertaking) crossed 40% combined
- Lender invoked pledged shares (even partial)

**Insider trading red flags:**
- KMP (CEO/CFO/CS) sold shares within 30 days before results (check SAST/PIT disclosures)
- Multiple independent directors sold in the same quarter
- Designated persons sold >25% of their holding in a single quarter

### B. Governance / trust collapse

- Auditor resignation mid-cycle (any reason — always material in India; rotation doesn't count)
- Auditor qualification or adverse opinion in latest annual report
- Emphasis of matter paragraph mentioning going concern, fraud investigation, or regulatory non-compliance
- SEBI order (adjudication, interim, show-cause) naming the company, promoter, or KMP
- ED / CBI / IT raid or investigation naming the company or promoter
- Forensic audit ordered by board or regulator
- CEO/MD or CFO resignation without named successor within 7 days
- CEO + CFO exit within 90 days of each other (classic pre-fraud-discovery pattern)
- Independent director resignation citing governance concerns or "personal reasons" within 6 months of joining
- Whistleblower complaint reported by reputable media
- Restatement or revision of past financials (any period)
- Related party transactions jumped >50% YoY without proportionate revenue growth
- Auditor changed mid-tenure to a smaller/less reputable firm

### C. Surveillance / regulatory red flags

- Stock entered GSM Stage 2 or higher (Stage 1 alone = Sev-2)
- Stock entered ASM Long-term additional surveillance framework
- Stock moved to Trade-to-Trade (T2T) segment
- Trading suspended or halt imposed by exchange
- Circuit limit reduced (from 20% to 10%, or 10% to 5%)
- SEBI debarment order against promoter/KMP
- NSE/BSE issued clarification letter and company response was evasive or delayed

### D. Capital structure / solvency stress

- Credit rating downgrade by ≥2 notches OR downgrade to below investment grade (below BBB-)
- Credit rating placed on "watch with negative implications" (not just "negative outlook")
- Debt-to-equity jumped >30% QoQ in latest results
- Interest coverage ratio fell below 1.5x (debt servicing at risk)
- Default or delay on debt servicing (even technical default)
- Company drew down emergency credit lines or raised expensive short-term debt
- Debt maturity wall: >30% of total debt maturing within 12 months with inadequate cash/facilities
- Convertible instrument (FCCB/OCD/CCD) conversion triggered at adverse terms

### E. Earnings shock (when quarterly results are out)

**Revenue & profit:**
- Revenue miss >20% vs consensus OR >15% below same quarter last year without one-off explanation
- PAT miss >25% vs consensus
- Operating loss reported for first time in 8+ quarters
- Revenue degrowth for 2nd consecutive quarter (trend confirmation)

**Margin deterioration:**
- EBITDA margin compression >300 bps QoQ without one-off explanation
- Gross margin compression >500 bps QoQ (input cost pass-through failure)
- FY guidance cut >15% on revenue OR >200 bps on margin

**Cash flow quality (THE most underrated check — catches window dressing):**
- Cash flow from operations (CFO) negative while PAT is positive (classic red flag)
- CFO/PAT ratio below 0.5x for 2+ consecutive quarters (accrual-heavy, cash-light earnings)
- CFO/PAT ratio diverging: PAT growing while CFO is flat or declining over 3+ quarters
- Significant increase in "other income" as % of PBT (>25%) without clear treasury/investment explanation
- Trade receivables growing >2x revenue growth rate for 2 consecutive quarters
- Inventory buildup >1.5x revenue growth for 2 consecutive quarters
- Exceptional/extraordinary items used to inflate PAT for 2+ of last 4 quarters

**Working capital deterioration:**
- Working capital cycle (inventory days + receivable days - payable days) increased >15 days QoQ
- Net working capital turned negative to positive (company now funding WC from debt, not operations)
- Receivable days crossed 90 (collection risk in Indian context)

**Tax rate anomalies:**
- Effective tax rate below 15% without SEZ/tax holiday explanation (aggressive planning signal)
- Sharp ETR swing (>10pp) QoQ without disclosed reason (reserves/write-backs manipulation)

### F. Concall delta signals

Sev-1 if 2+ of these hit simultaneously. Any single one = Sev-2.

- Management explicitly mentions demand weakness / slowdown in core segment
- Capex plan cut >20% vs prior guidance
- Order book / pipeline declining QoQ for 2nd consecutive quarter
- Tone shift on guidance: "confident/strong" language replaced with "cautious/watchful/challenging"
- Pricing pressure or competitive intensity called out as NEW development
- Customer concentration risk disclosed (top client >15% of revenue)
- Management unable to provide forward guidance (previously used to guide)
- Concall significantly shorter than usual with fewer analyst questions taken

**Management credibility check (track over time in state):**
- Management guided X in previous quarter, delivered <70% of guided number → low credibility flag
- 2+ consecutive quarters of missing own guidance → credibility score drops, weight all management statements lower

### G. Litigation / business disruption

- Adverse Supreme Court or High Court ruling with quantifiable financial impact >5% of market cap
- Loss of a top-3 customer (by revenue share) or key licence/contract
- Plant/facility shutdown lasting >7 days with >10% revenue impact
- Cyber/data breach disclosed to exchanges
- Major product recall or quality failure
- Anti-trust (CCI) order with penalty >2% of revenue
- Environmental clearance revoked or NOC denied for expansion project
- Key raw material supply disrupted (>30 day impact)

### H. Sector-wide regulatory shocks (map to held stocks)

- Government ban, export restriction, or sharp duty change on company's primary product
- RBI action: PCA framework, lending restrictions, digital lending curbs (for banks/NBFCs)
- USFDA Warning Letter or Import Alert (for pharma — held stock or 2+ peers)
- TRAI tariff order change (telecom)
- IRDAI product/pricing regulation change (insurance)
- MoEFCC clearance policy shift affecting mining/metals/power
- GST rate change with direct revenue line impact on held stock

### I. Short-term triggers (elevated weight when user horizon = short-term)

- Block/bulk deal: promoter or >5% shareholder sold ≥1% of equity
- Single-day fall ≥7% on volumes >3x 20-day average
- 52-week low breached on >2x average volume
- FII holding cut >2 percentage points in quarterly disclosure
- Stock entered F&O ban period (derivative settlement pressure)
- Open interest buildup >30% with price decline >3% (short buildup)

### J. Conglomerate-specific triggers (for multi-segment companies like Reliance, Tata, Adani)

- Segment EBIT turned negative for any major segment (>10% of revenue)
- Cross-subsidization: profitable segment margin declining while loss-making segment scales
- Holding company discount widened >30% vs sum-of-parts NAV
- Key subsidiary IPO/demerger cancelled or delayed
- Intercompany loans or guarantees crossed >20% of standalone net worth

---

## Sev-1 POSITIVE — Actionable good news (notify if user preference allows)

These don't trigger alerts by default (silence-first design) but are logged and shown on request or in daily_brief mode:

- Promoter increased holding via open market purchase (strong conviction signal in India)
- Company announced buyback (especially if at premium to CMP)
- Credit rating upgrade by ≥1 notch
- Stock exited GSM/ASM surveillance framework
- Major new contract win >10% of annual revenue
- Received regulatory approval pending for >6 months (USFDA ANDA, SEBI, RBI licence)
- Debt repaid ahead of schedule / became debt-free
- Institutional investor (marquee PE/sovereign fund) picked up >1% stake

---

## Sev-2 — Dashboard only (do NOT push notification)

- GSM Stage 1 entry (no immediate action, but watch)
- Single brokerage downgrade (note target price change)
- Single concall warning sign (doesn't meet 2+ threshold for Sev-1)
- Peer earnings miss or guidance cut (industry signal, not direct)
- Mutual fund net selling >0.5% of equity in latest month-end data
- Single block deal 0.5–1% of equity by non-promoter institutional investor
- 200-DMA breakdown on normal volume
- Sector derating (PE compression) without company-specific trigger
- Promoter pledge increased 1–5 percentage points (below Sev-1 threshold but worth noting)
- Management missed guidance by 10–30% (below credibility-collapse threshold)
- Trade receivables growing faster than revenue for 1 quarter (not yet 2-quarter trend)
- CFO/PAT ratio between 0.5x–0.7x for 1 quarter
- Company in MSCI/Nifty rebalancing exclusion list (passive flow risk)
- FII holding cut 1–2 percentage points
- ADR/GDR discount widened significantly (for dual-listed stocks)

---

## Sev-3 — Log only (never surface)

- Routine corporate actions (dividend declaration, AGM notice, routine board meeting)
- Minor management changes below KMP level
- Regular brokerage initiating coverage or reiterating rating
- Macro news without direct sector mapping to held stocks
- Index rebalancing inclusion (generally positive but not actionable)
- Routine SEBI circular not specific to company/sector
- Stock split / bonus announcement (mechanical, not fundamental)
- ESG rating change by third-party agency

---

## Context modifiers (adjust severity based on these)

### Peer-relative adjustment
If the entire sector (3+ peers) fell >5% on the same day, a single stock falling 7% is less alarming — reduce from Sev-1 to Sev-2. Conversely, if the stock fell 7% while peers are flat/up, elevate urgency.

### Horizon adjustment
- **Short-term holder**: Elevate all Section I triggers by one level. Block deals, volume spikes, and F&O ban are immediately actionable.
- **Long-term holder**: Demote single-day price triggers by one level UNLESS accompanied by a fundamental trigger (governance, earnings, capital structure). A 7% drop alone is noise for a long-term holder.

### Position size adjustment
If the stock is >25% of portfolio value (concentration risk), elevate any Sev-2 trigger to Sev-1. The user has outsized exposure and deserves earlier warning.

### Market regime
During broad market corrections (Nifty down >10% from recent high), individual stock price drops need a higher threshold to qualify as Sev-1 (raise single-day fall threshold from 7% to 12%). During bull markets, lower the threshold (5%).

---

## Decision rule

Notify the user IF AND ONLY IF:
1. At least one Sev-1 trigger fires for a held stock NOT flagged in last 14 days, OR
2. At least 2 Sev-1 triggers fire across peers in same sector within 7 days (industry stress), OR
3. Quarterly workflow concluded EXIT BIAS or WATCH on a held stock, OR
4. Portfolio health check found concentration risk >30% in a single stock with any Sev-2+ signal on that stock.

When in doubt, default to silence. False positives erode trust faster than missed Sev-2 signals.


path: sources.md
content: # Data Sources — AI stock watchdog v2

Sources are listed in priority order within each category. When two sources conflict, trust regulatory/exchange filings over news, and news over social media.

---

## 1. Exchange filings & regulatory (highest trust — primary source of truth)

### Corporate announcements
- **NSE**: https://www.nseindia.com/companies-listing/corporate-filings-announcements
- **BSE**: https://www.bseindia.com/corporates/ann.html
- Search: `site:nseindia.com "{COMPANY_NAME}" announcement` or `site:bseindia.com "{COMPANY_NAME}"`

### Shareholding patterns (quarterly — critical for promoter holding/pledge tracking)
- **BSE shareholding**: https://www.bseindia.com/corporates/shpSecurities.aspx
- **NSE shareholding**: search `"{TICKER} shareholding pattern" site:nseindia.com`
- **Trendlyne shareholding**: https://trendlyne.com/equity/{TICKER}/shareholding/
- **Screener shareholding tab**: https://www.screener.in/company/{TICKER}/
- Filing schedule: within 21 days of quarter-end (Apr 21, Jul 21, Oct 21, Jan 21)

### SEBI orders & enforcement
- **SEBI orders**: https://www.sebi.gov.in/sebiweb/home/HomeAction.do?doListing=yes&sid=1&ssid=6&smid=0
- **SEBI adjudication orders**: https://www.sebi.gov.in/sebiweb/home/HomeAction.do?doListing=yes&sid=5
- **SEBI interim orders**: search `site:sebi.gov.in "{COMPANY_NAME}" interim order`
- Search: `"{COMPANY_NAME}" SEBI order` last 30 days

### Surveillance
- **NSE ASM/GSM**: https://www.nseindia.com/regulations/asm-listed-securities
- **BSE surveillance**: https://www.bseindia.com/markets/equity/EQReports/Surveillance.aspx
- **NSE T2T list**: search `site:nseindia.com trade-to-trade`
- **NSE F&O ban list**: https://www.nseindia.com/market-data/f-o-ban-list (check daily during expiry week)

### Insider trading / SAST disclosures
- **NSE SAST/PIT**: corporate filings → filter by "Insider Trading / SAST"
- **BSE insider trading**: https://www.bseindia.com/corporates/Insider_Trading_new.aspx
- Search: `"{TICKER} insider trading disclosure" site:nseindia.com` or `site:bseindia.com`

---

## 2. Fundamentals, financials & filings

### Quarterly results & ratios
- **Screener.in**: https://www.screener.in/company/{TICKER}/ — quarterly results, annual P&L, balance sheet, cash flow, ratios, shareholding, concall transcripts
- **Trendlyne**: https://trendlyne.com/equity/Snapshot/{TICKER}/ — consensus estimates, broker ratings, DVM score
- **Tijori Finance**: https://www.tijorifinance.com/company/{TICKER} — segment breakdown, subsidiary mapping
- **TIKR**: https://tikr.com/ — global-quality financial data for Indian companies

### Cash flow statement (critical for CFO/PAT divergence check)
- **Screener cash flow**: https://www.screener.in/company/{TICKER}/#cash-flow
- **Moneycontrol financials**: cash flow tab
- **Annual report**: always cross-reference audited cash flow vs quarterly estimates

### Segment-wise results (use for multi-segment / conglomerate names)
- **BSE segment results filing**: search `"{COMPANY_NAME}" segment results site:bseindia.com`
- **Annual report segment note**: Note on segment reporting in audited financials
- **Tijori segment view**: provides clean segment breakdown

### Related party transactions
- **Annual report Note**: related party disclosures (mandatory under Ind-AS 24)
- **BSE corporate governance report**: filed quarterly, includes RPT details
- Search: `"{COMPANY_NAME}" related party transactions` last 90 days

### Credit ratings
- **CRISIL**: https://www.crisil.com/
- **ICRA**: https://www.icra.in/
- **CARE Ratings**: https://www.careratings.com/
- **India Ratings (Fitch)**: https://www.indiaratings.co.in/
- **Brickwork Ratings**: https://www.brickworkratings.com/
- Search: `"{COMPANY_NAME}" credit rating` last 30 days
- Search: `"{COMPANY_NAME}" rating downgrade OR watch OR negative` last 30 days

### Auditor reports
- **Annual report auditor section**: independent auditor's report, qualifications, emphasis of matter
- Search: `"{COMPANY_NAME}" auditor qualification OR emphasis of matter OR going concern`
- **ICAI disciplinary orders**: search if auditor flagged (rare but devastating)

---

## 3. Concall transcripts & investor presentations

- **Screener "Documents" tab**: https://www.screener.in/company/{TICKER}/#documents (often fastest)
- **Company investor relations page**: usually at `{company-domain}/investors` or `{company-domain}/investor-relations`
- **Trendlyne concall page**: https://trendlyne.com/equity/{TICKER}/concall-transcripts/
- **NDTV Profit concall coverage**: for major companies, journalists cover key quotes
- Search: `"{COMPANY_NAME}" concall transcript Q{N} FY{YY}` or `"{COMPANY_NAME}" analyst meet`

---

## 4. News (use multiple, cross-check before flagging)

### Tier-1 financial news
- **Moneycontrol**: https://www.moneycontrol.com/india/stockpricequote/{slug}
- **Economic Times Markets**: https://economictimes.indiatimes.com/markets
- **Business Standard**: https://www.business-standard.com/markets
- **Mint**: https://www.livemint.com/market
- **Reuters India**: https://www.reuters.com/world/india/
- **NDTV Profit (BQ Prime)**: https://www.ndtvprofit.com/

### Investigative / deep-dive (flag Sev-1 governance triggers from these)
- **The Ken**: https://the-ken.com/
- **Newslaundry Business**: for investigative pieces
- **SEBI Chai (Twitter/X)**: tracks SEBI orders and unusual filings

### Search patterns for news
- `"{COMPANY_NAME}" news` last 1 day (daily scan)
- `"{COMPANY_NAME}" SEBI OR "show cause" OR order` last 7 days
- `"{COMPANY_NAME}" ED OR CBI OR "income tax" OR raid OR investigation` last 30 days
- `"{COMPANY_NAME}" downgrade OR "target price cut"` last 7 days
- `"{COMPANY_NAME}" promoter pledge OR "shares pledged" OR encumbrance` last 30 days
- `"{COMPANY_NAME}" auditor resignation OR "auditor change"` last 90 days
- `"{COMPANY_NAME}" fraud OR whistleblower OR "forensic audit"` last 90 days

---

## 5. Institutional flows

### FII/FPI data
- **NSDL FPI data**: https://www.fpi.nsdl.co.in/ (sector-wise monthly flows)
- **Trendlyne FII/DII data**: daily net buy/sell
- **Moneycontrol FII/DII**: https://www.moneycontrol.com/stocks/marketstats/fii_dii_activity/

### Mutual fund holdings (monthly)
- **ValueResearch**: https://www.valueresearchonline.com/ — fund-wise holdings
- **Trendlyne MF holdings**: https://trendlyne.com/equity/{TICKER}/mutual-fund-holdings/
- **AMFI**: https://www.amfiindia.com/ — industry-level AUM data
- **MorningStar India**: portfolio-level holdings data

### Block / bulk deals
- **NSE bulk/block deals**: https://www.nseindia.com/market-data/large-deals
- **BSE bulk deals**: https://www.bseindia.com/markets/equity/EQReports/bulk_deals.aspx
- Decode who traded: cross-reference entity name with promoter group, PE/VC funds, FIIs

---

## 6. Pre-market & global cues

- **GIFT Nifty / SGX Nifty**: ET Markets pre-market page, Moneycontrol pre-market
- **US close**: Dow, Nasdaq, S&P 500 — any major source
- **Asian markets**: Nikkei 225, Hang Seng, Shanghai Composite
- **Brent crude**: Investing.com (direct impact on OMCs, airlines, paints)
- **USD/INR**: RBI reference rate, Investing.com (impact on IT, pharma exporters)
- **US 10Y yield**: sharp moves impact FII flows into emerging markets
- **VIX (India VIX)**: https://www.nseindia.com/market-data/india-vix — elevated >20 = risk-off

---

## 7. India market calendar (check at start of each week)

### Regular events
- **RBI MPC**: 6 meetings/year (Feb, Apr, Jun, Aug, Oct, Dec) — 3-day meeting, decision on last day
- **Union Budget**: typically Feb 1
- **Economic Survey**: day before Budget
- **GST Council meetings**: roughly quarterly
- **SEBI board meetings**: quarterly

### Result season windows (heaviest scan load)
- **Q3 (Oct-Dec) results**: mid-Jan to mid-Feb
- **Q4 (Jan-Mar) results**: mid-Apr to end-May (busiest — annual + quarterly)
- **Q1 (Apr-Jun) results**: mid-Jul to mid-Aug
- **Q2 (Jul-Sep) results**: mid-Oct to mid-Nov

### F&O expiry (elevated volatility)
- **Monthly expiry**: last Thursday of each month
- **Weekly Bank Nifty/Nifty expiry**: every Thursday
- **Quarterly expiry**: end-March, end-June, end-Sep, end-Dec (rollover week = extra volatile)

### Result date tracking
- **BSE result calendar**: https://www.bseindia.com/corporates/results_calendar.html
- **Trendlyne results calendar**: https://trendlyne.com/calendar/quarterly-results/
- **Moneycontrol results calendar**: check company page for board meeting date

---

## 8. Sector-specific sources

### Banks / NBFCs
- **RBI**: weekly statistical supplement, financial stability report, master circulars
- **RBI PCA list**: https://www.rbi.org.in/ — search "prompt corrective action"
- **NPA data**: quarterly RBI financial stability report, individual bank disclosures
- Key metrics to search: NIM, CASA ratio, GNPA/NNPA, slippage ratio, credit cost, CD ratio

### Auto
- **SIAM monthly data**: https://www.siam.in/statistics.aspx (wholesale dispatches)
- **FADA monthly data**: https://www.fada.in/ (retail registrations — more reliable than SIAM)
- **VAHAN dashboard**: https://vahan.parivahan.gov.in/vahan4dashboard/ (registration data)

### IT Services
- **NASSCOM**: https://nasscom.in/ — industry reports
- **Peer concalls**: TCS/Infosys/HCL Tech guide for the sector — their commentary is sector read
- Key metrics: deal TCV, headcount, attrition, utilization, constant currency growth

### Pharma
- **USFDA**: https://www.fda.gov/ — search for Form 483, Warning Letters, Import Alert
- **DCGI / CDSCO**: https://cdsco.gov.in/ — Indian drug regulator
- **ANDA approvals**: https://www.accessdata.fda.gov/scripts/cder/daf/
- Key metrics: US revenue %, ANDA pipeline, R&D as % of sales, API vs formulations mix

### Cement
- **Company monthly dispatches**: most large players disclose monthly volumes
- **ICRA cement reports**: quarterly
- Key metrics: realization per tonne, cost per tonne, capacity utilization, clinker ratio

### Oil & Gas (refining, petchem, E&P)
- **Singapore GRM**: proxy for India refining margins — search `Singapore GRM` weekly
- **Brent-Dubai spread**: impacts Indian refiner margins vs global benchmarks
- **Petchem spreads**: polymer/polyester delta — search `{product} spread Asia`
- **Ministry of Petroleum**: https://www.ppac.gov.in/ — petroleum planning & analysis cell
- **Gas pricing**: APM gas price notification (revised semi-annually by govt)

### Telecom (relevant for Reliance Jio)
- **TRAI data**: https://www.trai.gov.in/ — subscriber data, ARPU, monthly reports
- **COAI**: https://coai.com/ — industry body data
- Key metrics: subscriber adds, ARPU, data usage per subscriber, tower sharing revenue

### Retail (relevant for Reliance Retail)
- **RAI (Retailers Association of India)**: sentiment surveys
- Key metrics: revenue per sqft, same-store sales growth, store count, footfall
- Compare with: DMart (DMART), Trent (TRENT), V-Mart, Shoppers Stop

### Real Estate
- **ANAROCK / Knight Frank / JLL**: quarterly reports on absorption, launches, pricing
- **RERA portals**: state-wise project registrations

### Power & Energy
- **CEA daily reports**: https://cea.nic.in/ — generation, PLF data
- **IEX (Indian Energy Exchange)**: spot power prices
- **MNRE**: https://mnre.gov.in/ — renewable energy capacity additions

---

## 9. Macro indicators (scan weekly, not daily)

- **RBI press releases & MPC minutes**: https://www.rbi.org.in/
- **Budget documents**: https://www.indiabudget.gov.in/
- **MOSPI GDP data**: https://mospi.gov.in/
- **CMIE**: economic indicators (unemployment, consumer sentiment, capex data)
- **PMI Manufacturing & Services**: released first week of each month
- **GST collection data**: released monthly by Finance Ministry (proxy for economic activity)
- **Auto sales data**: released by 1st-2nd of each month (early economic indicator)
- **Core sector output (IIP)**: 8 core industries data — released monthly

---

## 10. Search query templates (copy-paste ready)

### Daily scan per stock
```
"{COMPANY_NAME}" news today
"{TICKER}" NSE announcement
"{COMPANY_NAME}" SEBI
"{COMPANY_NAME}" results OR earnings
"{COMPANY_NAME}" promoter pledge OR holding
"{COMPANY_NAME}" block deal OR bulk deal
```

### Weekly deep scan per stock
```
"{COMPANY_NAME}" credit rating
"{COMPANY_NAME}" auditor
"{COMPANY_NAME}" forensic OR fraud OR whistleblower
"{COMPANY_NAME}" ED OR CBI OR "income tax" raid
"{COMPANY_NAME}" shareholding pattern
"{COMPANY_NAME}" related party transaction
```

### Sector scan
```
"{SECTOR}" India outlook 2026
RBI policy impact {SECTOR}
"{SECTOR}" India regulatory change
```


path: state/last-run.json
content: {
  "last_run_date": null,
  "alerts_sent": [],
  "data_quality_flags": [],
  "results_calendar": [],
  "surveillance_check": {
    "last_checked": null,
    "next_due": null,
    "active_entries": []
  },
  "watch_list_for_followup": [],
  "guidance_tracker": {},
  "promoter_holding_history": {},
  "institutional_holding_history": {},
  "management_credibility": {}
}


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (HIGH)