forward-risk
Estimate potential future losses using VaR, Expected Shortfall, Monte Carlo simulation, and stress testing. Use when the user asks about Value-at-Risk, CVaR, Expected Shortfall, scenario analysis, stress testing, or factor-based risk decomposition. Also trigger when users mention 'how much could I lose', 'worst-case scenario', 'tail risk', 'risk budget', 'component VaR', 'marginal VaR', '99% confidence loss', 'Monte Carlo simulation', or ask how to project portfolio risk forward.
What this skill does
# Forward-Looking Risk Analysis
## Purpose
Estimate potential future losses and risk exposures using parametric models, simulation, and scenario analysis. This skill covers parametric and Monte Carlo Value-at-Risk, Conditional VaR (Expected Shortfall), component and marginal VaR, stress testing, scenario analysis, and factor-based risk decomposition. These tools are essential for portfolio risk management and regulatory capital calculations.
## Layer
1b — Forward-Looking Risk
## Direction
Prospective
## When to Use
- Estimating potential future losses for a portfolio or position
- Computing parametric VaR (variance-covariance method) for normally distributed returns
- Running Monte Carlo simulations to estimate VaR for non-normal distributions
- Computing CVaR / Expected Shortfall to understand tail risk beyond VaR
- Decomposing portfolio risk into component and marginal contributions
- Performing scenario analysis with historical or hypothetical shocks
- Stress testing portfolios under extreme but plausible conditions
- Breaking down risk into systematic factor risk and idiosyncratic risk
## Core Concepts
### Parametric (Variance-Covariance) VaR
Assumes returns are normally distributed. For a single asset or portfolio in dollar terms (assuming zero expected return over short horizons):
```
VaR = W * z_alpha * sigma_p
```
where:
- W = portfolio value
- z_alpha = z-score for confidence level (1.645 for 95%, 2.326 for 99%)
- sigma_p = portfolio volatility over the relevant horizon
More generally, including expected return:
```
VaR_alpha = mu - z_alpha * sigma
```
To convert from 1-day VaR to h-day VaR (assuming i.i.d. returns):
```
VaR_h = VaR_1 * sqrt(h)
```
### Portfolio VaR (Multiple Assets)
For a portfolio with weight vector w and covariance matrix Sigma:
```
sigma_p = sqrt(w' * Sigma * w)
VaR_p = W * z_alpha * sqrt(w' * Sigma * w)
```
The covariance matrix captures both individual volatilities and correlations between assets.
### Monte Carlo VaR
Simulate a large number of portfolio return scenarios (e.g., 10,000+), then take the alpha-percentile of the simulated loss distribution.
Steps:
1. Estimate the return distribution parameters (mean vector, covariance matrix, or use a copula model).
2. Generate N random return scenarios (e.g., via Cholesky decomposition of the covariance matrix for multivariate normal).
3. Compute portfolio return for each scenario.
4. Sort results and identify the alpha-percentile loss.
Monte Carlo VaR can accommodate non-normal distributions, fat tails, path-dependent instruments, and nonlinear payoffs (e.g., options).
### Conditional VaR (CVaR) / Expected Shortfall
CVaR answers: "Given that losses exceed VaR, what is the expected loss?"
```
ES_alpha = E[Loss | Loss > VaR_alpha]
```
For a normal distribution:
```
ES_alpha = mu + sigma * phi(z_alpha) / (1 - alpha)
```
where phi is the standard normal PDF.
CVaR is a **coherent risk measure** (unlike VaR) because it satisfies subadditivity: CVaR(A+B) <= CVaR(A) + CVaR(B). This means diversification always reduces or maintains CVaR, which is not guaranteed for VaR.
### Component VaR
Decomposes total portfolio VaR into contributions from each position. Component VaRs sum to total VaR.
```
CVaR_i = w_i * beta_i * VaR_p
```
where beta_i = Cov(R_i, R_p) / Var(R_p) is the asset's beta to the portfolio.
Equivalently:
```
CVaR_i = w_i * (partial VaR / partial w_i)
sum(CVaR_i) = VaR_p
```
This decomposition identifies which positions are the largest contributors to portfolio risk.
### Marginal VaR
Measures the rate of change of portfolio VaR with respect to a small increase in a position's weight.
```
MVaR_i = partial(VaR_p) / partial(w_i) = z_alpha * (Sigma * w)_i / sigma_p
```
Marginal VaR is used for position sizing: adding to a position with low marginal VaR reduces portfolio risk more efficiently.
### Scenario Analysis
Apply specific historical or hypothetical market moves to the current portfolio to estimate P&L impact.
- **Historical scenarios:** Replay actual market events (e.g., 2008 GFC, 2020 COVID crash, 2022 rate hiking cycle) with current holdings.
- **Hypothetical scenarios:** Construct custom shocks (e.g., "equities -20%, rates +200bp, credit spreads +300bp, USD +10%").
Scenario P&L is computed by applying the scenario returns to current position exposures and revaluing.
### Stress Testing
A structured framework for assessing portfolio resilience under extreme but plausible conditions.
Common stress scenarios:
- Equity crash: S&P 500 -30% to -40%
- Interest rate shock: +300bp parallel shift
- Credit crisis: investment-grade spreads +200bp, high-yield +800bp
- Liquidity freeze: bid-ask spreads widen 10x, forced selling at discount
- Currency shock: major currency pair moves 15-20%
- Stagflation: inflation +5%, GDP -3%, rates +200bp
Stress tests should include second-order effects: margin calls, liquidity demands, correlation spikes, counterparty risk.
### Factor-Based Risk Decomposition
Separate total portfolio risk into systematic factor risk and idiosyncratic (security-specific) risk.
```
sigma^2_p = b' * Sigma_f * b + sum(w_i^2 * sigma^2_epsilon_i)
```
where:
- b = vector of portfolio factor exposures
- Sigma_f = factor covariance matrix
- sigma^2_epsilon_i = idiosyncratic variance of asset i
Common factor models: Fama-French (market, size, value, momentum), Barra risk models, PCA-based statistical factors.
## Key Formulas
| Formula | Expression | Use Case |
|---------|-----------|----------|
| Parametric VaR (single) | W * z_alpha * sigma | Simple position VaR |
| Portfolio VaR | W * z_alpha * sqrt(w' * Sigma * w) | Multi-asset VaR |
| Multi-day VaR | VaR_1 * sqrt(h) | Scale to h-day horizon |
| CVaR (normal) | mu + sigma * phi(z_alpha) / (1 - alpha) | Expected tail loss |
| Component VaR | w_i * beta_i * VaR_p | Risk contribution per position |
| Marginal VaR | z_alpha * (Sigma * w)_i / sigma_p | Sensitivity to weight change |
| Factor Risk | b' * Sigma_f * b | Systematic risk component |
| Idiosyncratic Risk | sum(w_i^2 * sigma^2_epsilon_i) | Security-specific risk |
## Worked Examples
### Example 1: Parametric 95% VaR
**Given:** A $1,000,000 equity portfolio with an annualized volatility of 15%.
**Calculate:** 1-day 95% parametric VaR (assuming 252 trading days and zero expected daily return).
**Solution:**
Daily volatility:
```
sigma_daily = 0.15 / sqrt(252) = 0.15 / 15.875 = 0.00945
```
1-day 95% VaR:
```
VaR = $1,000,000 * 1.645 * 0.00945 = $15,545
```
Alternatively, computing directly from annual figures:
```
VaR_annual = $1,000,000 * 1.645 * 0.15 = $246,750
VaR_1day = $246,750 / sqrt(252) = $15,545
```
Interpretation: There is a 5% chance of losing more than $15,545 in a single day under normal market conditions.
### Example 2: Monte Carlo VaR
**Given:** A two-asset portfolio (60% equities, 40% bonds). Equities: mu = 10%, sigma = 18%. Bonds: mu = 4%, sigma = 5%. Correlation rho = -0.2. Portfolio value = $1,000,000.
**Calculate:** 95% annual VaR via Monte Carlo simulation (conceptual steps).
**Solution:**
1. **Construct covariance matrix:**
```
Sigma = | 0.0324 -0.0018 |
| -0.0018 0.0025 |
```
2. **Cholesky decomposition** of Sigma to get lower triangular matrix L.
3. **Simulate 10,000 scenarios:** For each simulation, draw z ~ N(0, I), compute r = mu + L*z, then portfolio return R_p = w' * r.
4. **Compute portfolio P&L** for each scenario: P&L = $1,000,000 * R_p.
5. **Sort P&L** from worst to best. The 500th worst (5th percentile) is the 95% VaR.
For this portfolio, the analytical answer provides a benchmark:
```
sigma_p = sqrt(0.6^2 * 0.0324 + 0.4^2 * 0.0025 + 2 * 0.6 * 0.4 * (-0.0018))
= sqrt(0.01105)
= 10.51%
VaR_95% = $1,000,000 * 1.645 * 0.1051 = $172,890
```
The Monte Carlo result should converge to approximately this value for a multivariate normal assumption.
### Example 3: Expected Shortfall
**Given:** From the Monte Carlo simulation above, tRelated in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.