Variance risk premium

View as MarkdownOpen the editor

Variance risk premium is for option sellers: do options price in bigger moves than the market then makes?

The pane draws implied volatility (how big a move option prices expect) beside realized volatility (how much price actually moved). Its premium is the implied volatility of a month ago minus the moves that followed: above zero, sellers got paid. A card names the zone: sell options, neutral or stand down. Use it to judge whether selling options pays now, once 60 premiums exist, about 81 trading days.

Under the hood: the recipe reads the 30-day at-the-money IV from option_daily. It reads a candles stream of the chart's own daily candles, kept in a CandleList (Calendar periods and candle lists). Two DayHistory rings from the options kit keep the IV and the completed premiums (Options kit). It draws the spread as columns coloured per bar by a sign value, beside a render.hud card in the chart's default look. It is also the vrp template, the Variance Risk Premium card under Beyond the time axis in the editor's starter list. It compiles as written.

The wrun indicator

// Variance Risk Premium: for option sellers, do options price in bigger moves than the market then makes? A pane under
// the chart draws implied volatility (how big a move option prices expect). It also draws realized volatility (how much
// price actually moved), and the gap between the two as columns. Then it draws the premium: the implied volatility of a
// month ago minus the moves that followed. Above zero, option sellers got paid for the risk they took. A card says sell
// options when the premium ranks high, and stand down when it ranks low or negative. Use it to judge whether selling
// options has paid lately.
//
// Technical notes: the chart's underlying's implied volatility against the volatility its price then delivered, from
// the daily options statistics (option_daily, the 30-day at-the-money IV per session) and the chart's own daily
// candles. Two readings, both in volatility points. The spread is today's 30-day IV minus the realized volatility of
// the last 21 daily returns (30 on crypto, which trades every day, so its month holds 30): known at once, but it
// compares the forecast with the past. The premium is the IV of that many sessions ago minus the realized volatility of
// the returns that followed it: the honest comparison, known only that many sessions later, so it is drawn on the
// session it completes, never on the session it starts. Realized volatility annualizes over 252 days a year, 365 on
// crypto. The premium's rank is its percentile among the window's earlier completed premiums; at or over the sell rank
// with a positive premium the options have paid their sellers (the sell zone), at or under the stand-down rank or with
// a negative premium they have not (the stand-down zone). A pane under the chart draws the IV and the realized
// volatility as step lines, the spread as columns and the premium as a line; a card at the bottom right reads the zone,
// the ratio and the numbers behind them. The statistics are short today (they start when the data plane switches the
// daily job on): the spread needs one session, the premium 22 sessions (31 on crypto), and its rank Minimum history
// (60) completed premiums; until then the card says how many there are. Daily or finer charts.

