--- name: stock-analysis description: Analyze stocks and cryptocurrencies using LongPort (primary, HK/US/CN) + Yahoo Finance (fallback, US only) data. Supports 8-dimension stock scoring, portfolio management, watchlists with alerts, dividend analysis, viral trend detection (Hot Scanner), and rumor/early signal detection. Use for stock analysis, portfolio tracking, earnings reactions, crypto monitoring, trending stocks, or finding rumors before they go mainstream. Includes unified data layer with graceful Yahoo fallback. version: 6.4.0 homepage: https://finance.yahoo.com commands: - /stock - Analyze a stock or crypto (e.g., /stock AAPL) - /stock_compare - Compare multiple tickers - /stock_dividend - Analyze dividend metrics - /stock_watch - Add/remove from watchlist - /stock_alerts - Check triggered alerts - /stock_hot - Find trending stocks & crypto (Hot Scanner) - /stock_rumors - Find early signals, M&A rumors, insider activity (Rumor Scanner) - /portfolio - Show portfolio summary - /portfolio_add - Add asset to portfolio metadata: {"clawdbot":{"emoji":"๐Ÿ“ˆ","requires":{"bins":["uv"],"env":[]},"install":[{"id":"uv-brew","kind":"brew","formula":"uv","bins":["uv"],"label":"Install uv (brew)"}]}} --- # Stock Analysis v6.3 Analyze US stocks and cryptocurrencies with **LongPort (primary) + Yahoo Finance (fallback)** data sources. ## What's New in v6.4 - ๐Ÿ†• **DCA Ladder Monitoring** โ€” Automated buy signals when prices hit ladder tiers - Position config JSON with 3-tier price ladders + lot sizes - Monitor script checks prices vs targets, silent when no triggers - 5 cron jobs: HK market 2x/day, US market 2x/day, daily morning brief - Status tracking: mark tiers as "done" after purchase - See `references/dca-ladder-monitoring.md` - ๐Ÿ†• **Autonomous workflow** โ€” Full analysis pipeline runs without asking user permission - ๐Ÿ†• **DCA 6-dimension scoring** โ€” Yield + PE + PB + Price Position + YTD Dip + Safety - See `references/dca-screener.md` ## What's New in v6.3 - ๐Ÿ†• **LongPort Data Source** โ€” Primary data for HK/US/CN stocks - Real-time quotes, PE, PB, EPS, BPS, dividend yield - Market cap, turnover rate, volume ratio - Full Hong Kong and A-share coverage - ๐Ÿ†• **Unified Data Layer** โ€” `data_source.py` merges LongPort + Yahoo - LongPort: valuation metrics, realtime quotes - Yahoo: operating margins, ROE, analyst data, earnings history - ๐Ÿ†• **Valuation Analysis** โ€” `analyze_stock_unified.py` - PE/PB/Dividend scoring (-1 to +1) - Weighted overall score - BUY/HOLD/SELL recommendations ## What's New in v6.2 - ๐Ÿ”ฎ **Rumor Scanner** โ€” Early signals before mainstream news - M&A rumors and takeover bids - Insider buying/selling activity - Analyst upgrades/downgrades - Twitter/X "hearing that...", "sources say..." detection - ๐ŸŽฏ **Impact Scoring** โ€” Rumors ranked by potential market impact ## What's in v6.1 - ๐Ÿ”ฅ **Hot Scanner** โ€” Find viral stocks & crypto across multiple sources - ๐Ÿฆ **Twitter/X Integration** โ€” Social sentiment via bird CLI - ๐Ÿ“ฐ **Multi-Source Aggregation** โ€” CoinGecko, Google News, Yahoo Finance - โฐ **Cron Support** โ€” Daily trend reports ## What's in v6.0 - ๐Ÿ†• **Watchlist + Alerts** โ€” Price targets, stop losses, signal changes - ๐Ÿ†• **Dividend Analysis** โ€” Yield, payout ratio, growth, safety score - ๐Ÿ†• **Fast Mode** โ€” `--fast` skips slow analyses (insider, news) - ๐Ÿ†• **Improved Performance** โ€” `--no-insider` for faster runs ## Quick Commands ### Valuation Analysis (NEW v6.3) โ€” LongPort Primary + 8-Dimension Scoring ```bash # Single stock valuation uv run {baseDir}/scripts/analyze_stock_unified.py O # Multiple stocks comparison uv run {baseDir}/scripts/analyze_stock_unified.py O 823.HK MAIN JEPI NLY # Hong Kong stocks uv run {baseDir}/scripts/analyze_stock_unified.py 823.HK 778.HK 0405.HK # Fast mode (skip slow analyses) uv run {baseDir}/scripts/analyze_stock_unified.py O --fast # JSON output uv run {baseDir}/scripts/analyze_stock_unified.py O --output json ``` **8-Dimension Scoring System:** - Fundamentals (40%): PE, PB, dividend yield, margins, ROE, debt - Valuation (30%): PE/PB/dividend relative to thresholds - Momentum (20%): RSI, volume ratio, price change - Market Cap (10%): Large-cap stability vs small-cap risk **Recommendation Thresholds:** - Score > 0.3: BUY (High confidence) - Score > 0.0: BUY (Moderate confidence) - Score > -0.3: HOLD - Score < -0.3: SELL ### Legacy Analysis (Yahoo Finance) ```bash # Basic analysis uv run {baseDir}/scripts/analyze_stock.py AAPL # Fast mode (skips insider trading & breaking news) uv run {baseDir}/scripts/analyze_stock.py AAPL --fast # Compare multiple uv run {baseDir}/scripts/analyze_stock.py AAPL MSFT GOOGL # Crypto uv run {baseDir}/scripts/analyze_stock.py BTC-USD ETH-USD ``` ### Dividend Analysis (NEW v6.0) ```bash # Analyze dividends uv run {baseDir}/scripts/dividends.py JNJ # Compare dividend stocks uv run {baseDir}/scripts/dividends.py JNJ PG KO MCD --output json ``` **Dividend Metrics:** - Dividend Yield & Annual Payout - Payout Ratio (safe/moderate/high/unsustainable) - 5-Year Dividend Growth (CAGR) - Consecutive Years of Increases - Safety Score (0-100) - Income Rating (excellent/good/moderate/poor) ### Watchlist + Alerts (NEW v6.0) ```bash # Add to watchlist uv run {baseDir}/scripts/watchlist.py add AAPL # With price target alert uv run {baseDir}/scripts/watchlist.py add AAPL --target 200 # With stop loss alert uv run {baseDir}/scripts/watchlist.py add AAPL --stop 150 # Alert on signal change (BUYโ†’SELL) uv run {baseDir}/scripts/watchlist.py add AAPL --alert-on signal # View watchlist uv run {baseDir}/scripts/watchlist.py list # Check for triggered alerts uv run {baseDir}/scripts/watchlist.py check uv run {baseDir}/scripts/watchlist.py check --notify # Telegram format # Remove from watchlist uv run {baseDir}/scripts/watchlist.py remove AAPL ``` **Alert Types:** - ๐ŸŽฏ **Target Hit** โ€” Price >= target - ๐Ÿ›‘ **Stop Hit** โ€” Price <= stop - ๐Ÿ“Š **Signal Change** โ€” BUY/HOLD/SELL changed ### Portfolio Management ```bash # Create portfolio uv run {baseDir}/scripts/portfolio.py create "Tech Portfolio" # Add assets uv run {baseDir}/scripts/portfolio.py add AAPL --quantity 100 --cost 150 uv run {baseDir}/scripts/portfolio.py add BTC-USD --quantity 0.5 --cost 40000 # View portfolio uv run {baseDir}/scripts/portfolio.py show # Analyze with period returns uv run {baseDir}/scripts/analyze_stock.py --portfolio "Tech Portfolio" --period weekly ``` ### ๐Ÿ”ฅ Hot Scanner (NEW v6.1) ```bash # Full scan - find what's trending NOW python3 {baseDir}/scripts/hot_scanner.py # Fast scan (skip social media) python3 {baseDir}/scripts/hot_scanner.py --no-social # JSON output for automation python3 {baseDir}/scripts/hot_scanner.py --json ``` **Data Sources:** - ๐Ÿ“Š CoinGecko Trending โ€” Top 15 trending coins - ๐Ÿ“ˆ CoinGecko Movers โ€” Biggest gainers/losers - ๐Ÿ“ฐ Google News โ€” Finance & crypto headlines - ๐Ÿ“‰ Yahoo Finance โ€” Gainers, losers, most active - ๐Ÿฆ Twitter/X โ€” Social sentiment (requires auth) **Output:** - Top trending by mention count - Crypto highlights with 24h changes - Stock movers by category - Breaking news with tickers **Twitter Setup (Optional):** 1. Install bird: `npm install -g @steipete/bird` 2. Login to x.com in Safari/Chrome 3. Create `.env` with `AUTH_TOKEN` and `CT0` ### ๐Ÿ”ฎ Rumor Scanner (NEW v6.2) ```bash # Find early signals, M&A rumors, insider activity python3 {baseDir}/scripts/rumor_scanner.py ``` **What it finds:** - ๐Ÿข **M&A Rumors** โ€” Merger, acquisition, takeover bids - ๐Ÿ‘” **Insider Activity** โ€” CEO/Director buying/selling - ๐Ÿ“Š **Analyst Actions** โ€” Upgrades, downgrades, price target changes - ๐Ÿฆ **Twitter Whispers** โ€” "hearing that...", "sources say...", "rumor" - โš–๏ธ **SEC Activity** โ€” Investigations, filings **Impact Scoring:** - Each rumor is scored by potential market impact (1-10) - M&A/Takeover: +5 points - Insider buying: +4 points - Upgrade/Downgrade: +3 points - "Hearing"/"Sources say": +2 points - High engagement: +2 bonus **Best Practice:** Run at 07:00 before US market open to catch pre-market signals. ## Analysis Dimensions (8 for stocks, 3 for crypto) ### Stocks | Dimension | Weight | Description | |-----------|--------|-------------| | Earnings Surprise | 30% | EPS beat/miss | | Fundamentals | 20% | P/E, margins, growth | | Analyst Sentiment | 20% | Ratings, price targets | | Historical | 10% | Past earnings reactions | | Market Context | 10% | VIX, SPY/QQQ trends | | Sector | 15% | Relative strength | | Momentum | 15% | RSI, 52-week range | | Sentiment | 10% | Fear/Greed, shorts, insiders | ### Crypto - Market Cap & Category - BTC Correlation (30-day) - Momentum (RSI, range) ## Sentiment Sub-Indicators | Indicator | Source | Signal | |-----------|--------|--------| | Fear & Greed | CNN | Contrarian (fear=buy) | | Short Interest | Yahoo | Squeeze potential | | VIX Structure | Futures | Stress detection | | Insider Trades | SEC EDGAR | Smart money | | Put/Call Ratio | Options | Sentiment extreme | ## Risk Detection - โš ๏ธ **Pre-Earnings** โ€” Warns if < 14 days to earnings - โš ๏ธ **Post-Spike** โ€” Flags if up >15% in 5 days - โš ๏ธ **Overbought** โ€” RSI >70 + near 52w high - โš ๏ธ **Risk-Off** โ€” GLD/TLT/UUP rising together - โš ๏ธ **Geopolitical** โ€” Taiwan, China, Russia, Middle East keywords - โš ๏ธ **Breaking News** โ€” Crisis keywords in last 24h ## Performance Options | Flag | Effect | Speed | |------|--------|-------| | (default) | Full analysis | 5-10s | | `--no-insider` | Skip SEC EDGAR | 3-5s | | `--fast` | Skip insider + news | 2-3s | ## Supported Cryptos (Top 20) BTC, ETH, BNB, SOL, XRP, ADA, DOGE, AVAX, DOT, MATIC, LINK, ATOM, UNI, LTC, BCH, XLM, ALGO, VET, FIL, NEAR (Use `-USD` suffix: `BTC-USD`, `ETH-USD`) ## Data Storage | File | Location | |------|----------| | Portfolios | `~/.clawdbot/skills/stock-analysis/portfolios.json` | | Watchlist | `~/.clawdbot/skills/stock-analysis/watchlist.json` | ## Data Source Architecture (v6.3) **Primary:** LongPort SDK โ€” PE, PB, EPS, BPS, dividend yield, market cap, realtime quotes, HK/CN coverage **Fallback:** Yahoo Finance โ€” operating margins, ROE, debt ratios, analyst data, earnings history ### Files | File | Purpose | |------|---------| | `scripts/data_source.py` | Unified data layer: LongPort primary + Yahoo fallback | | `scripts/analyze_stock_unified.py` | 8-dimension analysis using unified data source | | `scripts/analyze_stock.py` | Original Yahoo-only analysis (unchanged) | | `references/valuation-quickstart.md` | Quick reference for valuation commands | | `references/dca-ladder-monitoring.md` | DCA ladder monitoring: config, script, cron setup | ### Yahoo Fallback Pattern Yahoo data is **optional** โ€” if it fails (rate limiting, timeout), LongPort data alone is sufficient for core analysis. The `merge_data()` function handles this gracefully: - LongPort fails โ†’ use Yahoo - Yahoo fails โ†’ use LongPort only - Both fail โ†’ return None - Analysis functions return None on error โ†’ skipped in scoring **User preference:** Yahoo data failures must NEVER block the overall analysis. Always degrade gracefully. **User preference:** Do NOT simplify scoring systems. The 8-dimension scoring (earnings, fundamentals, analysts, historical, market context, sector, momentum, sentiment) must be preserved. Simple PE/PB/dividend scoring is insufficient โ€” users want the full framework. ### DCA Screening (้˜ถๆขฏๅผไนฐๅ…ฅ) โ€” High Dividend Candidates ```bash # Uses calc_indexes with 5-dimension scoring: yield + PE + PB + volatility + YTD dip # See references/dca-screening.md for full candidate list and scoring framework ``` ## DCA (Dollar-Cost Averaging / ้˜ถๆขฏๅผไนฐๅ…ฅ) Screener When user asks about DCA, ้˜ถๆขฏๅผไนฐๅ…ฅ, ๅˆ†ๆ‰นๅปบไป“, or drip-feeding into stocks: 1. **Screen candidates** via LongPort `calc_indexes` with `DividendRatioTtm` + `TotalMarketValue` + `PeTtmRatio` + `PbRatio` (see `references/dca-screener.md`) 2. **Score with 6-dimension DCA model** (different from the 8-dimension earnings model): - Dividend yield (25pts) โ€” higher = better - PE valuation (20pts) โ€” sweet spot 5-12 - PB value (15pts) โ€” below 1 is great - Price position in 60-day range (15pts) โ€” lower = better entry - YTD drawdown (15pts) โ€” negative = buying opportunity - Safety/sustainability (10pts) โ€” profitable + asset-backed + reasonable yield 3. **Generate price ladder**: 3 tiers โ€” current price, 20-day support, 60-day low ร— 0.98 4. **Present visually**: emoji grades (๐Ÿ”ฅโ‰ฅ70, โญโ‰ฅ55, โœ…<55), table format See `references/dca-screener.md` for the full scoring methodology and script template. ## DCA Ladder Monitoring (้˜ถๆขฏไนฐๅ…ฅ่‡ชๅŠจ็›‘ๆŽง) After screening DCA candidates, set up automated price monitoring: config JSON โ†’ monitor script โ†’ cron jobs. When prices hit ladder tiers, push buy signals with exact share counts. Full workflow: `references/dca-ladder-monitoring.md` ``` ~/.hermes/scripts/dca_positions.json โ† positions + ladder + budget ~/.hermes/scripts/dca_monitor.py โ† price checker (silent when no triggers) cron jobs (5x) โ† HK 10:00+15:00, US 22:30+02:00, ๆ™จๆŠฅ 9:00 ``` Key interactions: "ๆˆ‘ไนฐไบ†XX T1" โ†’ mark tier done | "่ฐƒๆ•ดไปทไฝ" โ†’ edit JSON | "ๅŠ ไธ€ๅช" โ†’ add position | "่ฎพ็ฝฎ้ข„็ฎ—" โ†’ recalc lots | "ๆš‚ๅœDCA" โ†’ pause crons ## Workflow Preference **CRITICAL โ€” Autonomous analysis**: When user asks to analyze stocks, screen candidates, or find DCA targets, DO the full analysis immediately. Do NOT ask "should I run X?" or "want me to check Y?". User explicitly corrected: "ไฝ ่ฆ่‡ชไธปๅŽปๅˆ†ๆž๏ผŒๆˆ‘็š„้ฃŽๆ ผไฝ ็Ÿฅ้“ไบ†ๅ˜›๏ผŸ". This means: run screens, pull data from LongPort, score, generate price ladders, present results โ€” all in one shot. Only clarify if genuinely ambiguous (which market? which budget?). The user expects proactive execution, not permission-seeking. ## Pitfalls - **Yahoo data fault tolerance**: Yahoo Finance frequently rate-limits or fails. The unified data layer (`data_source.py`, `analyze_stock_unified.py`) treats LongPort as primary and Yahoo as optional supplement. If Yahoo fails, analysis MUST still complete with LongPort data only. Never let a Yahoo failure block or crash the analysis. Each Yahoo-dependent field (operating_margin, roe, analyst ratings, earnings_history) is optional โ€” check for None before using. - **Keep full 8-dimension scoring**: User explicitly requires the full 8-dimension scoring system (Earnings, Fundamentals, Analysts, Historical, Market Context, Sector, Momentum, Sentiment). Do NOT simplify to PE/PB/dividend-only scoring. Simple scoring is insufficient โ€” users want the full framework. - **Decimal conversion**: LongPort returns `decimal.Decimal` for market_cap and some fields. Always `float()` before arithmetic. - **uv not available**: If `uv run` fails with "command not found", install via `curl -LsSf https://astral.sh/uv/install.sh | sh` or fall back to `python3` directly with `pip3 install yfinance requests`. The analyze_stock_unified.py script needs uv; analyze_stock.py can run with plain python3 if yfinance is installed. - **Yahoo Finance dead tickers**: Some tickers (especially BDCs, mREITs, small caps) fail on Yahoo Finance with "Invalid ticker or data unavailable". Always have LongPort as primary fallback โ€” write a direct LongPort script if the unified scripts fail. - **uv not installed**: All `uv run` scripts require `uv`. Install: `curl -LsSf https://astral.sh/uv/install.sh | sh`. - **HK stocks incomplete on Yahoo**: Yahoo Finance coverage for HK stocks is spotty. For HK analysis, LongPort is primary. - **Symbol format**: LongPort needs `TICKER.US` or `CODE.HK`. The data layer auto-converts bare tickers like `O` to `O.US`. - **Monthly dividend stocks**: User frequently asks about monthly dividend stocks (US + HK). See `references/monthly-dividend-stocks.md`. ## Limitations - Yahoo Finance may lag 15-20 minutes - Short interest lags ~2 weeks (FINRA) - Insider trades lag 2-3 days (SEC filing) - US markets only (non-US incomplete) - Breaking news: 1h cache, keyword-based ## Disclaimer โš ๏ธ **NOT FINANCIAL ADVICE.** For informational purposes only. Consult a licensed financial advisor before making investment decisions.