- name
- risk-and-portfolio
- description
- Complete trading risk management, portfolio construction, performance tracking, and quantitative stress testing — all in one skill. The safety layer for all trading decisions.
RISK MANAGEMENT: "risk management", "position sizing", "lot size calculation", "stop loss placement", "drawdown management", "Kelly criterion", "ATR-based sizing", "fixed percentage risk model", "risk-reward analysis", "profit factor", "expectancy", "trading psychology", "trade-psychology-coach biases", "loss aversion", "FOMO", "revenge trading", "emotional management", "daily loss limit", "weekly loss limit", "max drawdown", "portfolio heat", "correlation risk", "trailing stops", "losing streak", "drawdown recovery", "risk of ruin", "VaR", "CVaR", "Calmar ratio", "Sortino ratio", "margin requirements", "money management", "1% rule trading".
EXECUTION & COSTS: "best entry timing", "scaling in out", "limit vs market orders", "partial fills", "slippage reduction", "scale into position", "split my entry", "reduce slippage", "DCA strategy", "pyramid into trade", "trail my stop", "order book", "bid ask spread", "microstructure", "spread analysis", "execution cost", "broker comparison", "true spread", "market impact", "TWAP", "VWAP execution", "transaction cost analysis", "TCA", "Almgren-Chriss".
TRADE JOURNAL: "log my trade", "journal this trade", "show my stats", "performance report", "what's my win rate", "equity curve", "expectancy", "R-multiple", "trade history", "best worst trades", "review my trading", "monthly P&L", "streak analysis".
TRADE FILTER: "should I trade today", "is it safe to trade", "any events to avoid", "blackout zones", "when not to trade", "event risk", "news blackout", "rollover time", "low liquidity", "NFP week", "FOMC week", "end of month".
PORTFOLIO: "portfolio optimization", "Markowitz", "efficient frontier", "Black-Litterman", "risk parity", "asset allocation", "portfolio weights", "minimum variance", "maximum Sharpe", "basket trade", "currency basket", "synthetic pair", "strategy allocation", "ensemble trading", "multi-strategy fund", "DXY replica", "capital allocation".
MULTI-ACCOUNT: "multi account", "track accounts", "aggregate P&L", "compare accounts", "total balance", "portfolio across brokers", "account summary", "all my accounts".
TAIL RISK: "tail risk", "black swan", "crash protection", "hedge portfolio", "portfolio insurance", "fat tails", "disaster hedge".
RISK PREMIA: "risk premia", "factor investing", "value factor", "momentum factor", "carry factor", "volatility premium", "alternative risk premia", "ARP", "factor harvesting", "smart beta", "systematic factor", "factor portfolio".
ARBITRAGE: "arbitrage", "stat arb", "pairs trading", "triangular arbitrage", "convergence trade", "mean reversion pair", "cointegration", "basis trade", "spread trading", "relative value", "mispricing detection", "hedge ratio", "spread z-score", "cross-asset arbitrage".
RISK-ADJUSTED COMPOUNDING: "compounding", "risk-adjusted compounding", "Sharpe ratio", "compound projection", "geometric growth rate", "monthly compounding", "CAGR".
PERFORMANCE ATTRIBUTION: "performance attribution", "P&L by pair", "P&L by setup", "P&L by session", "P&L by direction", "best pair", "worst pair", "edge analysis".
MONTE CARLO: "Monte Carlo", "stress test", "bootstrap returns", "parametric simulation", "regime shuffle", "parameter perturbation", "robustness test", "risk of ruin simulation", "fat tail simulation", "Student-t Monte Carlo".
PARAMETER SENSITIVITY: "parameter sensitivity", "grid sweep", "heatmap", "overfit detection", "flatness score", "one-at-a-time sensitivity", "curve fitting check", "robustness check".
TRADE PSYCHOLOGY: "tilt detector", "revenge trading detection", "trade-psychology-coach bias check", "discipline score", "pre-trade checklist", "trading psychology coach", "emotional state", "consecutive losses", "overtrading detection".
TRADE-LEVEL RISK: "midpoint entry", "SL halving", "partial close", "break-even rule", "FVG midpoint", "R:R improvement", "trade management protocol".
DO NOT USE FOR: ICT-specific risk rules (use ict-smart-mon…
- related_skills
- ["portfolio-optimization","risk-and-portfolio","portfolio-optimization","trading-fundamentals"]
- tags
- ["trading","risk","portfolio","position-sizing","drawdown","kelly"]
- skill_level
- intermediate
- kind
- reference
- category
- trading/risk
- status
- active
> **Skill:** Risk And Portfolio | **Domain:** trading | **Category:** risk | **Level:** intermediate
> **Tags:** `trading`, `risk`, `portfolio`, `position-sizing`, `drawdown`, `kelly`
# Risk & Portfolio — Complete Framework
> The safety layer. No trade should be taken without passing through risk checks.
## Sections
1. **Risk Management** — position sizing, rules, psychology, drawdown recovery
2. **Execution & Costs** — entry timing, scaling, microstructure, spread/slippage
3. **Trade Journal & Performance** — logging, analytics, equity curve
4. **Trade Filter** — when NOT to trade (event blackouts, structural risks)
5. **Portfolio & Allocation** — Markowitz, risk parity, baskets, strategy allocation
6. **Multi-Account Manager** — aggregate P&L across brokers
7. **Tail Risk Hedging** — black swan protection
8. **Risk Premia** — factor investing (momentum, carry, value, volatility premium)
9. **Arbitrage Engine** — cointegration, pairs trading, triangular arb, spread z-score
10. **Risk-Adjusted Compounding** — Sharpe/Sortino/Calmar metrics, Kelly compounding, projections
11. **Performance Attribution** — P&L decomposition by pair, setup, direction, session, day
12. **Monte Carlo Stress Testing** — bootstrap, parametric (fat-tail), regime shuffle, parameter perturbation
13. **Parameter Sensitivity** — 2D grid sweep, OAT analysis, heatmaps, overfit/flatness scoring
14. **Trade Psychology Coach** — tilt detector, trade-psychology-coach bias check, discipline score, pre-trade checklist
15. **Trade-Level Risk Refinement** — midpoint entry (SL halving), partial close & break-even protocol
---
## Reference Files
- **[references/risk-and-portfolio.md](references/risk-and-portfolio.md)** — Core risk rules, position sizing (fixed %, Kelly, ATR), drawdown protocol, portfolio heat, psychology, journal template
- **[references/execution-costs.md](references/execution-costs.md)** — Entry timing, order splitting/scaling, trailing stops, market microstructure, spread/slippage analysis, market impact model
- **[references/journal-and-filter.md](references/journal-and-filter.md)** — Trade journal engine, performance analytics (win rate, equity curve, R-multiple), event blackout filter, should_i_trade()
- **[references/portfolio-allocation.md](references/portfolio-allocation.md)** — Portfolio optimization (Markowitz, Black-Litterman, risk parity), strategy allocator, currency baskets, synthetic instruments
- **[references/account-tail-risk.md](references/account-tail-risk.md)** — Multi-account manager (aggregate P&L) + tail risk hedging (black swan protection)
- **[references/risk-premia.md](references/risk-premia.md)** — Factor investing: momentum factor, carry factor, value factor, volatility premium harvesting, combined factor portfolio
- **[references/arbitrage-engine.md](references/arbitrage-engine.md)** — Cointegration testing, OLS hedge ratio, triangular arbitrage check, spread z-score signals, pair scanner
## Quick Decision Guide
| Task | Load |
|------|------|
| Position sizing, lot size, stop placement | `references/risk-and-portfolio.md` |
| Kelly criterion, drawdown rules, psychology | `references/risk-and-portfolio.md` |
| When to enter, how to scale, slippage | `references/execution-costs.md` |
| Microstructure, spread analysis, TCA | `references/execution-costs.md` |
| Log a trade, check win rate, equity curve | `references/journal-and-filter.md` |
| Should I trade today? Event blackouts? | `references/journal-and-filter.md` |
| Portfolio weights, Markowitz, risk parity | `references/portfolio-allocation.md` |
| Currency basket, DXY replica, multi-strategy | `references/portfolio-allocation.md` |
| Multi-account P&L, broker comparison | `references/account-tail-risk.md` |
| Black swan hedge, crash protection | `references/account-tail-risk.md` |
| Factor investing, momentum/carry/value/vol premia | `references/risk-premia.md` |
| Cointegration, pairs trade, triangular arb, spread z-score | `references/arbitrage-engine.md` |
| Sharpe/Sortino/Calmar, compounding projections, Kelly growth | See **Risk-Adjusted Compounding** below |
| P&L by pair/setup/session/direction, edge analysis | See **Performance Attribution Engine** below |
| Monte Carlo bootstrap, parametric fat-tail, regime shuffle | See **Monte Carlo Stress Tester** below |
| Parameter grid sweep, heatmap, overfit detection | See **Parameter Sensitivity Analyzer** below |
| Tilt detection, revenge trading, trade-psychology-coach biases, discipline | See **Trade Psychology Coach** below |
| Midpoint entry (SL halving), partial close, break-even rule | See **Trade-Level Risk Refinement** below |
## Core Quick Reference Card
```
POSITION SIZE = (Account × Risk%) / Stop Distance
KELLY % = W − [(1−W) / R] → Use HALF Kelly
ATR STOP = ATR × Multiplier (2–4× depending on TF)
EXPECTED VALUE = (Win% × Avg Win) − (Loss% × Avg Loss)
PROFIT FACTOR = Gross Profit / Gross Loss → Target > 1.5
DAILY LIMIT = 3–5% account loss → STOP
WEEKLY LIMIT = 5–10% → reduce size
MAX DRAWDOWN = 15–25% → halt and review
PORTFOLIO HEAT = 6% max total open risk
LOSING STREAK = 3 losses → cut 50% | 5 losses → 25% or pause
MIN R:R = 1:1.5 → prefer 1:2+
BREAKEVEN STOP = move to entry when +1R reached
KILL SWITCH = 10% daily DD → stop trading for the day
MARGIN = never exceed 50% utilization
```
---
# Inline Implementations (merged from risk-and-portfolio)
> The sections below contain full Python implementations for risk-adjusted compounding,
> tail risk hedging, spread/slippage cost analysis, performance attribution,
> Monte Carlo stress testing, parameter sensitivity analysis, trade psychology coaching,
> and trade-level risk refinement techniques.
---
## Risk Adjusted Compounding
# Risk Adjusted Compounding
```python
import numpy as np
import pandas as pd
from typing import Optional
# ── Shared performance metrics ──────────────────────────────────────────────
def _sharpe(returns: np.ndarray, risk_free_daily: float = 0.04 / 252,
annualise: bool = True) -> float:
"""Annualised Sharpe ratio (excess return / vol)."""
excess = returns - risk_free_daily
std = returns.std(ddof=1)
if std == 0:
return 0.0
sr = excess.mean() / std
return float(sr * np.sqrt(252) if annualise else sr)
def _sortino(returns: np.ndarray, risk_free_daily: float = 0.04 / 252,
annualise: bool = True) -> float:
"""Sortino ratio — penalises only downside volatility."""
excess = returns - risk_free_daily
downside = returns[returns < 0]
down_std = downside.std(ddof=1) if len(downside) > 1 else 0.0
if down_std == 0:
return 0.0
sr = excess.mean() / down_std
return float(sr * np.sqrt(252) if annualise else sr)
def _calmar(returns: np.ndarray) -> float:
"""Calmar ratio = annualised return / max drawdown."""
equity = np.cumprod(1 + returns)
peak = np.maximum.accumulate(equity)
dd = (equity - peak) / peak
max_dd = abs(dd.min())
ann_ret = (equity[-1] ** (252 / len(returns)) - 1)
return float(ann_ret / max_dd) if max_dd > 0 else 0.0
def _max_drawdown(returns: np.ndarray) -> float:
equity = np.cumprod(1 + returns)
peak = np.maximum.accumulate(equity)
return float(((equity - peak) / peak).min())
def _profit_factor(returns: np.ndarray) -> float:
gains = returns[returns > 0].sum()
losses = abs(returns[returns < 0].sum())
return float(gains / losses) if losses > 0 else float("inf")
def comprehensive_metrics(
returns: "pd.Series | np.ndarray",
risk_free_annual: float = 0.04,
label: str = "Strategy",
) -> dict:
"""
Compute a full suite of risk-adjusted performance metrics.
Parameters
----------
returns : daily returns series (decimal, e.g. 0.01 = +1 %)
risk_free_annual : annual risk-free rate (default 4 %)
label : name shown in output
Returns
-------
dict with Sharpe, Sortino, Calmar, max drawdown, profit factor, VaR, CVaR, etc.
Example
-------
>>> metrics = comprehensive_metrics(df["returns"], label="My Strategy")
>>> print(metrics["sharpe"])
1.42
"""
r = np.asarray(returns, dtype=float)
r = r[~np.isnan(r)]
if len(r) < 5:
return {"error": "Need at least 5 return observations", "label": label}
rfr_daily = risk_free_annual / 252
equity = np.cumprod(1 + r)
ann_ret = float(equity[-1] ** (252 / len(r)) - 1)
# VaR & CVaR
var_95 = float(np.percentile(r, 5))
cvar_95 = float(r[r <= var_95].mean()) if (r <= var_95).any() else var_95
return {
"label": label,
"n_periods": len(r),
"total_return": round(float(equity[-1] - 1) * 100, 2),
"ann_return": round(ann_ret * 100, 2),
"ann_volatility": round(float(r.std(ddof=1) * np.sqrt(252)) * 100, 2),
"sharpe": round(_sharpe(r, rfr_daily), 3),
"sortino": round(_sortino(r, rfr_daily), 3),
"calmar": round(_calmar(r), 3),
"max_drawdown": round(_max_drawdown(r) * 100, 2),
"profit_factor": round(_profit_factor(r), 3),
"win_rate": round(float((r > 0).mean()) * 100, 1),
"var_95": round(var_95 * 100, 3),
"cvar_95": round(cvar_95 * 100, 3),
"skewness": round(float(pd.Series(r).skew()), 3),
"kurtosis": round(float(pd.Series(r).kurtosis()), 3),
"grade": (
"A+" if _sharpe(r, rfr_daily) > 2.0 else
"A" if _sharpe(r, rfr_daily) > 1.5 else
"B" if _sharpe(r, rfr_daily) > 1.0 else
"C" if _sharpe(r, rfr_daily) > 0.5 else "D"
),
}
class CompoundingOptimizer:
"""
Kelly-criterion compounding and multi-period projection.
Example
-------
>>> opt = CompoundingOptimizer.optimal_growth(0.55, 1.5, 1.0)
>>> print(opt["recommended"])
8.33
"""
@staticmethod
def optimal_growth(
win_rate: float,
avg_win: float,
avg_loss: float,
trades_per_year: int = 252,
) -> dict:
"""
Compute Kelly criterion fractions and geometric growth rates.
Parameters
----------
win_rate : fraction of winning trades (0–1)
avg_win : average win in R-multiples (or % of account)
avg_loss : average loss in R-multiples (positive value)
trades_per_year : used for annualising growth rate
Returns
-------
dict with full/half/quarter kelly and projected growth rates.
"""
if avg_win <= 0:
raise ValueError("avg_win must be positive")
if not 0 < win_rate < 1:
raise ValueError("win_rate must be between 0 and 1 (exclusive)")
kelly = (win_rate * avg_win - (1 - win_rate) * avg_loss) / avg_win
kelly = max(kelly, 0.0) # No negative sizing
half_kelly = kelly / 2
quarter_kelly = kelly / 4
def _growth_rate(f: float) -> float:
"""Expected log-growth per trade at fraction f."""
try:
return (win_rate * np.log1p(f * avg_win / 100)
+ (1 - win_rate) * np.log1p(-f * avg_loss / 100))
except (ValueError, ZeroDivisionError):
return -np.inf
return {
"full_kelly_pct": round(kelly * 100, 2),
"half_kelly_pct": round(half_kelly * 100, 2),
"quarter_kelly_pct": round(quarter_kelly * 100, 2),
"recommended": round(half_kelly * 100, 2),
"expectancy_r": round(win_rate * avg_win - (1 - win_rate) * avg_loss, 4),
"growth_at_half_kelly_ann": round(_growth_rate(half_kelly) * trades_per_year * 100, 2),
"growth_at_quarter_kelly_ann": round(_growth_rate(quarter_kelly) * trades_per_year * 100, 2),
"risk_of_ruin_half_kelly": round(
((1 - win_rate) / win_rate) ** (1 / max(half_kelly, 1e-6)), 4
),
"note": (
"Half Kelly = ~75 % of full Kelly growth with ~50 % of the variance. "
"Best risk-adjusted choice for most traders."
),
}
@staticmethod
def compound_projection(
balance: float,
monthly_return_pct: float,
months: int = 12,
withdrawal_pct: float = 0.0,
) -> dict:
"""
Project compounded account growth with optional monthly withdrawals.
Parameters
----------
balance : starting capital
GitHubで見る