Skew history

View as MarkdownOpen the editor

Skew history tracks how much more puts, which pay when price falls, cost than calls over time.

A pane draws calls' implied volatility (how big a move option prices expect) minus puts', daily and per bar. Below zero, puts cost more and traders fear a drop, and the card says how unusual today's reading is. Panels add the term structure (near expiries' prices against far ones) against its past and daily moves in standard deviations. Use it to see fear build or fade, once 60 trading days of daily options data exist.

Under the hood: the recipe reads option_daily fields and option_surface through hasBit and isPartial. On each bar it asks for the nearest_days pick (Option surface, Chain page views). That is the one expiry nearest Expiry, days out with both wings at Expiry line, delta. The options kit's DayHistory keeps the percentiles, the z-score, the quantiles and each session's 1-day IV (Options kit). It draws the year's percentile in a named pane (Panes). The Sigma strip comes from a candles stream kept in a CandleList, with oneSigmaMove, as a panel.bars coloured per bar (Bars). The term structure draws as a panel.line over category maturities (Line panels), beside a render.hud card. It is also the skew-history template, the Skew History card under Beyond the time axis in the editor's starter list, and it compiles as written.

The wrun indicator

// Skew History: how this symbol's options skew moves over time. Skew is how much more puts cost than calls. A put pays
// when price falls, and a call pays when it rises. Here it is the risk reversal: the call's implied volatility (how big
// a move option prices expect) minus the put's. Below zero, puts cost more and traders fear a drop. A pane under the
// chart draws the daily 30-day skew and one expiry's skew on every bar. A card rates the skew against its own history.
// It also says how pricey puts far below the price are, and flags skew that moves against the price. A panel compares
// today's term structure (near expiries' prices against far ones) with its past. A strip shows each day's move in 1σ
// moves (one standard deviation). Use it to see fear build or fade.
//
// Technical notes: how the chart's underlying's options skew has moved, and where today's term structure sits in its
// own past. Four reads. The 30-day 25 delta risk reversal, one per session from the daily options statistics
// (option_daily: the call's IV minus the put's at the expiry nearest 30 days), drawn as a step line with its percentile
// and z-score against the window's earlier sessions. The risk reversal of one expiry, the one nearest the Expiry
// setting's days out, at 25 or 10 delta, read on every bar from the option surface (option_surface: one tuple per
// expiry with present bits per value; a bar the data plane marks partial, bit 14, draws on a dotted line of its own and
// is counted, never mixed into the solid line). The put tail of that same expiry: the 10 delta put's IV minus the 25
// delta put's, drawn on every solid bar, with its z-score against its last Put tail window solid readings in five steps
// (low at -1.5 or under, easing at -0.5 or under, normal, elevated at +0.5 or over, high at +1.5 or over); the window
// holds one expiry's readings and restarts when the picked expiry rolls. And the term structure now against its window:
// the at-the-money IV at seven constant maturities (7 days to a year) beside each one's median and 25th and 75th
// percentile over the window's sessions, in a panel below the chart. The surface line is also read against spot: over
// the Skew vs spot window, the close up by Spot move or more while the risk reversal falls by Skew move or more is puts
// bid into a rally, the close down while it rises is calls bid into a dip, and either tints the candles; both ends of
// the window must be solid bars on one expiry. A card at the bottom right names the skew (puts rich over 0.06 of the
// 30-day IV, calls rich below 0, flat between) with the numbers behind it. The statistics are short today (they start
// when the data plane switches the daily job on): the percentile, the z-score and the distribution need Minimum history
// (60 sessions), and until then the card says how many sessions there are. The surface's five-minute history is kept 30
// days, so older intraday bars arrive partial. Crypto, CME and US stock charts, daily or finer. Beside the window's
// percentile, the 30-day risk reversal's percentile over a fixed year, its last 252 sessions (the newest against the
// 251 before it), is drawn as a step line in a pane of its own and read on the card; it needs Minimum history too. And
// Sigma by session, a strip under the chart: each of the chart's newest closed daily candles (a session, keyed by the
// UTC day it opens on) has its close against its open over its 1σ move, the open x the prior session's 1-day ATM IV
// from the daily statistics x sqrt(1/252) (oneSigmaMove), the newest 60 sessions drawn.