param.int("rv_days", 0, { min: 0, max: 63, label: "Realized window, days", description: "How many daily price changes each realized volatility measures. 0 is auto: 30 on crypto, which trades every day, and 21 elsewhere. Either way, that is the month the 30-day IV covers." });
param.int("lookback", 252, { min: 20, max: 520, label: "Rank window, sessions", description: "How many past premiums the rank compares against. 252 is about a year, or 8 months on crypto." });
param.int("min_sessions", 60, { min: 10, max: 520, label: "Minimum history, sessions", description: "Completed premiums needed before a rank shows. Until then the card counts them." });
param.number("sell_rank", 50, { min: 0, max: 100, step: 1, label: "Sell zone rank", description: "A premium ranked at or above this, and above zero, marks the sell zone." });
param.number("stand_rank", 20, { min: 0, max: 100, step: 1, label: "Stand-down rank", description: "A premium ranked at or below this, or below zero, marks the stand-down zone." });
input("close", ohlcv.close); // the chart's own close: the grid
input("iv30", option_daily.atm_iv_30d, { missing: "nan", description: "The 30-day implied volatility (IV) of this symbol's options, in percent, one reading per trading day" }); // lands on the first bar of its day, NaN elsewhere
input("daily", candles.cells, { interval: "1d", bars: 400, description: "This symbol's closed daily candles, the newest 400 and each new one as it closes, for the realized volatility" }); // [offset_ms, open, high, low, close, volume] per candle, oldest first
market.zone(); // the market's clock: 0 UTC on crypto, which trades every day (the realized window and year)
output("iv", line, lower, { color: "theme.text", opacity: 0.55, width: 1.5, step: true, label: "30-day IV", format: "0.00", unit: "%", description: "The newest 30-day IV, in percent" });
output("rv", line, lower, { color: "theme.text", opacity: 0.32, width: 1, step: true, label: "Realized vol", format: "0.00", unit: "%", description: "How much the price actually moved over the realized window, as a yearly percent. It counts 252 days a year, 365 on crypto." });
output("spread", histogram, lower, { color_by: "spread_sign", colors: ["theme.down", "theme.up"], opacity: 0.6, label: "IV minus realized", format: "0.00", description: "Today's 30-day IV minus the realized volatility up to today's close, in IV points" });
output("premium", line, lower, { color: "theme.text", width: 2, step: true, label: "Premium", format: "0.00", description: "The IV from one realized window ago minus the realized volatility that followed it, in IV points. It draws on the day it completes." });
output("zero", line, lower, { role: "guide", color: "theme.muted", width: 1, line_style: "dashed", label: "0", description: "The zero line" });
output("spread_sign", none, lower, { description: "1 when the IV is above the realized volatility, 0 below. It sets the columns' colour." });
output("zone", none, lower, { description: "0 stand down, 1 neutral, 2 sell zone. Empty until the premium has a rank." });
output("prem_rank", none, lower, { description: "Where the newest premium ranks among the window's earlier ones, 0 to 100" });
output("ratio", none, lower, { description: "The 30-day IV divided by the realized volatility" });
output("completed", none, lower, { description: "How many completed premiums the rank window holds" });
output("status", none, lower, { description: "0 waiting for history or candles, 1 the premium has a rank, 2 bars longer than a day" });
string("read", { max_bytes: 64 }); // the headline: the zone, or why there is none
string("title", { max_bytes: 64 }); // the card's title: the session the readings are as of
string("spread_text", { max_bytes: 48 }); // "IV over realized by 3.20 pts, 1.21x"

render.hud("vrp_card", {
  position: "bottom_right",
  title: "{{title}}",
  columns: 2,
  tiles: [
    tile.pill("Premium", "read", { headline: true }),
    tile.pill("Spread", "spread_text", { color_by: "spread_sign", colors: ["theme.down", "theme.up"] }),
    tile.value("Premium rank", "prem_rank", { format: "0" }),
    tile.rows([
      ["IV, 30 days", "iv", "0.00"],
      ["Realized vol", "rv", "0.00"],
      ["IV minus realized", "spread", "0.00"],
      ["Premium, completed", "premium", "0.00"],
      ["Premiums ranked", "completed", "int"],
    ]),
  ],
});

const DAY = 86400.0;
const CAPACITY = 520; // the most sessions each history keeps
const MAX_CANDLES = 420; // the daily candles kept: the stream's backlog and the window's days
const MONTHS: String[] = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
const ivs = new DayHistory(CAPACITY); // one 30-day IV per session
const premiums = new DayHistory(CAPACITY); // one completed premium per session, keyed by the session it starts
const days = new CandleList(MAX_CANDLES); // the chart's closed daily candles
const dateClock = new Clock("UTC");

let rvDays = 21; // settings, read in onStart()
let lookback = 252;
let need = 60;
let sellRank = 50.0;
let standRank = 20.0;
let yearDays = 252.0; // the year realized volatility annualizes over: 365 on crypto
let prevT: f64 = NaN; // the bar spacing
let barSec: f64 = NaN;
let pairedDay: f64 = NaN; // the newest session the spread has paired with its close
let doneDay: f64 = NaN; // the newest session whose premium completed (or can never complete)
let lastCandleT: f64 = NaN; // the newest candle seen: new work only when it moves
let rvNow: f64 = NaN; // the readings, held until the next session moves them
let spreadNow: f64 = NaN;
let ratioNow: f64 = NaN;
let premiumNow: f64 = NaN;
let rankNow: f64 = NaN;

