feat: add quant layer, portfolio-review, and strategy-backtest skills
All checks were successful
continuous-integration/drone/push Build is passing

fundamental-analysis: added statistical risk layer
- normality test (Jarque-Bera) — validates Sharpe/VaR reliability
- unit root test (ADF) — validates technical analysis applicability
- rolling skew/kurtosis — tail risk monitoring
- interpretation rules for crash risk detection

portfolio-review (NEW): portfolio health check and similarity search
- HRP optimization, correlation matrix, risk parity weights
- t-SNE clustering for hidden correlations
- stock similarity search for diversification
- rule-engine BUY_MORE/HOLD/SELL per holding

strategy-backtest (NEW): historical strategy validation
- SMA crossover, RSI mean-reversion, buy-and-hold, momentum
- comparison framework with Sharpe, max DD, win rate
- validation workflow for trade-analyze recommendations

Coverage: 67% → 79% of API endpoints (104/131)
This commit is contained in:
Yaojia Wang
2026-03-21 19:19:40 +01:00
parent 880f830741
commit e798fce6a8
3 changed files with 294 additions and 2 deletions

View File

@@ -0,0 +1,130 @@
---
name: strategy-backtest
description: "Strategy backtesting — test SMA crossover, RSI, buy-and-hold, momentum strategies against historical data. Use when user wants to validate a trading idea or compare strategies."
user-invocable: true
metadata: { "openclaw": { "emoji": "🧪", "requires": { "bins": ["curl"] } } }
---
# Strategy Backtest
Professional backtesting for strategy validation. Think like a quant researcher — data over intuition.
**Trigger**: User says "backtest", "test this strategy", "would this have worked", "compare strategies", or wants to validate a trade-analyze recommendation.
## Available Strategies
### 1. SMA Crossover (trend-following)
When short SMA crosses above long SMA → buy. Crosses below → sell.
```bash
BASE=https://invest-api.k8s.home
curl -sk -X POST "$BASE/api/v1/backtest/sma-crossover" \
-H "Content-Type: application/json" \
-d '{"symbol": "{TICKER}", "short_window": 20, "long_window": 50, "days": 365, "initial_capital": 10000}'
```
Best for: trending markets, medium-term holds.
Weak in: sideways/choppy markets (many false signals).
### 2. RSI Mean Reversion
Buy when RSI < oversold threshold, sell when RSI > overbought threshold.
```bash
curl -sk -X POST "$BASE/api/v1/backtest/rsi" \
-H "Content-Type: application/json" \
-d '{"symbol": "{TICKER}", "period": 14, "oversold": 30, "overbought": 70, "days": 365, "initial_capital": 10000}'
```
Best for: range-bound stocks, mean-reverting behavior.
Weak in: strong trends (catches falling knives).
### 3. Buy and Hold (benchmark)
Always run this as the baseline comparison.
```bash
curl -sk -X POST "$BASE/api/v1/backtest/buy-and-hold" \
-H "Content-Type: application/json" \
-d '{"symbol": "{TICKER}", "days": 365, "initial_capital": 10000}'
```
### 4. Momentum (multi-stock rotation)
Rank stocks by recent performance, hold top N, rebalance periodically.
```bash
curl -sk -X POST "$BASE/api/v1/backtest/momentum" \
-H "Content-Type: application/json" \
-d '{"symbols": ["AAPL","MSFT","GOOGL","AMZN","NVDA","META","TSLA","JPM","V","WMT"], "lookback": 60, "top_n": 3, "rebalance_days": 30, "days": 365, "initial_capital": 10000}'
```
Best for: diversified portfolios, capturing sector rotation.
## Standard Workflow
**Always run all 3 single-stock strategies + buy-and-hold for comparison:**
```bash
# Run all 4 in one go
curl -sk -X POST "$BASE/api/v1/backtest/buy-and-hold" -H "Content-Type: application/json" -d '{"symbol":"{TICKER}","days":365,"initial_capital":10000}'
curl -sk -X POST "$BASE/api/v1/backtest/sma-crossover" -H "Content-Type: application/json" -d '{"symbol":"{TICKER}","short_window":20,"long_window":50,"days":365,"initial_capital":10000}'
curl -sk -X POST "$BASE/api/v1/backtest/rsi" -H "Content-Type: application/json" -d '{"symbol":"{TICKER}","period":14,"oversold":30,"overbought":70,"days":365,"initial_capital":10000}'
```
## Report Structure
```
## {TICKER} Strategy Backtest — {date}
### Period: {start_date} to {end_date} ({days} days)
### Initial Capital: $10,000
### Strategy Comparison
| Strategy | Return | Sharpe | Max DD | Win Rate | Trades |
|----------|--------|--------|--------|----------|--------|
| Buy & Hold | {%} | {val} | {%} | N/A | 1 |
| SMA 20/50 | {%} | {val} | {%} | {%} | {n} |
| RSI 14/30/70 | {%} | {val} | {%} | {%} | {n} |
### Winner: {strategy name}
- Outperformed buy-and-hold by: {%}
- Key advantage: {why it worked for this stock}
### Equity Curve Summary
- Buy & Hold final: ${value}
- Best strategy final: ${value}
- Worst drawdown period: {date range}
### Strategy Suitability for {TICKER}
- Stock behavior: [trending / mean-reverting / choppy]
- Best fit: {strategy} because {reason}
- Avoid: {strategy} because {reason}
### ⚠️ Backtest Caveats
- No transaction costs or slippage included
- Past performance ≠ future results
- Optimized parameters may overfit
- Consider out-of-sample testing (different time period)
```
## Validation Workflow (after /trade-analyze)
When used to validate a trade-analyze recommendation:
1. Run buy-and-hold for baseline
2. If trade-analyze recommended BUY based on technical signals:
- Run SMA crossover to see if trend-following would have worked
- Run RSI to see if mean-reversion entries would have worked
3. Compare Sharpe ratios and max drawdowns
4. Conclusion: "The data {supports / does not support} the trade-analyze recommendation because {reason}"
## Rules
- **Always include buy-and-hold as benchmark** — any strategy must beat it
- Sharpe > 1.0 = good risk-adjusted returns
- Max drawdown > 20% = strategy needs tighter risk management
- Win rate < 40% can still be profitable if average win >> average loss
- If all strategies underperform buy-and-hold → the stock rewards patience, not trading
- Keep under 500 words