param.int("days", 30, { min: 1, max: 365, label: "Expiry, days out", description: "The expiry line draws the skew of one expiry (the day the option ends) on every bar. It reads the expiry nearest this many days out, never one that ends today." });
param.choice("delta", ["25 delta", "10 delta"], "25 delta", { label: "Expiry line, delta", description: "Which options the expiry line compares: 25 delta sits a moderate distance from the price, 10 delta far out." });
param.int("lookback", 252, { min: 20, max: 520, label: "Window, sessions", description: "The past trading days the percentile, the z-score and the term panel compare against. 252 is about a year." });
param.int("min_sessions", 60, { min: 10, max: 520, label: "Minimum history, sessions", description: "The percentile, the z-score and the term panel show only after this many trading days of data." });
param.int("tail_bars", 72, { min: 10, max: 2000, label: "Put tail window, bars", description: "The put tail is how much more puts far below the price cost than nearer puts. Its z-score (standard deviations from average) uses this many recent bars with full options data. 72 is three days of hourly bars." });
param.int("vs_bars", 24, { min: 2, max: 500, label: "Skew vs spot window, bars", description: "The price move and the skew move run over this many bars. 24 is a day of hourly bars." });
param.number("vs_spot_pct", 1, { min: 0.1, max: 20, step: 0.1, label: "Spot move, percent", description: "How far the price must rise or fall over that window to count as a rally or a dip" });
param.number("vs_rr_points", 0.5, { min: 0.05, max: 10, step: 0.05, label: "Skew move, IV points", description: "How far the skew must fall or rise over that window to count as puts or calls getting pricier" });
param.bool("vs_tint", true, { label: "Tint candles on a divergence", description: "Colours candles where skew fights price: down for puts pricier in a rally, up for calls pricier in a dip." });
input("close", ohlcv.close); // the chart's own close: the grid
input("rr25", option_daily.rr25_30d, { missing: "nan", description: "The 30-day skew: the 25 delta call's IV minus the put's, in IV points, one reading per trading day" });
input("iv7", option_daily.atm_iv_7d, { missing: "nan", description: "The 7-day at-the-money IV, in percent" });
input("iv14", option_daily.atm_iv_14d, { missing: "nan", description: "The 14-day at-the-money IV, in percent" });
input("iv30", option_daily.atm_iv_30d, { missing: "nan", description: "The 30-day at-the-money IV, in percent" });
input("iv60", option_daily.atm_iv_60d, { missing: "nan", description: "The 60-day at-the-money IV, in percent" });
input("iv90", option_daily.atm_iv_90d, { missing: "nan", description: "The 90-day at-the-money IV, in percent" });
input("iv180", option_daily.atm_iv_180d, { missing: "nan", description: "The 180-day at-the-money IV, in percent" });
input("iv365", option_daily.atm_iv_365d, { missing: "nan", description: "The 365-day at-the-money IV, in percent" });
input("surface", option_surface.cells, { max_cells: 1800, pick: "nearest_days", days: "@days", delta: "@delta", description: "This symbol's options on each bar: only the expiry nearest the days set, with both sides at the chosen delta" }); // [expiry_ms, dte_days, forward, atm_iv, iv_p25, iv_c25, iv_p10, iv_c10, present] per expiry, in the surface's order
input("iv1d", option_daily.atm_iv_1d, { missing: "nan", description: "The 1-day at-the-money IV, in percent, one reading per trading day. The day before's reading sets each day's 1σ move (one standard deviation)." });
input("daily", candles.cells, { interval: "1d", bars: 64, description: "The newest 64 closed daily candles: each day's open and close for the Sigma strip" }); // [offset_ms, open, high, low, close, volume] per candle, oldest first
output("rr30", line, lower, { color: "theme.text", width: 2, step: true, label: "Skew 30d", format: "0.00", description: "The 30-day skew: the 25 delta call's IV minus the put's, in IV points, one per trading day" });
output("rr_expiry", line, lower, { color: "theme.text", opacity: 0.55, width: 1.5, label: "Skew, expiry", format: "0.00", description: "The chosen expiry's skew at the chosen delta: call IV minus put IV, in IV points, per bar" });
output("rr_partial", line, lower, { color: "theme.text", opacity: 0.55, width: 1.5, line_style: "dotted", label: "Skew, partial", format: "0.00", description: "The same reading on a bar with partial options data, drawn dotted and kept off the solid line" });
output("zero", line, lower, { role: "guide", color: "theme.muted", width: 1, line_style: "dashed", label: "0", description: "The zero line: below it, puts cost more than calls" });
output("rr_pct", none, lower, { description: "Where today's 30-day skew ranks among the window's earlier days, 0 to 100" });
output("rr_z", none, lower, { description: "Today's 30-day skew in standard deviations from the window's average" });
output("scaled", none, lower, { description: "Put IV minus call IV, divided by the 30-day IV: the number behind the skew verdict" });
output("skew_code", none, lower, { description: "0 calls rich (under 0), 1 flat, 2 puts rich (over 0.06). It reads 1 with no reading." });
output("expiry_days", none, lower, { description: "Days until the expiry the expiry line reads" });
output("partial_bars", none, lower, { description: "Bars so far with partial options data" });
output("sessions", none, lower, { description: "How many trading days of data the window holds" });
output("status", none, lower, { description: "0 not enough history yet, 1 the window reads, 2 bars longer than a day" });
output("tail", line, lower, { color: "theme.text", opacity: 0.32, width: 1, label: "Put tail", format: "0.00", description: "The put tail: the 10 delta put's IV minus the 25 delta put's, in IV points, per bar. High means crash cover is dear." });
output("tail_z", none, lower, { description: "The put tail in standard deviations from its average over the Put tail window. The window starts over when the expiry rolls. Empty on a bar without a reading." });
output("tail_code", none, lower, { description: "The put tail's z-score in five steps. 0 low (-1.5 or under), 1 easing (-0.5 or under), 2 normal, 3 elevated (+0.5 up), 4 high (+1.5 up). It reads 2 until the window holds enough bars, and again after the expiry rolls." });
output("spot_chg", none, lower, { description: "The price change over the Skew vs spot window, in percent" });
output("rr_chg", none, lower, { description: "The expiry line's skew change over the Skew vs spot window, in IV points. Empty unless both bars have full data on one expiry." });
output("vs_code", none, lower, { description: "0 puts pricier in a rally, 1 in line or no reading, 2 calls pricier in a dip" });
output("vs_on", none, lower, { description: "1 on a bar where skew moves against price and the candle takes the tint" });
output("rr_pct_1y", line, lower, { pane: "skew_pct", color: "theme.text", width: 1.5, step: true, label: "Skew percentile, 252 sessions", format: "0", description: "Where today's 30-day skew ranks among the 251 trading days before it, about a year, 0 to 100. Empty until Minimum history is met." });
pane("skew_pct", { title: "Skew percentile, 252 sessions", height_frac: 0.1, min: 0, max: 100, format: "0" });
string("read", { max_bytes: 64 }); // the headline
string("title", { max_bytes: 64 }); // the card's title
string("history_text", { max_bytes: 48 }); // "Percentile 18, z-score -1.42" or the wait
string("tail_text", { max_bytes: 48 }); // "Put tail elevated, z-score +1.07" or the wait
string("vs_text", { max_bytes: 56 }); // "Puts pricier in a rally, spot +2.00%, skew -1.00" or the wait
const termRows = frame("term_rows", { max_bytes: 4096 }); // one row per maturity: [label, now, median, 25th, 75th]
// The term structure now against its window: the maturities across, IV up; the frame carries the caption per run.
panel.line({ name: "term", title: "Term structure now against its past", x: "category", place: "below", frame: termRows, height_frac: 0.24, hover_card: true, format: "0.0", unit: "%", series: [
  { name: "Now", color: "theme.text", width: 2, points: true },
  { name: "Median", color: "theme.muted", width: 1.5 },
  { name: "25th", color: "theme.muted", width: 1, line_style: "dashed" },
  { name: "75th", color: "theme.muted", width: 1, line_style: "dashed" },
] });
render.barcolor("divergence_tint", { where: "vs_on", color_by: "vs_code", colors: ["theme.down", "theme.muted", "theme.up"] }); // the candles where skew moves against spot
const sigmaRows = frame("sigma_rows", { max_bytes: 6144 }); // the strip: one bar per session, oldest first
// Sigma by session under the chart: each bar a session's close against its open in 1σ moves, its colour the band
// (muted under 0.5, the text ink under 1, up or down from 1 on).
panel.bars({ name: "sigma_strip", title: "Sigma by session", x: "category", place: "below", frame: sigmaRows, orientation: "vertical", series: [{ name: "Sigma", color: "theme.text" }], format: "0.00", hover_card: true, legend_style: "title", height_frac: 0.12 });