function onStart(): void {
  const crypto = i32(p_market_zone()) == 0; // zone 0, UTC: a market that trades every day of the year
  rvDays = i32(p_rv_days()) > 0 ? i32(p_rv_days()) : crypto ? 30 : 21; // 0 is auto: a month of the market's sessions
  yearDays = crypto ? 365.0 : 252.0;
  lookback = i32(p_lookback());
  need = i32(p_min_sessions());
  if (need > lookback) need = lookback;
  sellRank = p_sell_rank();
  standRank = p_stand_rank();
}

function candleDay(i: i32): f64 {
  return Math.floor(days.openSec(i) / DAY);
}

/** The candle of day d, newest first; -1 when the list holds none. */
function candleOf(d: f64): i32 {
  for (let i = days.count() - 1; i >= 0; i -= 1) {
    const cd = candleDay(i);
    if (cd == d) return i;
    if (cd < d) return -1;
  }
  return -1;
}

/** The realized volatility of the daily log returns from candle first's close to candle last's, annualized, percent:
 *  the sample standard deviation, NaN under two returns or on a close that is not above 0. */
function realized(first: i32, last: i32): f64 {
  const n = last - first;
  if (n < 2 || first < 0) return NaN;
  let sum = 0.0;
  for (let k = first + 1; k <= last; k += 1) {
    const before = days.close(k - 1);
    const after = days.close(k);
    if (!(before > 0.0) || !(after > 0.0)) return NaN;
    sum += Math.log(after / before);
  }
  const mean = sum / f64(n);
  let squares = 0.0;
  for (let k = first + 1; k <= last; k += 1) {
    const r = Math.log(days.close(k) / days.close(k - 1)) - mean;
    squares += r * r;
  }
  return Math.sqrt((squares / f64(n - 1)) * yearDays) * 100.0;
}

// ── The spread: the newest session's IV against the realized volatility through its close ──
function pairSpread(): void {
  if (ivs.count() == 0) return;
  const d = ivs.day(0);
  if (d == pairedDay) return;
  const at = candleOf(d);
  if (at < 0) return; // its candle has not closed yet: the previous pairing holds
  const rv = realized(at - rvDays, at);
  pairedDay = d;
  rvNow = rv;
  const iv = ivs.value(0);
  spreadNow = isNaN(rv) ? NaN : iv - rv;
  ratioNow = rv > 0.0 ? iv / rv : NaN;
}

// ── The premium: each session's IV against the realized volatility of the rvDays returns after it ──
function completePremiums(): void {
  const newest = days.count() - 1;
  if (newest < 0) return;
  const oldestDay = candleDay(0);
  let moved = false;
  for (let ago = ivs.count() - 1; ago >= 0; ago -= 1) { // oldest session first
    const d = ivs.day(ago);
    if (!isNaN(doneDay) && d <= doneDay) continue;
    const at = candleOf(d);
    if (at < 0) {
      if (d < oldestDay) {
        doneDay = d; // older than every kept candle: it can never complete
        continue;
      }
      if (d < candleDay(newest)) {
        doneDay = d; // no candle that day (a holiday on the chart's own calendar): skipped
        continue;
      }
      break; // its candle has not closed yet, nor any later one
    }
    if (at + rvDays > newest) break; // not enough returns after it yet, nor after any later session
    const rv = realized(at, at + rvDays);
    doneDay = d;
    if (!isNaN(rv) && premiums.push(d, ivs.value(ago) - rv)) moved = true;
  }
  if (!moved) return;
  premiumNow = premiums.value(0);
  rankNow = premiums.span(lookback) >= need ? premiums.percentile(lookback) : NaN;
}

