惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

G
Google Developers Blog
云风的 BLOG
云风的 BLOG
Google DeepMind News
Google DeepMind News
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - 三生石上(FineUI控件)
V
Visual Studio Blog
爱范儿
爱范儿
宝玉的分享
宝玉的分享
人人都是产品经理
人人都是产品经理
大猫的无限游戏
大猫的无限游戏
博客园 - 聂微东
月光博客
月光博客
雷峰网
雷峰网
L
LangChain Blog
Stack Overflow Blog
Stack Overflow Blog
B
Blog RSS Feed
有赞技术团队
有赞技术团队
T
Tailwind CSS Blog
阮一峰的网络日志
阮一峰的网络日志
V
V2EX
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
C
Check Point Blog
N
Netflix TechBlog - Medium
罗磊的独立博客
博客园 - 司徒正美
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
F
Full Disclosure
Security Archives - TechRepublic
Security Archives - TechRepublic
V
Vulnerabilities – Threatpost
H
Help Net Security
博客园 - 【当耐特】
博客园_首页
Microsoft Security Blog
Microsoft Security Blog
小众软件
小众软件
Hugging Face - Blog
Hugging Face - Blog
L
Lohrmann on Cybersecurity
C
Cybersecurity and Infrastructure Security Agency CISA
P
Privacy International News Feed
Blog — PlanetScale
Blog — PlanetScale
C
CERT Recently Published Vulnerability Notes
P
Privacy & Cybersecurity Law Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Cisco Talos Blog
Cisco Talos Blog
K
Kaspersky official blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Cyberwarzone
Cyberwarzone
S
Schneier on Security
S
SegmentFault 最新的问题
C
Cyber Attacks, Cyber Crime and Cyber Security
S
Securelist

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Volatility Risk Premium in 30 Lines of Python (And the 5 Mistakes That Wreck It)
tomasz dobro · 2026-05-11 · via DEV Community

The volatility risk premium (VRP) is the gap between what the options market prices in and what the underlying actually delivers. The formula fits in one line. The interesting part is in the inputs, the unit conversions, and a handful of mistakes that produce a plausible-looking but wrong number.

This post walks through the math, a worked SPY example, a self-contained Python implementation in 30 lines, and the five pitfalls I see in almost every homemade implementation.

TL;DR

VRP = sigma_IV - sigma_RV   # vol units
VRP_var = sigma_IV**2 - sigma_RV**2   # variance units

Enter fullscreen mode Exit fullscreen mode

Where:

  • sigma_IV is annualized implied vol (typically 30-day ATM IV)
  • sigma_RV is annualized realized vol over a matched window

If 30-day ATM IV is 18% and 30-day realized vol is 12%, VRP is +6 vol points. Positive on ~70 to 75% of trading days across major US equity indices over the last 30 years. That spread is the structural edge premium sellers harvest.

The formula is the easy part. Keep reading.

Vol vs variance: same idea, two units

Term Formula Units
Volatility risk premium σ_IV − σ_RV Annualized vol points
Variance risk premium σ_IV² − σ_RV² Annualized variance
Variance swap rate Model-free integral over the strip Variance

For most practitioner work, vol units are easier to reason about. For variance swaps and academic papers (Carr-Wu, Bollerslev), variance units are more rigorous. The rest of this post uses vol units. Square both inputs to translate.

The four inputs that actually matter

1. Which IV

"Implied volatility" is not one number. Every strike at every expiration has its own IV. The standard choice for VRP work is 30-day ATM IV, interpolated from the listed expirations that bracket 30 days.

  • 30 days matches the VIX horizon (comparability).
  • ATM is the least skewed point on the surface (central expectation, not tail demand).
  • Interpolation smooths weekend / earnings artifacts.

2. Which RV estimator

Three commonly used estimators, and they disagree by 1 to 3 vol points on the same day for the same window:

Estimator Inputs Bias
Close-to-close Daily closes Underestimates (no overnight gaps, no range)
Parkinson High, low Captures range, misses gaps
Yang-Zhang OHLC + prior close Lowest bias, the right default