render.hud("skew_card", {
  position: "bottom_right",
  title: "{{title}}",
  columns: 2,
  tiles: [
    tile.pill("Skew", "read", { headline: true }),
    tile.pill("Against its history", "history_text"),
    tile.pill("Put tail", "tail_text"),
    tile.pill("Skew vs spot", "vs_text"),
    tile.value("Skew, 30 days", "rr30", { format: "0.00" }),
    tile.rows([
      ["Skew, chosen expiry", "rr_expiry", "0.00"],
      ["Expiry, days out", "expiry_days", "int"],
      ["Skew over IV", "scaled", "0.000"],
      ["Percentile", "rr_pct", "0"],
      ["Percentile, 252 sessions", "rr_pct_1y", "0"],
      ["Z-score", "rr_z", "0.00"],
      ["Partial bars", "partial_bars", "int"],
    ]),
  ],
});

const DAY = 86400.0;
const TUPLE = 9; // option_surface: expiry_ms, dte_days, forward, atm_iv, iv_p25, iv_c25, iv_p10, iv_c10, present
const BIT_DTE = 1; // present bits: each value after expiry_ms, then the partial bar
const BIT_P25 = 4;
const BIT_C25 = 5;
const BIT_P10 = 6;
const BIT_C10 = 7;
const PUT_RICH = 0.06; // the scaled skew past which puts are rich (under 0, calls are)
const CAPACITY = 520;
const YEAR = 252; // the fixed window of the year's percentile, in sessions
const SIGMA_YEARS: f64 = 1.0 / 252.0; // one trading day: a session's 1σ move is its open x the 1-day IV x sqrt(1/252)
const DAY_MS: f64 = 86400000.0;
const STRIP = 60; // sessions the Sigma strip draws
const dailyCandles = new CandleList(64); // the chart's newest closed daily candles: the strip's sessions
const ivDays = new DayHistory(128); // the 1-day at-the-money IV per session, keyed by the UTC day its row lands on
const stripDay = new StaticArray<f64>(STRIP); // the strip's sessions, newest first: the day and the sigma
const stripSigma = new StaticArray<f64>(STRIP);
const TENORS = 7;
const TENOR_LABELS: String[] = ["7d", "14d", "30d", "60d", "90d", "180d", "1y"];
const MONTHS: String[] = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
const rrs = new DayHistory(CAPACITY); // one 30-day risk reversal per session
const terms: DayHistory[] = []; // one history per maturity
for (let k = 0; k < TENORS; k += 1) terms.push(new DayHistory(CAPACITY));
const termNow = new StaticArray<f64>(TENORS); // the newest session's IV per maturity
const dateClock = new Clock("UTC");
const TAIL_HIGH = 1.5; // the put tail's z-score steps
const TAIL_ELEVATED = 0.5;
const TAIL_WORDS: String[] = ["Put tail low", "Put tail easing", "Put tail normal", "Put tail elevated", "Put tail high"];
const VS_CAP = 501; // the window's buffer: the most bars back plus the bar itself
const vsClose = new StaticArray<f64>(VS_CAP); // each bar's close, solid risk reversal and expiry
const vsRr = new StaticArray<f64>(VS_CAP);
const vsExpiry = new StaticArray<f64>(VS_CAP);