function zoneOf(): f64 { // 0 stand down, 1 neutral, 2 sell; NaN with no rank
  if (isNaN(rankNow)) return NaN;
  if (premiumNow < 0.0 || rankNow <= standRank) return 0.0;
  return rankNow >= sellRank ? 2.0 : 1.0;
}

function sbDay(day: f64): void { // "16OCT"
  dateClock.update(day * DAY);
  if (dateClock.dayOfMonth() < 10) sb_text("0");
  sb_int(dateClock.dayOfMonth());
  sb_text(MONTHS[dateClock.month() - 1]);
}

function writeWords(coarse: bool): void {
  const held = premiums.span(lookback);
  sb_clear();
  if (coarse) sb_text("Needs a daily or finer chart");
  else if (ivs.count() == 0) sb_text("Waiting for the daily options statistics");
  else if (isNaN(rankNow)) {
    sb_text("Not enough history yet: ");
    sb_int(held);
    sb_text(" of ");
    sb_int(need);
    sb_text(" premiums");
  } else {
    const z = zoneOf();
    if (z == 2.0) sb_text("Sell zone: options overpriced, rank ");
    else if (z == 0.0) sb_text(premiumNow < 0.0 ? "Stand down: options underpriced, rank " : "Stand down: thin premium, rank ");
    else sb_text("Neutral: premium rank ");
    sb_f64(rankNow, 0);
  }
  str_read_sb();
  sb_clear();
  if (coarse || ivs.count() == 0) sb_text("No spread");
  else if (isNaN(spreadNow)) {
    sb_text("Needs ");
    sb_int(rvDays + 1);
    sb_text(" daily closes");
  } else {
    sb_text(spreadNow >= 0.0 ? "IV over realized by " : "IV under realized by ");
    sb_f64(Math.abs(spreadNow), 2);
    sb_text(" pts");
    if (!isNaN(ratioNow)) {
      sb_text(", ");
      sb_f64(ratioNow, 2);
      sb_text("x");
    }
  }
  str_spread_text_sb();
  sb_clear();
  sb_text("Variance risk premium");
  if (!coarse && ivs.count() > 0) {
    sb_text(", as of ");
    sbDay(ivs.day(0));
  }
  str_title_sb();
}

// onBar() runs once per bar: the bar spacing; every closed daily candle the bar carries; the session's IV when it lands;
// then the spread when its close is in and every premium that completed. Each bar writes the held readings.
function onBar(): void {
  const t = bar.time();
  if (!isNaN(prevT) && t > prevT && (isNaN(barSec) || t - prevT < barSec)) barSec = t - prevT;
  prevT = t;
  const coarse = !isNaN(barSec) && barSec > 1.5 * DAY;
  days.load(in_daily_view(), in_daily_cells(), t);
  const iv = in_iv30();
  let landed = false;
  if (!coarse && !isNaN(iv) && iv > 0.0) landed = ivs.push(Math.floor(t / DAY), iv);
  const newestT = days.count() > 0 ? days.openSec(days.count() - 1) : NaN;
  if (!coarse && (landed || newestT != lastCandleT)) {
    lastCandleT = newestT;
    pairSpread();
    completePremiums();
  }
  out_zero(0.0);
  out_iv(coarse || ivs.count() == 0 ? NaN : ivs.value(0));
  out_rv(coarse ? NaN : rvNow);
  out_spread(coarse ? NaN : spreadNow);
  out_spread_sign(coarse || isNaN(spreadNow) ? NaN : spreadNow >= 0.0 ? 1.0 : 0.0);
  out_premium(coarse ? NaN : premiumNow);
  out_zone(coarse ? NaN : zoneOf());
  out_prem_rank(coarse ? NaN : rankNow);
  out_ratio(coarse ? NaN : ratioNow);
  out_completed(coarse ? NaN : f64(premiums.span(lookback)));
  out_status(coarse ? 2.0 : isNaN(rankNow) ? 0.0 : 1.0);
  if (bar.isLast()) writeWords(coarse);
}

How it works