This post uses close-to-close to keep the math readable. Production should use Yang-Zhang.

3. Window length and annualization

  • Match windows. 30-day IV pairs with 20 to 30 day RV.
  • Annualize daily SD by multiplying by sqrt(252). Forgetting this is the single most common error.
  • Trading days, not calendar days. Using 365 inflates RV by ~16%.

4. Z-score lookback

A 4% VRP is wide in a low-vol year and narrow in a high-vol year. Normalize:

z = (vrp_today - vrp_252d_mean) / vrp_252d_std

Enter fullscreen mode Exit fullscreen mode

z > 1 is the rich-premium tier. z < -0.5 is do-not-sell.

Worked example: SPY, by hand

Lock the formula in on paper before touching code.

1. 30-day ATM IV interpolated from the surface: 0.174 (17.4%)

2. Last 21 SPY closes, log returns:

r_t = ln(P_t / P_{t-1})

Enter fullscreen mode Exit fullscreen mode

Standard deviation of the 20 daily log returns: 0.00692

3. Annualize:

0.00692 * sqrt(252) = 0.00692 * 15.875 = 0.1099 = 10.99%

Enter fullscreen mode Exit fullscreen mode

4. Subtract:

VRP = 17.4% - 10.99% = +6.41%

Enter fullscreen mode Exit fullscreen mode

Variance form: 0.174**2 - 0.1099**2 = 0.01820.

Four arithmetic steps. Now the code.

Python in 30 lines

import numpy as np
import pandas as pd
import yfinance as yf


def compute_vrp(symbol: str, atm_iv_30d: float, rv_window: int = 20) -> dict:
    """
    Compute volatility risk premium for `symbol`.

    Parameters
    ----------
    symbol      : underlying ticker, e.g. "SPY"
    atm_iv_30d  : 30-day ATM implied vol, annualized, decimal (0.18 = 18%)
    rv_window   : trailing trading-day window for RV (default 20)
    """
    hist = yf.download(symbol, period="60d", progress=False, auto_adjust=False)
    closes = hist["Close"].dropna().tail(rv_window + 1)

    if len(closes) < rv_window + 1:
        raise ValueError(f"Not enough history for {symbol}")

    log_returns = np.log(closes / closes.shift(1)).dropna()
    rv = float(log_returns.std()) * np.sqrt(252)

    vrp_vol = atm_iv_30d - rv
    vrp_var = atm_iv_30d**2 - rv**2

    return {
        "symbol": symbol,
        "atm_iv_30d": atm_iv_30d,
        "rv_window": rv_window,
        "rv": rv,
        "vrp_vol_points": vrp_vol,
        "vrp_variance": vrp_var,
    }


if __name__ == "__main__":
    result = compute_vrp("SPY", atm_iv_30d=0.174, rv_window=20)
    print(f"ATM IV (30d):  {result['atm_iv_30d']:.2%}")
    print(f"RV (20d):      {result['rv']:.2%}")
    print(f"VRP (vol):     {result['vrp_vol_points'] * 100:+.2f} vol pts")
    print(f"VRP (var):     {result['vrp_variance']:+.5f}")

Enter fullscreen mode Exit fullscreen mode

Three implementation notes:

  1. np.log(closes / closes.shift(1)) is the canonical log-return idiom.
  2. The sqrt(252) is the only unit conversion. Drop it and your VRP is meaningless.
  3. This uses close-to-close. Swapping in Yang-Zhang only changes the rv = ... line.

The one input you cannot get from yfinance is the ATM IV. Either compute it from a chain (interpolate two listed expirations bracketing 30 days, take the ATM strike at each, time-weight) or pull it from a vol-surface API.

The five pitfalls

1. Forgetting sqrt(252)

Daily SD is around 0.005 to 0.015 for an index ETF. ATM IV is 0.10 to 0.30. Subtracting them looks wrong but produces a small negative number that is "in the right range." It is not in the right range. It is in different units.

Fix: Multiply daily SD by sqrt(252). First sanity check on any RV figure: is it the same order of magnitude as the IV?