let targetDays = 30.0; // settings, read in onStart()
let tenDelta = false;
let lookback = 252;
let need = 60;
let prevT: f64 = NaN; // the bar spacing
let barSec: f64 = NaN;
let rrNow: f64 = NaN; // the session readings, held
let pctNow: f64 = NaN;
let pctYearNow: f64 = NaN; // the newest session's percentile over the last YEAR sessions
let needYear = 60; // Minimum history, at most YEAR: the year's percentile shows from there
let zNow: f64 = NaN;
let scaledNow: f64 = NaN;
let iv30Now: f64 = NaN;
let partialBars = 0;
let lastDays: f64 = NaN; // the surface line's expiry, held for the card
let tailWindow = 72; // the put tail's window, read in onStart()
let tailZs = new Zscore(72); // rebuilt in onStart()
let tailCount = 0; // solid put tail readings so far
let tailZNow: f64 = NaN; // the newest solid reading's z-score, held for the card
let tailExpiry: f64 = NaN; // the expiry the window's readings come from: a roll restarts the window
let vsBars = 24; // the skew against spot settings, read in onStart()
let vsSpot = 1.0;
let vsMove = 0.5;
let vsTint = true;
let vsAt = 0; // bars so far: the next bar's slot in the window's buffer
let vsSpotNow: f64 = NaN; // the bar's spot move and skew move over the window
let vsRrNow: f64 = NaN;

function onStart(): void {
  targetDays = p_days();
  tenDelta = i32(p_delta()) == 1;
  lookback = i32(p_lookback());
  need = i32(p_min_sessions());
  if (need > lookback) need = lookback;
  needYear = i32(p_min_sessions());
  if (needYear > YEAR) needYear = YEAR;
  for (let k = 0; k < TENORS; k += 1) termNow[k] = NaN;
  tailWindow = i32(p_tail_bars());
  tailZs = new Zscore(tailWindow);
  vsBars = i32(p_vs_bars());
  vsSpot = p_vs_spot_pct();
  vsMove = p_vs_rr_points();
  vsTint = p_vs_tint() > 0.5;
}

function tenorInput(k: i32): f64 {
  if (k == 0) return in_iv7();
  if (k == 1) return in_iv14();
  if (k == 2) return in_iv30();
  if (k == 3) return in_iv60();
  if (k == 4) return in_iv90();
  if (k == 5) return in_iv180();
  return in_iv365();
}

// ── The surface on this bar: the expiry nearest targetDays with both wings served, and whether the bar is partial ──
let surfaceRr: f64 = NaN;
let surfaceDays: f64 = NaN;
let surfacePartial = false;
let surfaceTail: f64 = NaN;
let surfaceExpiry: f64 = NaN;
function readSurface(): void {
  surfaceRr = NaN;
  surfaceDays = NaN;
  surfacePartial = false;
  surfaceTail = NaN;
  surfaceExpiry = NaN;
  const n = in_surface_cells();
  if (n < TUPLE) return; // an empty bar: no surface, a gap in the line
  const cells = in_surface_view();
  const putBit = tenDelta ? BIT_P10 : BIT_P25;
  const callBit = tenDelta ? BIT_C10 : BIT_C25;
  const putAt = tenDelta ? 6 : 4;
  const callAt = tenDelta ? 7 : 5;
  let bestGap: f64 = Infinity;
  let bestExpiry: f64 = Infinity;
  for (let i = 0; i + TUPLE <= n; i += TUPLE) {
    const present = cells[i + 8];
    if (isPartial(present)) surfacePartial = true;
    if (!hasBit(present, BIT_DTE) || !hasBit(present, putBit) || !hasBit(present, callBit)) continue;
    const dte = cells[i + 1];
    if (!(dte >= 1.0)) continue; // an expiry that settles today never stands for a tenor
    const gap = Math.abs(dte - targetDays);
    const expiry = cells[i];
    if (gap < bestGap || (gap == bestGap && expiry < bestExpiry)) {
      bestGap = gap;
      bestExpiry = expiry;
      surfaceDays = dte;
      surfaceRr = cells[i + callAt] - cells[i + putAt];
      surfaceTail = hasBit(present, BIT_P10) && hasBit(present, BIT_P25) ? cells[i + 6] - cells[i + 4] : NaN;
      surfaceExpiry = expiry;
    }
  }
}