Realized volatility. The sample standard deviation of rv_days daily log returns of the chart's own closes, annualized over 252 days a year, in percent: the same unit as the IV. The defaults follow the market's clock (market.zone()): rv_days 0 is auto, 21 returns on a US stock or a CME future and 30 on crypto, a month of the market's sessions either way, and crypto annualizes over 365 days, since it trades every day.

The spread pairs each session with its own close. The IV row of a session is its closing reading, so the spread waits for that session's daily candle: on a daily chart they arrive on the same bar; on an intraday chart the candle closes later, and until it does the previous pairing holds.

The premium completes a window later. Each session's IV is paired with the rv_days returns after its close (21, or 30 on crypto). On the bar the last of those candles closes, the premium of that session joins its own DayHistory (keyed by the session it starts on) and the line moves. A session with no candle of its own on the chart's calendar is skipped and never blocks the later ones.

The rank and the zone. percentile() over the newest lookback completed premiums. The zone is stand down when the premium is negative or the rank is at or under Stand-down rank (20), sell when the rank is at or over Sell zone rank (50), neutral between.

What the settings do

  • Realized window, days: How many daily price changes realized volatility measures, where 0 picks 30 on crypto and 21 elsewhere.
  • Rank window, sessions: How many past premiums the rank compares against: 252 is about a year, 8 months on crypto.
  • Minimum history, sessions: A rank shows only after this many completed premiums, so a short history never passes for a year.
  • Sell zone rank: A positive premium ranked at or above this marks the sell zone, where selling options has paid.
  • Stand-down rank: A premium ranked at or below this, or below zero, marks the stand-down zone, where selling has not paid.
  • Premium: The zone in words, sell, neutral or stand down, with the premium's rank.
  • Spread: Today's IV against the realized volatility so far: known at once, but it compares a forecast with the past.
  • Premium rank: Where the newest premium ranks among the window's earlier ones, 0 to 100.
  • IV, 30 days: Today's 30-day implied volatility, as a yearly percent.
  • Realized vol: How much the price actually moved over the realized window, as a yearly percent.
  • IV minus realized: Today's 30-day IV minus the realized volatility, in IV points.
  • Premium, completed: The IV of one window ago minus the moves that followed: the honest comparison, known only later.
  • Premiums ranked: How many completed premiums the rank window holds.

Where it runs

It works on coins with listed options, on a daily or intraday chart. A copy you run from the editor (the code panel beside the chart) reads the same data. On a US stock chart, every indicator that runs in your browser reads it. The data is 15 minutes behind unless you have real-time US options data. On a CME (Chicago futures exchange) futures chart, every indicator that runs in your browser reads it too, once you accept the CME market data terms (Limitations). CME data is 10 minutes behind unless you have real-time CME data. The daily candles come from this chart's own market.

When data is missing

The history starts the day OpenMarket switched on these daily readings, so it is short. The spread shows from the first trading day, since the candles reach back 400 days. The premium needs 22 trading days, or 31 on crypto. Its rank needs Minimum history (60) completed premiums, about 81 trading days in all, or 90 on crypto. Until then the card reads "Not enough history yet: 12 of 60 premiums" and names no zone. With too few daily closes, the card's Spread line reads "Needs 22 daily closes", or 31 on crypto. Before the first trading day, the card reads "Waiting for the daily options statistics". A chart with bars longer than a day reads "Needs a daily or finer chart".

Customize it

  • Another horizon. Set rv_days to 10 for two weeks of returns, or 63 for a quarter (the premium then completes that many sessions later); 0 goes back to the market's month.
  • Another year. lookback sets how many completed premiums the rank reads.
  • Other zones. Move Sell zone rank and Stand-down rank to the bands you act on.

Run it

  1. In the editor's Explorer, press the Templates icon and pick Variance Risk Premium under Beyond the time axis.
  2. Press Run on BTCUSDT's daily chart: the lines fill from the first session the statistics hold.
  3. At the editor's Console prompt, type spread, premium and prem_rank.

Concepts used