2. Mismatched windows

30-day IV with 5-day RV swings violently with recent price action. The IV forecasts a month. The RV summarizes a week. The spread is mostly window-mismatch noise.

Fix: Match windows. 30-day IV pairs with 20 to 30 day RV.

3. Trading the raw spread

A 3% VRP at VIX 12 is wide. The same 3% at VIX 25 is narrow. Acting on the raw number ignores the regime.

Fix: Use the rolling 252-day z-score, not the raw number.

4. Close-to-close on gap-heavy names

Single stocks with regular earnings, ADRs, post-event reactions: close-to-close systematically understates RV. Apparent VRP looks rich. Real edge is smaller.

Fix: Yang-Zhang for any name with non-trivial overnight moves.

5. Lookahead bias in backtests

The classic. If you compute percentile thresholds from the entire history and apply them to a "sell when VRP is rich" rule, you are using future data to set today's threshold. Looks brilliant in-sample, falls apart out-of-sample.

Fix: Compute z-scores and percentiles using only data available at the trade-decision time:

df["vrp_z"] = (
    (df["vrp"] - df["vrp"].rolling(252).mean())
    / df["vrp"].rolling(252).std()
)

Enter fullscreen mode Exit fullscreen mode

rolling() is point-in-time by construction. Do not use full-sample mean and SD anywhere in your backtest pipeline.

From number to trade

Computing VRP is half the job. The sizing rule is the other half:

VRP z-score Action
z > 1.5 Aggressive selling, full size
0.5 to 1.5 Standard sizing
−0.5 to 0.5 Reduced size, defined risk only
z < −0.5 Sit out or hedge

Three questions decide the structure once z says go:

  1. Where is the edge directional? Put-side and call-side VRP are rarely equal.
  2. What is the dealer regime? 4% VRP in positive gamma is a different trade from the same 4% in negative gamma.
  3. Which structure fits? Short straddle, iron condor, put credit spread, jade lizard, calendar.

When to stop rolling your own

Computing VRP for one symbol on one date: 30 lines of Python.

Computing it correctly across many symbols and dates, with the directional decomposition, GEX-conditioned regime, and leak-free historical percentiles a real backtest needs: an infrastructure project that adds zero alpha.

I built FlashAlpha for this. GET https://lab.flashalpha.com/v1/vrp/{symbol} returns ATM IV, four matched RV windows (5d, 10d, 20d, 30d) using Yang-Zhang, the VRP for each, rolling z-score and percentile, put-call directional decomposition, GEX regime, and strategy suitability scores. The historical endpoint at historical.flashalpha.com/v1/vrp/{symbol}?at=<timestamp> returns the same shape with point-in-time z-scores for lookahead-free backtesting.

Free tier, no card. Useful as a sanity check against your own implementation:

import requests

resp = requests.get(
    "https://lab.flashalpha.com/v1/vrp/SPY",
    headers={"X-Api-Key": "YOUR_KEY"},
)
vrp = resp.json()["vrp"]

print(f"ATM IV:     {vrp['atm_iv']:.2f}%")
print(f"RV (20d):   {vrp['rv_20d']:.2f}%")
print(f"VRP (20d):  {vrp['vrp_20d']:+.2f}%")
print(f"Z-score:    {vrp['z_score']:+.2f}")

Enter fullscreen mode Exit fullscreen mode

Run your homemade compute_vrp against the 20-day RV and compare to vrp_20d. Within 0.1 vol point, your math and inputs are aligned. Off by more, work back through the five pitfalls.

Wrap

The VRP formula is a one-liner. Almost every homemade implementation gets the formula right and fails on at least one of: annualization, window matching, RV estimator choice, or leak-free percentile computation.

Compute it by hand once. Code it in 30 lines. Then either keep building the infrastructure or stop and use a feed. Either is fine. Mixing the two (homemade VRP with leaky percentiles fed into a "production" backtest) is the worst of both.


If you want the full systematic workflow (signal to execution to structure choice), the practical guide to trading VRP covers it end to end.