// ── The session readings, when a session lands ──
function measure(): void {
  rrNow = rrs.value(0);
  const ready = rrs.span(lookback) >= need;
  pctNow = ready ? rrs.percentile(lookback) : NaN;
  zNow = ready ? rrs.zscore(lookback) : NaN;
  pctYearNow = rrs.span(YEAR) >= needYear ? rrs.percentile(YEAR) : NaN;
  scaledNow = iv30Now > 0.0 ? -rrNow / iv30Now : NaN;
}

function skewCode(): f64 {
  if (isNaN(scaledNow)) return 1.0;
  return scaledNow > PUT_RICH ? 2.0 : scaledNow < 0.0 ? 0.0 : 1.0;
}

function tailCode(z: f64): f64 { // the five steps; 2 with no reading
  if (isNaN(z)) return 2.0;
  return z >= TAIL_HIGH ? 4.0 : z >= TAIL_ELEVATED ? 3.0 : z > -TAIL_ELEVATED ? 2.0 : z > -TAIL_HIGH ? 1.0 : 0.0;
}

function vsCode(spot: f64, rr: f64): f64 { // 0 puts bid into a rally, 2 calls bid into a dip, 1 in line or no reading
  if (isNaN(spot) || isNaN(rr)) return 1.0;
  if (spot >= vsSpot && rr <= -vsMove) return 0.0;
  return spot <= -vsSpot && rr >= vsMove ? 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 sbSigned(v: f64): void { // "+1.20", "-4.05"
  if (v >= 0.0) sb_text("+");
  sb_f64(v, 2);
}

// ── The term panel: each maturity now, its median and quartiles over the window ──
function writeTerm(): void {
  fb_clear();
  fb_text("{\"rows\":[");
  for (let k = 0; k < TENORS; k += 1) {
    if (k > 0) fb_text(",");
    fb_text("[");
    fb_str(TENOR_LABELS[k]);
    const h = terms[k];
    const ready = h.span(lookback) >= need;
    const now = termNow[k];
    fb_text(",");
    if (isNaN(now)) fb_text("null");
    else fb_f64(now, 2);
    for (let q = 0; q < 3; q += 1) {
      fb_text(",");
      const v = ready ? h.quantile(lookback, q == 0 ? 0.5 : q == 1 ? 0.25 : 0.75) : NaN;
      if (isNaN(v)) fb_text("null");
      else fb_f64(v, 2);
    }
    fb_text("]");
  }
  fb_text("],\"caption\":\"");
  const held = terms[2].span(lookback);
  if (held < need) {
    fb_text("Not enough history yet: ");
    fb_int(held);
    fb_text(" of ");
    fb_int(need);
    fb_text(" sessions");
  } else {
    fb_text("Now against ");
    fb_int(held);
    fb_text(" sessions");
  }
  fb_text("\"}");
  writeFrameBuffer(FRAME_TERM_ROWS);
}

// ── The Sigma strip: each closed daily candle's close against its open over its 1σ move ──
function priorIv(day: f64): f64 { // the newest daily 1-day IV of a day before day, a decimal; NaN with none
  for (let ago = 0; ago < ivDays.count(); ago += 1) {
    if (ivDays.day(ago) < day) return ivDays.value(ago) / 100.0;
  }
  return NaN;
}
function fbBand(s: f64): void { // the band's colour word
  const a = Math.abs(s);
  fb_text(a < 0.5 ? "theme.muted" : a < 1.0 ? "theme.text" : s < 0.0 ? "theme.down" : "theme.up");
}
function writeStrip(nowMs: f64): void { // the newest STRIP sessions with a reading, written oldest first; none, no strip
  let held = 0;
  for (let i = dailyCandles.count() - 1; i >= 0 && held < STRIP; i -= 1) {
    const day = Math.floor(dailyCandles.openSec(i) / DAY); // the session's day, the one its own statistics row lands on
    const open = dailyCandles.open(i);
    const s = (dailyCandles.close(i) - open) / oneSigmaMove(open, priorIv(day), SIGMA_YEARS); // the prior session's IV
    if (!isFinite(s)) continue;
    stripDay[held] = day;
    stripSigma[held] = s;
    held += 1;
  }
  if (held == 0) return;
  fb_clear();
  fb_text("{\"rows\":[");
  for (let k = held - 1; k >= 0; k -= 1) {
    if (k < held - 1) fb_text(",");
    fb_text("[\"");
    fbExpiryLabel(stripDay[k] * DAY_MS, nowMs, 0); // the session's date: a 00:00 UTC stamp reads as the date it names
    fb_text("\",{\"value\":");
    fb_f64(stripSigma[k], 3);
    fb_text(",\"color\":\"");
    fbBand(stripSigma[k]);
    fb_text("\"}]");
  }
  fb_text("],\"caption\":\"Each session's close against its open, in 1σ moves\"}");
  writeFrameBuffer(sigmaRows);
}

function writeWords(coarse: bool): void {
  const held = rrs.span(lookback);
  sb_clear();
  if (coarse) sb_text("Needs a daily or finer chart");
  else if (rrs.count() == 0) sb_text("Waiting for the daily options statistics");
  else {
    const code = skewCode();
    sb_text(code == 2.0 ? "Puts rich: skew " : code == 0.0 ? "Calls rich: skew " : "Flat: skew ");
    sbSigned(rrNow);
  }
  str_read_sb();
  sb_clear();
  if (coarse || rrs.count() == 0) sb_text("No history");
  else if (held < need) {
    sb_text("Not enough history yet: ");
    sb_int(held);
    sb_text(" of ");
    sb_int(need);
    sb_text(" sessions");
  } else {
    sb_text("Percentile ");
    sb_f64(pctNow, 0);
    if (!isNaN(zNow)) {
      sb_text(", z-score ");
      sbSigned(zNow);
    }
  }
  str_history_text_sb();
  sb_clear();
  if (coarse) sb_text("No reading");
  else if (tailCount < tailWindow) {
    sb_text("Put tail: ");
    sb_int(tailCount);
    sb_text(" of ");
    sb_int(tailWindow);
    sb_text(" bars");
  } else {
    sb_text(TAIL_WORDS[i32(tailCode(tailZNow))]);
    sb_text(", z-score ");
    sbSigned(tailZNow);
  }
  str_tail_text_sb();
  sb_clear();
  if (coarse) sb_text("No reading");
  else if (isNaN(vsSpotNow) || isNaN(vsRrNow)) {
    sb_text("Needs ");
    sb_int(vsBars);
    sb_text(" bars on one expiry");
  } else {
    const vs = vsCode(vsSpotNow, vsRrNow);
    sb_text(vs == 0.0 ? "Puts pricier in a rally" : vs == 2.0 ? "Calls pricier in a dip" : "In line with spot");
    sb_text(", spot ");
    sbSigned(vsSpotNow);
    sb_text("%, skew ");
    sbSigned(vsRrNow);
  }
  str_vs_text_sb();
  sb_clear();
  sb_text("Skew history, 25 delta");
  if (!coarse && rrs.count() > 0) {
    sb_text(", as of ");
    sbDay(rrs.day(0));
  }
  str_title_sb();
}

// onBar() runs once per bar: the spacing; the surface's expiry and its put tail on every bar, and the bar against the
// window's first bar for skew against spot; the session's statistics when they land (the risk reversal and each
// maturity's IV). Each bar writes the held session readings beside its own surface line.
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;
  dailyCandles.load(in_daily_view(), in_daily_cells(), t);
  readSurface();
  if (surfacePartial) partialBars += 1;
  const tailSolid = !coarse && !surfacePartial && !isNaN(surfaceTail);
  let tailZ: f64 = NaN;
  if (tailSolid) {
    if (surfaceExpiry != tailExpiry) { // the picked expiry rolled: its tails start a window of their own
      tailZs = new Zscore(tailWindow);
      tailCount = 0;
      tailExpiry = surfaceExpiry;
    }
    tailZ = tailZs.update(surfaceTail);
    tailCount += 1;
    tailZNow = tailZ;
  }
  const at = vsAt % VS_CAP;
  const close = in_close();
  vsClose[at] = close;
  vsRr[at] = coarse || surfacePartial ? NaN : surfaceRr;
  vsExpiry[at] = surfaceExpiry;
  vsSpotNow = NaN;
  vsRrNow = NaN;
  if (!coarse && vsAt >= vsBars) {
    const back = (vsAt - vsBars) % VS_CAP;
    if (vsClose[back] > 0.0) vsSpotNow = (close / vsClose[back] - 1.0) * 100.0;
    if (vsExpiry[back] == vsExpiry[at]) vsRrNow = vsRr[at] - vsRr[back];
  }
  vsAt += 1;
  const vs = vsCode(vsSpotNow, vsRrNow);
  if (!isNaN(surfaceDays)) lastDays = surfaceDays;
  const day = Math.floor(t / DAY);
  if (!coarse) {
    const iv30 = in_iv30();
    if (!isNaN(iv30) && iv30 > 0.0) iv30Now = iv30;
    for (let k = 0; k < TENORS; k += 1) {
      const v = tenorInput(k);
      if (!isNaN(v) && v > 0.0 && terms[k].push(day, v)) termNow[k] = v;
    }
    const rr = in_rr25();
    if (!isNaN(rr) && rrs.push(day, rr)) measure();
    ivDays.push(day, in_iv1d()); // a bar with no row reads NaN, which push() skips
  }
  out_zero(0.0);
  out_rr30(coarse ? NaN : rrNow);
  out_rr_expiry(coarse || surfacePartial ? NaN : surfaceRr);
  out_rr_partial(!coarse && surfacePartial ? surfaceRr : NaN);
  out_rr_pct(coarse ? NaN : pctNow);
  out_rr_z(coarse ? NaN : zNow);
  out_scaled(coarse ? NaN : scaledNow);
  out_skew_code(coarse ? 1.0 : skewCode());
  out_expiry_days(coarse ? NaN : lastDays);
  out_partial_bars(f64(partialBars));
  out_sessions(coarse ? NaN : f64(rrs.span(lookback)));
  out_status(coarse ? 2.0 : rrs.span(lookback) >= need ? 1.0 : 0.0);
  out_tail(tailSolid ? surfaceTail : NaN);
  out_tail_z(tailZ);
  out_tail_code(coarse ? 2.0 : tailCode(tailZNow));
  out_spot_chg(vsSpotNow);
  out_rr_chg(vsRrNow);
  out_vs_code(vs);
  out_vs_on(vsTint && vs != 1.0 ? 1.0 : 0.0);
  out_rr_pct_1y(coarse ? NaN : pctYearNow);
  if (bar.isLast()) {
    writeWords(coarse);
    if (!coarse) {
      writeTerm();
      writeStrip(t * 1000.0);
    }
  }
}

