Initial commit: Hermes Agent skills collection
- Trading skills (OKX, dividend, lottery, quantitative) - Creative skills (ASCII art, diagrams, video) - Development skills (GitHub, debugging, TDD) - Research skills (arXiv, blog monitoring) - Productivity skills (email, documents, notes) - MCP integration skills - Custom user skills
This commit is contained in:
@@ -0,0 +1,160 @@
|
||||
# DCA Ladder Monitoring — 阶梯买入自动监控
|
||||
|
||||
After screening candidates (see `dca-screener.md`), set up automated price monitoring so the user gets buy signals when prices hit ladder tiers.
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
dca_positions.json ← config (symbols, ladder prices, budget, status)
|
||||
↓
|
||||
dca_monitor.py ← reads config + fetches prices from LongPort
|
||||
↓
|
||||
cron jobs ← runs monitor on schedule, delivers alerts
|
||||
```
|
||||
|
||||
## Step 1: Create Position Config
|
||||
|
||||
File: `~/.hermes/scripts/dca_positions.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"updated": "YYYY-MM-DD",
|
||||
"positions": {
|
||||
"SYMBOL.US": {
|
||||
"name": "Display Name",
|
||||
"yield": 10.5,
|
||||
"market": "US",
|
||||
"ladder": [
|
||||
{"tier": 1, "price": 15.28, "alloc_pct": 40, "status": "pending", "shares": 3, "cost_local": 45.84},
|
||||
{"tier": 2, "price": 15.07, "alloc_pct": 30, "status": "pending", "shares": 2, "cost_local": 30.14},
|
||||
{"tier": 3, "price": 13.03, "alloc_pct": 30, "status": "pending", "shares": 3, "cost_local": 39.09}
|
||||
],
|
||||
"monthly_budget_hkd": 1071,
|
||||
"monthly_budget_local": 137,
|
||||
"notes": "PE8.5 科技BDC龙头"
|
||||
}
|
||||
},
|
||||
"budget": {
|
||||
"monthly_min_hkd": 6000,
|
||||
"monthly_max_hkd": 9000,
|
||||
"monthly_mid_hkd": 7500,
|
||||
"per_stock_hkd": 1071,
|
||||
"usd_hkd": 7.80
|
||||
},
|
||||
"alert_settings": {
|
||||
"trigger_pct": 2.0,
|
||||
"cooldown_hours": 24
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Lot Calculation
|
||||
|
||||
Given monthly budget M and N stocks:
|
||||
- `per_stock = M / N` (in HKD)
|
||||
- For US stocks: `per_stock_local = per_stock / USDHKD`
|
||||
- Per tier: `shares = floor(tier_budget / price)` where `tier_budget = per_stock_local * alloc_pct / 100`
|
||||
- Update JSON with `shares`, `cost_local`, `cost_hkd` fields
|
||||
|
||||
### Status Tracking
|
||||
|
||||
When user confirms a purchase:
|
||||
- Change `status` from `"pending"` to `"done"` in the ladder entry
|
||||
- This prevents re-alerting on already-purchased tiers
|
||||
|
||||
## Step 2: Monitor Script
|
||||
|
||||
File: `~/.hermes/scripts/dca_monitor.py`
|
||||
|
||||
Key logic:
|
||||
1. Load env vars from `~/.bashrc` (LONGBRIDGE_* → LONGPORT_*)
|
||||
2. Load `dca_positions.json`
|
||||
3. Fetch current prices via `ctx.quote(symbols)` in batches of 15
|
||||
4. For each position, compare price to each pending ladder tier
|
||||
5. If `current_price <= target * (1 + trigger_pct/100)`: emit alert
|
||||
6. If no alerts triggered: output empty (silent — no notification sent)
|
||||
|
||||
### Alert Format
|
||||
|
||||
```
|
||||
🔔 DCA买入信号 [YYYY-MM-DD HH:MM]
|
||||
|
||||
🚨 🇺🇸 HTGC.US Hercules Capital
|
||||
第1档目标: 15.28 现价: 15.20 已触达
|
||||
建议仓位: 40% 买入: 3股 股息率: 10.5%
|
||||
|
||||
🟡 🇺🇸 NLY.US Annaly Capital
|
||||
第2档目标: 21.07 现价: 21.22 差0.7%
|
||||
建议仓位: 30% 买入: 1股 股息率: 13.2%
|
||||
```
|
||||
|
||||
### Pitfalls
|
||||
|
||||
- **SecurityQuote attribute**: `SecurityQuote` may not have `change_rate` on some data tiers. Use `CalcIndex.ChangeRate` via `calc_indexes` instead.
|
||||
- **Price=0 on weekends**: LongPort returns 0 for `last_done` when markets are closed. The monitor will trigger all alerts on weekends — either skip weekends in cron schedule or handle in script.
|
||||
- **HK stock codes in python3 -c**: Codes like `0728.HK` start with digits. Always write scripts to file, never use `python3 -c`.
|
||||
- **Batch sizes**: quote 15/batch, calc_indexes 10/batch, static_info 20/batch.
|
||||
|
||||
## Step 3: Cron Jobs
|
||||
|
||||
Set up 5 jobs (all Beijing time):
|
||||
|
||||
| Schedule | Name | Purpose |
|
||||
|----------|------|---------|
|
||||
| `0 9 * * 1-6` | DCA每日晨报 | AI-driven summary with all positions status |
|
||||
| `0 10 * * 1-5` | DCA港股盘中(上午) | HK market check (1hr after open) |
|
||||
| `0 15 * * 1-5` | DCA港股盘中(下午) | HK market check (1hr before close) |
|
||||
| `30 22 * * 1-5` | DCA美股盘中(晚间) | US market check (30min after open) |
|
||||
| `0 2 * * 2-6` | DCA美股盘中(凌晨) | US market check (mid-session) |
|
||||
|
||||
### Cron Setup Pattern
|
||||
|
||||
**Script-only jobs** (no agent, just run monitor):
|
||||
```python
|
||||
cronjob(action='create', name='DCA港股盘中监控',
|
||||
schedule='0 10 * * 1-5', no_agent=True,
|
||||
script='scripts/dca_monitor.py', deliver='origin')
|
||||
```
|
||||
|
||||
**AI-driven daily summary** (with agent for richer formatting):
|
||||
```python
|
||||
cronjob(action='create', name='DCA每日晨报',
|
||||
schedule='0 9 * * 1-6',
|
||||
prompt='Run dca_monitor.py, generate morning brief...',
|
||||
enabled_toolsets=['terminal'], deliver='origin')
|
||||
```
|
||||
|
||||
## Step 4: User Interaction Commands
|
||||
|
||||
After deployment, user may say:
|
||||
|
||||
| User Says | Action |
|
||||
|-----------|--------|
|
||||
| "我买了XX T1" | Edit JSON: set tier status to `"done"` |
|
||||
| "调整XX阶梯价位" | Edit JSON: update ladder prices |
|
||||
| "设置预算XX万" | Recalculate lot sizes, update JSON |
|
||||
| "加一只XX" | Add new position to JSON |
|
||||
| "暂停DCA监控" | Pause cron jobs |
|
||||
| "DCA状态" | Run monitor script, show all positions |
|
||||
|
||||
## Full Script Template
|
||||
|
||||
See `~/.hermes/scripts/dca_monitor.py` for the production script.
|
||||
|
||||
Key env loading pattern (required for all LongPort scripts):
|
||||
```python
|
||||
import os, re
|
||||
env_vars = {}
|
||||
with open(os.path.expanduser('~/.bashrc')) as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if line.startswith('export LONGBRIDGE_') or line.startswith('export LONGPORT_'):
|
||||
parts = line.replace('export ', '').split('=', 1)
|
||||
if len(parts) == 2:
|
||||
env_vars[parts[0]] = parts[1]
|
||||
for key, val in env_vars.items():
|
||||
if '${' not in val: os.environ[key] = val
|
||||
for key, val in env_vars.items():
|
||||
if '${' in val:
|
||||
os.environ[key] = re.sub(r'\$\{(\w+)\}', lambda m: os.environ.get(m.group(1), ''), val)
|
||||
```
|
||||
@@ -0,0 +1,82 @@
|
||||
# DCA Screener — 阶梯式买入筛选器
|
||||
|
||||
When user asks about 阶梯式买入 / DCA / 分批建仓 / drip-feeding into dividend stocks.
|
||||
|
||||
## Scoring Model (6 Dimensions, 100 points total)
|
||||
|
||||
| Dimension | Weight | Logic |
|
||||
|-----------|--------|-------|
|
||||
| Dividend Yield | /25 | ≥15%→25, ≥10%→22, ≥7%→18, ≥5%→15, ≥3%→10, <3%→3 |
|
||||
| PE (sweet spot 5-12) | /20 | <5→15, <8→20(best), <12→18, <15→14, <20→10, ≥20→5, negative→3 |
|
||||
| PB (below 1 is great) | /15 | <0.5→15, <0.8→13, <1.0→11, <1.5→8, <2.0→5, ≥2→3 |
|
||||
| Price Position (60d) | /15 | <20%→15(best), <35%→12, <50%→10, <65%→7, <80%→4, ≥80→2 |
|
||||
| YTD Drawdown | /15 | <-15%→15, <-10→13, <-5→11, <0→9, <10→6, ≥10→3 |
|
||||
| Safety | /10 | profitable(+3), PB<1.5(+3), yield 3-15%(+4) |
|
||||
|
||||
Grades: 🔥 ≥70 (strong buy) | ⭐ ≥55 (recommended) | ✅ <55 (moderate)
|
||||
|
||||
## Price Ladder Calculation
|
||||
|
||||
```
|
||||
tier1 = current_price # Current level, buy 40%
|
||||
tier2 = 20day_support # Recent support, buy 30%
|
||||
tier3 = 60day_low × 0.98 # Below period low, buy 30%
|
||||
```
|
||||
|
||||
## Candidate Universe
|
||||
|
||||
### US — BDCs (Business Development Companies)
|
||||
ARCC, HTGC, MAIN, GAIN, GLAD, PSEC, FSK, HRZN, TSLX
|
||||
|
||||
### US — mREITs (Mortgage REITs)
|
||||
NLY, AGNC, ARR, DX, NYMT, CIM, ORC
|
||||
|
||||
### US — Equity REITs
|
||||
O, VICI, WPC, SPG
|
||||
|
||||
### US — Blue Chip Dividend
|
||||
MO, VZ, T, XOM, CVX, BTI, PG, JNJ, KO, PEP, ABBV
|
||||
|
||||
### US — MLP/Energy
|
||||
ET, EPD, MPLX, USAC
|
||||
|
||||
### US — Covered Call ETFs
|
||||
JEPI, JEPQ, QYLD, SPYI, DIVO, SVOL
|
||||
|
||||
### US — Utilities
|
||||
NEE, DUK, SO, D
|
||||
|
||||
### HK — High Dividend Blue Chips
|
||||
1088.HK (神华), 0883.HK (中海油), 3968.HK (招行), 2318.HK (平安),
|
||||
0939.HK (建行), 1398.HK (工行), 3988.HK (中行), 0005.HK (汇丰),
|
||||
0003.HK (中煤气), 0011.HK (恒生), 0002.HK (中电), 0006.HK (电能),
|
||||
0016.HK (新地), 0012.HK (恒基), 0388.HK (港交所), 1299.HK (友邦),
|
||||
0267.HK (中信), 0066.HK (港铁), 0857.HK (中石油), 0728.HK (中国电信)
|
||||
|
||||
### HK — High-Yield ETFs
|
||||
3416.HK (AGX国指兑), 3417.HK (AGX恒科备兑)
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- **mREIT rate sensitivity**: NLY/AGNC/DX are heavily influenced by Fed rate policy. In rate-cutting cycles, they outperform; in tightening cycles, dividends may be cut.
|
||||
- **BDC credit risk**: BDCs lend to mid-market companies. During recessions, default rates rise and NAV can decline.
|
||||
- **HK bank property exposure**: HK bank stocks (招行/工行/中行) have real estate exposure. Valuations may already reflect property market stress.
|
||||
- **PE negative = red flag**: Stocks with negative PE (some BDCs like FSK, PSEC) may have unsustainable dividends despite high headline yields.
|
||||
- **YTD hot stocks penalized**: Stocks with YTD > +20% (like 0883.HK +25%, 0857.HK +26%) score lower on DCA because they're less attractive for new money entry.
|
||||
- **Price=0 on weekends**: LongPort returns 0 for last_done when markets are closed. Use calc_indexes data (PE/PB/yield) which are always available.
|
||||
- **LongPort Quote object**: `SecurityQuote` does NOT have `change_rate` attribute on some market data tiers. Use `calc_indexes` with `CalcIndex.ChangeRate` instead.
|
||||
|
||||
## Script Template
|
||||
|
||||
Save as `/tmp/dca_screen.py` (never use `python3 -c` with HK stock codes starting with digits).
|
||||
|
||||
Key script pattern:
|
||||
```python
|
||||
# 1. Load env from bashrc (LONGBRIDGE_* → LONGPORT_*)
|
||||
# 2. ctx.calc_indexes(candidates, [DividendRatioTtm, PeTtmRatio, PbRatio, TotalMarketValue, ...])
|
||||
# 3. ctx.candlesticks(sym, Period.Day, 60, AdjustType.ForwardAdjust) for price ladder
|
||||
# 4. ctx.static_info(syms) for names
|
||||
# 5. Score + sort + present
|
||||
```
|
||||
|
||||
Batch sizes: quotes 20/batch, calc_indexes 10/batch, static_info 20/batch.
|
||||
@@ -0,0 +1,162 @@
|
||||
# DCA Screening (阶梯式买入) — High Dividend Candidates
|
||||
|
||||
Find stocks suitable for dollar-cost averaging (laddered buying) with high dividend yields. Combines LongPort data with weighted scoring.
|
||||
|
||||
**Last reviewed**: 2026-06-07
|
||||
|
||||
---
|
||||
|
||||
## DCA Scoring Framework
|
||||
|
||||
5-dimension weighted score (0-100) optimized for **income + value + stability**:
|
||||
|
||||
| Dimension | Weight | Ideal | Logic |
|
||||
|-----------|--------|-------|-------|
|
||||
| Dividend Yield | 30% | >10% | Higher = more income while DCA-ing; cap at 20% |
|
||||
| PE (TTM) | 20% | 5-15 | Sweet spot: cheap enough for value, not negative |
|
||||
| PB Ratio | 15% | <1.0 | Below book = margin of safety; <0.5 = deep value |
|
||||
| 5-Day Volatility | 15% | <3% | Low vol = smoother DCA entries, less timing risk |
|
||||
| YTD Drawdown | 20% | -5%~-15% | Pullback = better entry; too deep = fundamental risk |
|
||||
|
||||
```python
|
||||
def dca_score(r):
|
||||
score = 0
|
||||
# Yield (30%): higher = better, cap at 20%
|
||||
score += min(r['yield'] / 20.0, 1.0) * 30
|
||||
# PE (20%): sweet spot 5-15
|
||||
pe = r['pe']
|
||||
if pe is None or pe <= 0: score += 5 # negative = risky
|
||||
elif pe < 5: score += 15 # very cheap
|
||||
elif pe < 10: score += 20 # sweet spot
|
||||
elif pe < 15: score += 15
|
||||
elif pe < 20: score += 10
|
||||
else: score += 5
|
||||
# PB (15%): lower = better
|
||||
pb = r['pb']
|
||||
if pb is None: score += 5
|
||||
elif pb < 0.5: score += 15 # deep value
|
||||
elif pb < 1.0: score += 12 # below book
|
||||
elif pb < 1.5: score += 8
|
||||
else: score += 4
|
||||
# Volatility (15%): lower 5d change = better for DCA
|
||||
abs_5d = abs(r['five_d'])
|
||||
if abs_5d < 1: score += 15
|
||||
elif abs_5d < 3: score += 12
|
||||
elif abs_5d < 5: score += 8
|
||||
else: score += 4
|
||||
# YTD dip (20%): negative = better entry
|
||||
ytd = r['ytd']
|
||||
if ytd < -10: score += 20 # great entry
|
||||
elif ytd < -5: score += 15
|
||||
elif ytd < 0: score += 12
|
||||
elif ytd < 5: score += 8
|
||||
else: score += 4 # too hot
|
||||
return score
|
||||
```
|
||||
|
||||
## LongPort Data Fetching
|
||||
|
||||
```python
|
||||
from longport.openapi import CalcIndex
|
||||
|
||||
indexes = [
|
||||
CalcIndex.PeTtmRatio,
|
||||
CalcIndex.PbRatio,
|
||||
CalcIndex.DividendRatioTtm,
|
||||
CalcIndex.TotalMarketValue,
|
||||
CalcIndex.TurnoverRate,
|
||||
CalcIndex.FiveDayChangeRate,
|
||||
CalcIndex.YtdChangeRate,
|
||||
]
|
||||
|
||||
# Batch in groups of 10
|
||||
resp = ctx.calc_indexes(symbols, indexes)
|
||||
for item in resp:
|
||||
dy = float(item.dividend_ratio_ttm) if item.dividend_ratio_ttm else 0
|
||||
pe = float(item.pe_ttm_ratio) if item.pe_ttm_ratio else None
|
||||
pb = float(item.pb_ratio) if item.pb_ratio else None
|
||||
cap = float(item.total_market_value) if item.total_market_value else 0
|
||||
```
|
||||
|
||||
## Candidate Universe (2026-06 snapshot)
|
||||
|
||||
### 🇭🇰 Hong Kong — High Dividend Blue Chips
|
||||
|
||||
| Code | Name | Yield | PE | PB | Category |
|
||||
|------|------|-------|-----|-----|----------|
|
||||
| 3968.HK | 招商银行 | 6.9% | 7.1 | 0.95 | 银行 (破净) |
|
||||
| 2318.HK | 中国平安 | 5.4% | 6.8 | 0.89 | 保险 (破净) |
|
||||
| 0728.HK | 中国电信 | 6.1% | 12.7 | 0.86 | 电信 (央企) |
|
||||
| 1398.HK | 工商银行 | 5.1% | 5.8 | 0.55 | 银行 (破净) |
|
||||
| 0883.HK | 中海油 | 5.2% | 8.9 | 1.33 | 能源 |
|
||||
| 0267.HK | 中信股份 | 4.5% | 6.1 | 0.46 | 综合 (破净) |
|
||||
| 3988.HK | 中国银行 | ~5% | ~5 | ~0.5 | 银行 (破净) |
|
||||
| 0939.HK | 建设银行 | ~5% | ~5 | ~0.5 | 银行 (破净) |
|
||||
| 3416.HK | AGX国指兑 | 18.6% | N/A | N/A | 高息ETF (covered call) |
|
||||
| 3417.HK | AGX恒科备兑 | 18.8% | N/A | N/A | 高息ETF (covered call) |
|
||||
| 1088.HK | 中国神华 | 7.0% | 16.7 | 1.82 | 能源 (煤) |
|
||||
|
||||
**港股 DCA 特点**:
|
||||
- 银行股大面积破净(PB<1),适合长期收息
|
||||
- 央企分红稳定,但增长有限
|
||||
- 高息ETF(3416/3417)yield极高但属covered call策略,capital appreciation受限
|
||||
|
||||
### 🇺🇸 US — BDCs (Business Development Companies)
|
||||
|
||||
| Ticker | Name | Yield | PE | PB | Profile |
|
||||
|--------|------|-------|-----|-----|---------|
|
||||
| HTGC.US | Hercules Capital | 10.5% | 8.5 | 1.26 | 科技BDC龙头,YTD-14% |
|
||||
| ARCC.US | Ares Capital | 10.2% | 11.7 | 0.96 | 最大BDC,PB<1 |
|
||||
| MAIN.US | Main Street Capital | 5.9% | 11.3 | 1.56 | 月分红+补充分红 |
|
||||
| GAIN.US | Gladstone Investment | 6.2% | 3.3 | 0.91 | 小型BDC |
|
||||
| GLAD.US | Gladstone Capital | 9.3% | 10.2 | 0.90 | 收入型BDC |
|
||||
| HRZN.US | Horizon Technology | 25.4% | 14.6 | 0.94 | ⚠️ 高息但风险高 |
|
||||
| FSK.US | FS KKR Capital | 22.1% | -5.5 | 0.57 | ⚠️ PE为负,亏损 |
|
||||
| PSEC.US | Prospect Capital | 23.8% | -6.8 | 0.37 | ⚠️ PE为负,分红可持续性存疑 |
|
||||
|
||||
### 🇺🇸 US — mREITs (Mortgage REITs)
|
||||
|
||||
| Ticker | Name | Yield | PE | PB | Profile |
|
||||
|--------|------|-------|-----|-----|---------|
|
||||
| NLY.US | Annaly Capital | 13.2% | 7.7 | 1.07 | 最大agency mREIT |
|
||||
| AGNC.US | AGNC Investment | 14.2% | 9.0 | 1.14 | agency MBS |
|
||||
| ARR.US | Armour Residential | 16.8% | 9.3 | 0.91 | 住宅mREIT |
|
||||
| DX.US | Dynex Capital | 15.8% | 11.1 | 0.98 | 多元mREIT |
|
||||
|
||||
### 🇺🇸 US — Blue Chip Dividend
|
||||
|
||||
| Ticker | Name | Yield | PE | Profile |
|
||||
|--------|------|-------|-----|---------|
|
||||
| VICI.US | VICI Properties | 6.4% | 9.8 | 娱乐REIT,Triple-net |
|
||||
| T.US | AT&T | 4.9% | 7.5 | 电信,降息受益 |
|
||||
| MO.US | Altria Group | 5.8% | 15.0 | 烟草,稳定现金流 |
|
||||
| BTI.US | British American Tobacco | 5.3% | 12.6 | 国际烟草 |
|
||||
| XOM.US | Exxon Mobil | ~3.5% | ~14 | 能源巨头 |
|
||||
| O.US | Realty Income | 5.3% | 50.6 | 月分红REIT(PE偏高) |
|
||||
|
||||
### 🇺🇸 US — High Yield ETFs
|
||||
|
||||
| Ticker | Name | Yield | Strategy |
|
||||
|--------|------|-------|----------|
|
||||
| JEPI.US | JPMorgan Equity Premium Income | 8.3% | ELN + stock selection |
|
||||
| JEPQ.US | JPMorgan NASDAQ Equity Premium | 10.4% | NASDAQ版JEPI |
|
||||
| SPYI.US | Neos S&P 500 High Income | 11.9% | S&P 500 covered call |
|
||||
| QYLD.US | Global X NASDAQ 100 CC | 11.7% | ATM calls on QQQ |
|
||||
| SVOL.US | Simplify Volatility Premium | 22.3% | 波动率溢价 |
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- **⚠️ Ultra-high yield (>20%) = red flag**: HRZN/FSK/PSEC/SVOL yield 20%+ but PE is negative — recent losses. Dividend sustainability at risk. Always check PE > 0 before recommending.
|
||||
- **⚠️ mREITs are rate-sensitive**: NLY/AGNC/DX/ARR depend on net interest margin. Fed rate cuts = tailwind; rate hikes = headwind. Best DCA during rate-cutting cycles.
|
||||
- **⚠️ Covered call ETFs cap upside**: QYLD/JEPQ/SPYI generate income by selling calls — total return may lag underlying index in bull markets. DCA works better in range-bound markets.
|
||||
- **⚠️ HK bank PB<1 is structural**: Chinese bank "破净" has persisted for years — it reflects real estate risk, not necessarily a bargain. Still fine for dividend income but don't expect PB reversion.
|
||||
- **⚠️ BDC vs mREIT**: BDCs (HTGC/ARCC/MAIN) have more diversified income sources and typically more stable dividends than mREITs. Prefer BDCs for conservative DCA.
|
||||
- **Seasonality**: US ex-dividend dates cluster around Feb/May/Aug/Nov for quarterly payers. Plan DCA entries to capture dividends.
|
||||
|
||||
## DCA Strategy Tips
|
||||
|
||||
1. **3-5 price levels**: Set 3-5 buy levels below current price, spaced 5-10% apart
|
||||
2. **Equal dollar amounts**: Invest same $ amount at each level (not equal shares)
|
||||
3. **Dividend reinvestment**: DRIP accelerates compounding during DCA accumulation
|
||||
4. **Sector diversification**: Mix REIT + BDC + utility + telecom — don't over-concentrate
|
||||
5. **HK + US mix**: HK for value (low PE/PB), US for yield (higher dividend rates)
|
||||
@@ -0,0 +1,57 @@
|
||||
# Factor Mining & Quantitative Analysis Landscape
|
||||
|
||||
## Open-Source Projects
|
||||
|
||||
### Wrigggy/quant-factor-mining ⭐ (Primary)
|
||||
- **URL**: https://github.com/Wrigggy/quant-factor-mining
|
||||
- **Installed**: `~/.hermes/skills/trading/quant-factor-mining`
|
||||
- **Features**: Walk-forward validation, Alphalens evaluation, CVXPY optimization, Streamlit dashboard
|
||||
- **Factors**: Momentum (252d/21d skip), Mean Reversion (21d), Low Volatility (63d)
|
||||
- **Data**: LongPort integration via `src/qfm/data/longport_fetch.py`
|
||||
|
||||
### Yitong-Guo/Genetic-Algorithm-for-quantitative-alpha-factors-mining ⭐35
|
||||
- **URL**: https://github.com/Yitong-Guo/Genetic-Algorithm-for-quantitative-alpha-factors-mining
|
||||
- **Method**: Genetic algorithm for alpha factor discovery
|
||||
|
||||
### LinChengHao3606307/AlphaMining ⭐10
|
||||
- **URL**: https://github.com/LinChengHao3606307/AlphaMining
|
||||
- **Method**: Reinforcement learning, 5 neural network architectures
|
||||
|
||||
### IIcodehub/GP-Alpha-Miner ⭐7
|
||||
- **URL**: https://github.com/IIcodehub/GP-Alpha-Miner-GPU-Accelerated-Genetic-Programming-Framework
|
||||
- **Method**: GPU-accelerated genetic programming
|
||||
|
||||
## Python Libraries
|
||||
|
||||
| Library | Purpose | Install |
|
||||
|---------|---------|---------|
|
||||
| alphalens-reloaded | Factor evaluation & tearsheet | `pip install alphalens-reloaded` |
|
||||
| cvxpy | Portfolio optimization | `pip install cvxpy` |
|
||||
| pyportfolioopt | Mean-variance optimization | `pip install pyportfolioopt` |
|
||||
| zipline-reloaded | Event-driven backtesting | `pip install zipline-reloaded` |
|
||||
| vectorbt | Vectorized backtesting | `pip install vectorbt` |
|
||||
| optuna | Hyperparameter optimization | `pip install optuna` |
|
||||
| backtrader | Strategy backtesting | `pip install backtrader` |
|
||||
|
||||
## LongPort Factor Data
|
||||
|
||||
| Data Point | API | Field |
|
||||
|-----------|-----|-------|
|
||||
| PE TTM | calc_indexes | PeTtmRatio |
|
||||
| PB | calc_indexes | PbRatio |
|
||||
| Dividend Yield | calc_indexes | DividendRatioTtm |
|
||||
| Market Cap | calc_indexes | TotalMarketValue |
|
||||
| Turnover Rate | calc_indexes | TurnoverRate |
|
||||
| Volume Ratio | calc_indexes | VolumeRatio |
|
||||
| Change Rate | calc_indexes | ChangeRate |
|
||||
| EPS TTM | static_info | eps_ttm |
|
||||
| BPS | static_info | bps |
|
||||
| K-line History | history_candlesticks_by_offset | OHLCV |
|
||||
|
||||
## Factor Analysis Timing (User: UTC+8 Beijing)
|
||||
|
||||
| Market | Analysis Time (Beijing) | Cron (EDT) | Reason |
|
||||
|--------|------------------------|------------|--------|
|
||||
| HK/A-share | 17:00 daily | `0 5 * * 1-5` | 1hr after HK close |
|
||||
| US | 20:30 daily | `30 8 * * 1-5` | Pre-market signal |
|
||||
| Weekly | Fri 21:00 | `0 21 * * 5` | Weekend summary |
|
||||
@@ -0,0 +1,118 @@
|
||||
# Intraday Trading: Factors, Screening & Strategies
|
||||
|
||||
## Stock Screening Criteria for Day Trading
|
||||
|
||||
### Universal Filters
|
||||
| Factor | Metric | Threshold | Weight |
|
||||
|--------|--------|-----------|--------|
|
||||
| Volatility | Average Daily Range (ADR%) | > 2% (ideal > 3%) | 40% |
|
||||
| Liquidity | Volume | > 1M shares/day (HK: > 5M HKD turnover) | — |
|
||||
| Spread | Bid-Ask Spread | < 0.05% (scalping) / < 0.2% (swing) | — |
|
||||
| Activity | Volume Ratio (RVOL) | > 1.5x average | 30% |
|
||||
| Activity | Turnover Rate | > 1% | 30% |
|
||||
| Trend | ADX | > 25 (trending market) | bonus |
|
||||
|
||||
### Composite Day Trading Score
|
||||
```python
|
||||
day_trade_score = (min(ADR% / 3, 1) * 40 + # 3% ADR = max
|
||||
min(RVOL / 2, 1) * 30 + # 2x RVOL = max
|
||||
min(Turnover% / 2, 1) * 30) # 2% turnover = max
|
||||
|
||||
# > 60: Excellent for day trading
|
||||
# 40-60: Good for day trading
|
||||
# < 40: Not ideal
|
||||
```
|
||||
|
||||
### HK-Specific Screening
|
||||
- Price: HKD 2-500
|
||||
- HSI/HSCEI constituents or high-beta stocks
|
||||
- Connect stocks (Southbound/Northbound eligible)
|
||||
- AH spread opportunities
|
||||
- Note: HK has 0.1% stamp duty
|
||||
|
||||
## Intraday Strategies
|
||||
|
||||
### 1. Momentum Scalping
|
||||
- **Entry**: Breakout of consolidation with volume surge
|
||||
- **Exit**: Quick profit (0.2-0.5%), trailing stop
|
||||
- **Timeframe**: 1-5 min
|
||||
- **Key**: Speed, tight spreads
|
||||
|
||||
### 2. Mean Reversion
|
||||
- **Entry**: RSI extremes (< 30 buy, > 70 sell), Bollinger Band touches
|
||||
- **Exit**: Return to VWAP or MA
|
||||
- **Timeframe**: 5-15 min
|
||||
- **Key**: Identify overextended moves
|
||||
|
||||
### 3. VWAP Trading
|
||||
- **Entry**: Price crosses VWAP with volume confirmation
|
||||
- **Exit**: Previous swing high/low
|
||||
- **Timeframe**: 5-15 min
|
||||
- **Key**: Institutional reference point
|
||||
|
||||
### 4. Opening Range Breakout (ORB)
|
||||
- **Entry**: Break of first 15-30 min high/low
|
||||
- **Exit**: 1:2 risk-reward or trailing stop
|
||||
- **Timeframe**: 15-min opening range
|
||||
|
||||
### 5. AH Spread Arbitrage (HK-specific)
|
||||
- **Pairs**: AH premium/discount stocks (e.g., 700.HK vs TCEHY)
|
||||
- **Entry**: Spread deviation > 2 std from mean
|
||||
- **Exit**: Spread normalization
|
||||
- **Key**: Currency hedging, execution timing
|
||||
|
||||
### 6. Gap Trading
|
||||
- **Gap & Go**: Trade in gap direction with momentum
|
||||
- **Gap Fill**: Fade gaps that tend to fill
|
||||
- **Timeframe**: First 30-60 min
|
||||
|
||||
## Key Technical Indicators for Intraday
|
||||
|
||||
| Indicator | Use | Setting |
|
||||
|-----------|-----|---------|
|
||||
| ATR | Volatility measurement | 14-period |
|
||||
| VWAP | Institutional benchmark | Intraday |
|
||||
| RSI | Overbought/oversold | 14-period |
|
||||
| Bollinger Bands | Volatility channels | 20, 2σ |
|
||||
| MACD | Trend direction | 12, 26, 9 |
|
||||
| ADX | Trend strength | 14-period |
|
||||
| Volume Profile | Support/resistance levels | POC, VAH, VAL |
|
||||
|
||||
## Risk Management
|
||||
|
||||
- Position sizing: 1-2% risk per trade
|
||||
- Max daily loss: 3-5% of capital
|
||||
- Always use stop losses
|
||||
- Avoid revenge trading
|
||||
- Track all trades for review
|
||||
|
||||
## LongPort Data for Intraday
|
||||
|
||||
```python
|
||||
# Real-time quote
|
||||
resp = ctx.quote(['1024.HK', '9868.HK'])
|
||||
for q in resp:
|
||||
print(f'{q.symbol}: {q.last_done}, vol={q.volume}')
|
||||
|
||||
# K-line for ADR calculation
|
||||
candles = ctx.candlesticks('1024.HK', Period.Day, 20, AdjustType.ForwardAdjust)
|
||||
adr = sum(float(c.high) - float(c.low) for c in candles) / len(candles)
|
||||
|
||||
# Volume ratio and turnover
|
||||
from longport.openapi import CalcIndex
|
||||
resp = ctx.calc_indexes(['1024.HK'], [CalcIndex.VolumeRatio, CalcIndex.TurnoverRate])
|
||||
|
||||
# Order book depth
|
||||
depth = ctx.depth('1024.HK')
|
||||
```
|
||||
|
||||
## HK Day Trading Candidates (2026-06-01 snapshot)
|
||||
|
||||
| Stock | Price | ADR% | Score | Strategy |
|
||||
|-------|-------|------|-------|----------|
|
||||
| 快手(1024) | $46.54 | 5.07% | 78.7 | Momentum breakout |
|
||||
| 小鹏(9868) | $67.80 | 4.18% | 78.5 | Gap + trend |
|
||||
| 美团(3690) | $78.25 | 3.73% | 76.8 | VWAP bounce |
|
||||
| 理想(2015) | $58.55 | 4.35% | 65.7 | Trend follow |
|
||||
| 小米(1810) | $28.72 | 3.77% | 63.7 | Mean reversion |
|
||||
| 百度(9888) | $129.10 | 3.61% | 63.7 | AI momentum |
|
||||
@@ -0,0 +1,72 @@
|
||||
# Monthly Dividend Stocks Reference
|
||||
|
||||
Curated list of monthly-dividend-paying stocks and ETFs for US and HK markets. Organized by category for quick screening.
|
||||
|
||||
**Last reviewed**: 2025 (approximate yields — always verify current data via Yahoo Finance or LongBridge before presenting)
|
||||
|
||||
---
|
||||
|
||||
## US — REITs (Real Estate Investment Trusts)
|
||||
|
||||
| Ticker | Name | ~Yield | Profile |
|
||||
|--------|------|--------|---------|
|
||||
| O | Realty Income | 5-6% | "The Monthly Dividend Company" — 100+ consecutive dividend increases, retail/net-lease REIT, blue-chip |
|
||||
| STAG Industrial | STAG Industrial | 4-5% | Industrial/logistics warehouses, e-commerce tailwind |
|
||||
| AGNC Investment | AGNC Investment | 13-16% | Mortgage REIT (mREIT) — agency MBS, high yield but high volatility |
|
||||
| NLY | Annaly Capital | 12-14% | Mortgage REIT (mREIT) — largest agency mREIT, rate-sensitive |
|
||||
| ADC | Agree Realty | 4-5% | Net-lease REIT, essential retail tenants |
|
||||
|
||||
## US — BDCs (Business Development Companies)
|
||||
|
||||
| Ticker | Name | ~Yield | Profile |
|
||||
|--------|------|--------|---------|
|
||||
| MAIN | Main Street Capital | 6-7% | Quality BDC, monthly dividends + supplemental, steady grower |
|
||||
| GAIN | Gladstone Investment | 7-8% | Small/mid-cap BDC, income + capital gains distributions |
|
||||
| PSEC | Prospect Capital | 10-12% | High yield BDC, diversified lending, higher risk |
|
||||
| SLRC | SLR Investment Corp | 10-11% | Specialty lending BDC |
|
||||
|
||||
## US — Covered Call ETFs (Income-focused)
|
||||
|
||||
| Ticker | Name | ~Yield | Strategy |
|
||||
|--------|------|--------|----------|
|
||||
| QYLD | Global X NASDAQ 100 CC | 11-13% | Sells ATM calls on QQQ — max income, capped upside |
|
||||
| XYLD | Global X S&P 500 CC | 10-11% | Sells ATM calls on SPY — same strategy on S&P |
|
||||
| JEPI | JPMorgan Equity Premium Income | 7-9% | ELN + stock selection — lower vol, smoother returns |
|
||||
| JEPQ | JPMorgan NASDAQ Equity Premium | 8-10% | NASDAQ version of JEPI |
|
||||
| DIVO | Amplify CWP Enhanced Dividend | 4-5% | Blue-chip stocks + covered calls, capital appreciation focus |
|
||||
| RYLD | Global X Russell 2000 CC | 11-13% | Small-cap covered call ETF |
|
||||
|
||||
## US — Other Monthly Payers
|
||||
|
||||
| Ticker | Name | ~Yield | Profile |
|
||||
|--------|------|--------|---------|
|
||||
| SCHD | Schwab US Dividend Equity | 3-4% | Quarterly but frequently requested; quality dividend growth |
|
||||
| EPR | EPR Properties | 7-8% | Experiential REIT (theaters, ski resorts, gaming) |
|
||||
| LTC | LTC Properties | 6-7% | Senior housing/healthcare REIT |
|
||||
|
||||
## HK — Monthly Dividend REITs
|
||||
|
||||
| Code | Name | ~Yield | Notes |
|
||||
|------|------|--------|-------|
|
||||
| 0823.HK | Link REIT | 5-6% | Largest HK REIT, retail + office |
|
||||
| 0778.HK | Fortune REIT | 6-7% | Community shopping centers |
|
||||
| 0405.HK | Yuexiu REIT | 7-8% | HK + mainland China properties |
|
||||
| 0435.HK | Sunlight REIT | 7-8% | Office + retail in HK |
|
||||
| 1881.HK | Regal REIT | 8-9% | Hotel REIT, higher yield but cyclical |
|
||||
| 2191.HK | SF REIT | 5-6% | Logistics/warehouse REIT |
|
||||
|
||||
## Screening Tips
|
||||
|
||||
- **Dividend safety**: Check payout ratio (< 80% is sustainable), consecutive years of increases, FFO/AFFO coverage
|
||||
- **mREIT caveat**: AGNC/NLY/RNLY yield 12%+ but are rate-sensitive and can cut dividends during tightening cycles
|
||||
- **Covered call trade-off**: QYLD/XYLD maximize current income but sacrifice capital appreciation — total return may lag underlying index
|
||||
- **HK REITs**: Hong Kong property market has been under pressure since 2022; yields may reflect distressed valuations (opportunity or trap?)
|
||||
- **Best all-rounder**: O (Realty Income) — best risk-adjusted monthly income for most portfolios
|
||||
|
||||
## Fallback Data Sources
|
||||
|
||||
When Yahoo Finance is rate-limited or unavailable:
|
||||
1. **LongBridge CLI**: `longbridge quote --json <TICKERS>` (requires valid token)
|
||||
2. **Nasdaq API**: `https://api.nasdaq.com/api/quote/<TICKER>/dividends` (Nasdaq-listed only)
|
||||
3. **Web search**: Search `<TICKER> dividend yield 2025` for latest data
|
||||
4. **StockAnalysis.com**: `https://stockanalysis.com/stocks/<ticker>/dividend/`
|
||||
@@ -0,0 +1,109 @@
|
||||
# Stock Analysis v6.3 - Quick Reference
|
||||
|
||||
## New: LongPort-Powered 8-Dimension Analysis
|
||||
|
||||
### Basic Usage
|
||||
```bash
|
||||
# Single stock
|
||||
uv run ~/.hermes/skills/openclaw-imports/stock-analysis/scripts/analyze_stock_unified.py O
|
||||
|
||||
# Multiple stocks
|
||||
uv run ~/.hermes/skills/openclaw-imports/stock-analysis/scripts/analyze_stock_unified.py O 823.HK MAIN JEPI NLY
|
||||
|
||||
# Fast mode (skip Yahoo fallback for speed)
|
||||
uv run ~/.hermes/skills/openclaw-imports/stock-analysis/scripts/analyze_stock_unified.py O --fast
|
||||
|
||||
# JSON output
|
||||
uv run ~/.hermes/skills/openclaw-imports/stock-analysis/scripts/analyze_stock_unified.py O --output json
|
||||
```
|
||||
|
||||
### Symbol Format
|
||||
| Market | Format | Example |
|
||||
|--------|--------|---------|
|
||||
| US | `TICKER` or `TICKER.US` | `O`, `AAPL.US` |
|
||||
| HK | `CODE.HK` | `823.HK`, `9988.HK` |
|
||||
| CN | `CODE.SZ` or `CODE.SH` | `000001.SZ` |
|
||||
|
||||
### 8-Dimension Scoring System
|
||||
|
||||
| Dimension | Weight | Data Source | Metrics |
|
||||
|-----------|--------|-------------|---------|
|
||||
| **Fundamentals** | 40% | LongPort + Yahoo | PE, PB, dividend, margins, ROE, debt |
|
||||
| **Valuation** | 30% | LongPort | PE/PB/dividend relative scoring |
|
||||
| **Momentum** | 20% | LongPort | RSI, volume ratio, price change |
|
||||
| **Market Cap** | 10% | LongPort | Large-cap stability bonus |
|
||||
|
||||
### Scoring Logic
|
||||
|
||||
**Fundamentals Score:**
|
||||
- PE < 15: +0.5, PE > 30: -0.3
|
||||
- PB < 1.0: +0.6, PB > 5.0: -0.4
|
||||
- Dividend > 5%: +0.5
|
||||
- Operating margin > 15%: +0.5
|
||||
- ROE > 15%: +0.4
|
||||
- Debt/Equity < 50: +0.3
|
||||
|
||||
**Valuation Score:**
|
||||
- PE: <15 → +0.5, <25 → +0.2, >35 → -0.3
|
||||
- PB: <1.0 → +0.6, <2.0 → +0.3, >5.0 → -0.4
|
||||
- Dividend: >5% → +0.5, >3% → +0.3
|
||||
|
||||
**Momentum Score:**
|
||||
- RSI < 30 (oversold): +0.5
|
||||
- RSI > 70 (overbought): -0.5
|
||||
- Volume ratio > 1.5: +0.3
|
||||
|
||||
### Recommendations
|
||||
| Score | Recommendation | Confidence |
|
||||
|-------|----------------|------------|
|
||||
| > 0.3 | BUY | 80-90% |
|
||||
| > 0.0 | BUY | 50-80% |
|
||||
| > -0.3 | HOLD | 50-80% |
|
||||
| < -0.3 | SELL | 80-90% |
|
||||
|
||||
### Data Sources
|
||||
|
||||
**LongPort (Primary):**
|
||||
- PE TTM, PB, EPS TTM, BPS
|
||||
- Dividend yield, Market cap
|
||||
- Real-time quotes, Volume ratio
|
||||
- Full HK/CN/US coverage
|
||||
|
||||
**Yahoo Finance (Fallback - US only):**
|
||||
- Operating margins, ROE, ROA
|
||||
- Debt ratios, Revenue growth
|
||||
- Analyst ratings, Earnings history
|
||||
|
||||
## Legacy Commands (Yahoo Finance)
|
||||
|
||||
### Stock Analysis
|
||||
```bash
|
||||
uv run {baseDir}/scripts/analyze_stock.py AAPL --fast
|
||||
```
|
||||
|
||||
### Dividend Analysis
|
||||
```bash
|
||||
uv run {baseDir}/scripts/dividends.py O JEPI QYLD
|
||||
```
|
||||
|
||||
## Environment Setup
|
||||
|
||||
### LongPort SDK
|
||||
Add to `~/.bashrc`:
|
||||
```bash
|
||||
export LONGBRIDGE_APP_KEY=your_key
|
||||
export LONGBRIDGE_APP_SECRET=your_s...port LONGBRIDGE_ACCESS_TOKEN=your_t...The script auto-maps `LONGBRIDGE_*` → `LONGPORT_*` for the SDK.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "token invalid" error
|
||||
Token expired. Get new token from LongPort App → Settings → API Keys.
|
||||
|
||||
### Yahoo Finance rate limiting
|
||||
Normal during heavy usage. LongPort data is still available. Use `--fast` to skip Yahoo.
|
||||
|
||||
### Missing PE/PB for ETFs
|
||||
ETFs don't have traditional PE/PB. Only dividend yield is available.
|
||||
|
||||
### Negative PE
|
||||
Negative PE means the company is losing money. Fundamentals score will be lower.
|
||||
Reference in New Issue
Block a user