How it works

The session line. rr25_30d is the statistics' 30-day risk reversal, call IV minus put IV in volatility points: below zero the puts are dearer, the usual shape on a stock. Each session's reading joins a DayHistory; percentile() and zscore() read it against the window's earlier sessions.

The year's percentile. percentile(252) reads the same history over its last 252 sessions, about a year of trading days, whatever Window, sessions holds: the share of the 251 sessions before the newest that sit strictly below it, times 100. rr_pct_1y draws it as a step line in the skew_pct pane (0 to 100) and the card reads it as Percentile, 252 sessions. At the default window the two percentiles read the same; a window of 520 reads two years beside the fixed one.

The surface line. Every bar's option_surface block holds one tuple per expiry, [expiry_ms, dte_days, forward, atm_iv, iv_p25, iv_c25, iv_p10, iv_c10, present]. The module keeps the expiry whose dte_days is nearest the setting among those whose days and both wings are present (bits 1, 4 and 5 at 25 delta, bits 1, 6 and 7 at 10 delta), never an expiry that settles that day, and draws its call wing minus its put wing. When the nearest expiry lacks a wing the next nearest stands in. A bar with bit 14 set on any tuple is partial (older than the five-minute history the data plane keeps, or cut short): its reading goes to the dotted Skew, partial line, a floor of the data rather than a value.

The put tail. From the tuple the surface line keeps, the module reads iv_p10 minus iv_p25 when both are present (bits 6 and 4): how much dearer the 10 delta put is than the 25 delta put, in volatility points. A partial bar draws no put tail and is never counted. Each solid reading feeds a Zscore over the last Put tail window readings (the population deviation, the newest included). The window holds one expiry's readings and restarts when the picked expiry rolls, so a further expiry's wider tail never reads as a tail move. The newest z-score sets the step: high at +1.5 or over, elevated at +0.5 or over, easing at -0.5 or under, low at -1.5 or under, normal between. A high step says protection against a sharp fall is being bid harder than usual.

Skew against spot. Each bar keeps its close, the surface line's risk reversal on a solid bar and the expiry it read, in a buffer of the last 501 bars. Over the last Skew vs spot window bars, the spot move is the close against the close that many bars back, in percent, and the skew move is the risk reversal against its reading that many bars back, in volatility points. The skew move reads only when both bars are solid and read the same expiry, so a roll, a partial bar or an empty bar reads none. The close up by Spot move, percent or more while the risk reversal falls by Skew move, IV points or more is puts bid into a rally: the rally is being hedged, a warning. The close down by as much while the risk reversal rises by as much is calls bid into a dip: the dip may be bought. Either one tints the candles through the vs_on gate while Tint candles on a divergence is on, the down colour for puts bid and the up colour for calls bid.

The term panel. Each maturity's IV joins its own DayHistory; on the live bar quantile() reads the median and the quartiles over the window, and the panel draws them beside the newest session's curve.

The Sigma strip. The daily input is the chart's own daily candles, the newest 64 closed ones, kept in a CandleList that every bar feeds, and each daily row's 1-day at-the-money IV joins a DayHistory by the UTC day its row lands on. On the live bar each candle is a session, keyed by the UTC day it opens on (the day its own statistics row lands on): its close minus its open over oneSigmaMove(open, iv, 1 / 252), the IV the newest row of a day before it, so a session is priced on the IV it opened with and never on its own day's row. The newest 60 sessions with a reading draw as bars labelled by date, each in its band's colour: muted under 0.5, the text ink under 1, the up or down colour from 1 on.

What the settings do

  • Expiry, days out: The expiry line draws the skew of one expiry (the day the option ends) on every bar. It reads the expiry nearest this many days out, never one that ends today.
  • Expiry line, delta: Which options the expiry line compares: 25 delta sits a moderate distance from the price, 10 delta far out.
  • Window, sessions: The past trading days the percentile, the z-score and the term panel compare against: 252 is about a year.
  • Minimum history, sessions: The percentile, the z-score and the term panel show only after this many trading days of data.
  • Put tail window, bars: The put tail is how much more puts far below the price cost than nearer puts. Its z-score (standard deviations from average) uses this many recent bars with full options data. 72 is three days of hourly bars.
  • Skew vs spot window, bars: The price move and the skew move run over this many bars: 24 is a day of hourly bars.
  • Spot move, percent: How far the price must rise or fall over that window to count as a rally or a dip.
  • Skew move, IV points: How far the skew must fall or rise over that window to count as puts or calls getting pricier.
  • Tint candles on a divergence: Colours candles where skew fights price: down for puts pricier in a rally, up for calls pricier in a dip.
  • Skew: The verdict, puts rich, calls rich or flat, with today's 30-day skew in IV points.
  • Against its history: Where today's skew ranks in the window, as a percentile and a z-score (standard deviations from average).
  • Put tail: How much more puts far below the price cost than nearer puts, against the recent past. It reads low, easing, normal, elevated or high.
  • Skew vs spot: Whether skew moves against the price over the window: puts pricier in a rally or calls pricier in a dip.
  • Skew, 30 days: Today's 30-day skew: the 25 delta call's IV minus the put's, in IV points.
  • Skew, chosen expiry: The same gap on the expiry line's expiry, at the chosen delta.
  • Expiry, days out: Days until the expiry the expiry line reads.
  • Skew over IV: Put IV minus call IV over the 30-day IV: over 0.06 is puts rich, under 0 calls rich.
  • Percentile: Where today's 30-day skew ranks among the window's earlier days, 0 to 100.
  • Percentile, 252 sessions: The same rank over a fixed year, the last 252 trading days, whatever the window.
  • Z-score: Today's 30-day skew in standard deviations from the window's average.
  • Partial bars: How many bars so far had only partial options data.

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 the daily data too, once you accept the CME market data terms (Limitations). CME data is 10 minutes behind unless you have real-time CME data. The expiry line reads per-bar options data on crypto, CME and US stock charts (Option surface). Use a daily or intraday chart. Daily bars of the expiry line reach back without limit, and five-minute bars reach back 30 days.

When data is missing

The history starts the day OpenMarket switched on these daily readings. The daily skew line starts on the first trading day. The percentiles, the z-score and the term panel need Minimum history (60 trading days). Until then, the card and the panel's caption read "Not enough history yet: 12 of 60 sessions". A bar with no options data leaves a gap in both expiry lines. The card keeps the last expiry it read. Until the Put tail window is full, the card's Put tail line reads "Put tail: 31 of 72 bars". It counts only bars with full options data. In the editor's Console (the panel under the code), the put tail's step reads normal until then. The window starts over when the chosen expiry rolls to the next one. The card's Skew vs spot line reads "Needs 24 bars on one expiry" at first. It waits until the bar 24 back shares its expiry. That bar must have full data, so the reading waits a full window after each roll. 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". The Sigma strip shows each day's move in standard deviations. It draws once a closed daily candle has an IV reading from an earlier day.

Customize it

  • Another expiry. Set Expiry, days out to 7 for the weekly or 90 for the quarter.
  • Further wings. Switch Expiry line, delta to 10 delta to read the tails.
  • Another year. lookback sets the sessions the percentile, the z-score and the distribution read.
  • A calendar day on crypto. The Sigma strip prices one trading day as 1/252 of a year on every venue; on a coin that trades every day, set SIGMA_YEARS to 1.0 / 365.0.
  • A faster put tail. Set Put tail window to 24 for a day on an hourly chart, or 288 for a day on a five-minute chart.
  • A week against spot. On a daily chart set Skew vs spot window to 5, or turn Tint candles on a divergence off to read the divergence in the card alone.

Run it

  1. In the editor's Explorer, press the Templates icon and pick Skew History under Beyond the time axis.
  2. Press Run on a US stock's chart: the session line and the surface line fill as the statistics allow.
  3. At the editor's Console prompt, type rr30, rr_pct, rr_pct_1y, tail_z, vs_code and partial_bars.

Concepts used