Stress testing with options¶
Author: Artur Sepp / First recorded: 2026-09-14
Implemented in qis — Quantitative Investment Strategies. Software citation: CITATION.cff.
Option-portfolio stress testing revalues each contract after its underlying moves, rather than extending today’s delta across a large shock. This guide combines observed stock/ETF history with a synthetic short-option book to illustrate negative convexity: losses accelerate on the downside while short calls limit participation in an equity rally.
Overview¶
The example owns 100-share lots of AAPL, MSFT, AMZN, GOOGL and NVDA, and sells one call and one put position on every stock: five stocks, five short calls and five short puts. Calls cover the held shares; put quantities are about 1.5 times the stock lots. Puts are additional downside obligations, not protective hedges.
An EWMA model estimates the five stock responses to SPY, TLT, GLD and USO. Every stock and its two options share one fitted underlying response. The model therefore has five responses and four factors, even though the portfolio has fifteen holdings. The ETFs are risk proxies; they are not additional positions in the portfolio.
The ordinary InstrumentLeg call/put primitives are intrinsic payoffs. To retain time value,
this example supplies a public HoldingPayoff implementation priced by
VanillaOptionPricers (VOP). QIS owns scenario
completion, portfolio aggregation, risk and reporting. VOP is an example-only dependency;
importing qis does not import or require an option-pricing library.
The runnable source
and the generated short_convexity.pdf show full repricing beside the current-delta approximation.
This is an illustrative book, not a reconstruction of a client portfolio or its contract terms.
Inputs, notation, and assumptions¶
Convention |
This article |
|---|---|
Return basis |
Weekly log returns for estimation; factor shocks are log returns; P&L is revalued in currency |
Sampling grid |
Weekly |
Annualisation |
Annual covariance, 52 weekly periods per year; the band horizon \(\tau_{\mathrm{h}}\) is one month |
Mean adjustment |
None: EWMA moments about zero, |
Timing |
Holdings, loadings and option terms frozen at the valuation date \(t_0\) |
Output units |
USD P&L and decimal fractions of the net marked value \(V\) |
qis default |
EWMA span 52; 95% bounds exported alongside one- and two-sigma bands |
Input or symbol |
Meaning |
Convention |
|---|---|---|
\(t_0\) |
Frozen valuation date |
Default 2025-12-31; actual latest complete close at/before the requested cutoff |
\(S_i\) |
Current stock quote |
Yahoo |
\(y_{it}\) |
Stock return for estimation |
Weekly W-WED log return of Yahoo |
\(x_t\) |
Four ETF factor returns |
Weekly W-WED adjusted log returns, ordered SPY/TLT/GLD/USO |
\(B\) |
Stock-by-factor loading matrix |
Five rows, four columns; joint EWMA regression |
\(\Sigma_F\), \(d_i\) |
Factor covariance and stock residual variances |
Annualised with 52 weekly observations/year |
\(z\) |
Scenario factor vector |
Log returns; supplied simple bumps are converted by |
\(n_l\), \(m\) |
Signed option contracts and contract multiplier |
Negative contracts for shorts; 100 shares/contract |
\(K_l\), \(\tau_l\) |
Strike and remaining maturity |
USD/share and ACT/365 years at \(t_0\) |
\(r_{\mathrm{d}}\), \(q\) |
Pricing rate and dividend yield |
Assumed continuous 4% and 0%, held fixed in stresses |
\(\sigma_l\) |
Pricing volatility |
Assumed annual lognormal IV, not a downloaded option quote |
\(V\) |
Reporting denominator |
Current marked stock value plus signed option marks; positive USD amount |
\(\tau_{\mathrm{h}}\) |
Conditional-band horizon |
One month, \(1/12\) year; it does not advance option maturity |
Data and cache policy¶
The default download covers 2015-01-01 through 2025-12-31. The code explicitly requests
auto_adjust=False, retains both Close and Adj Close, and passes the next calendar day
as the exclusive end date. These arguments avoid relying on changing provider defaults.
See the yfinance download contract.
Only rows with all nine tickers and both price fields are used; missing observations are not filled with zero returns. The example rejects nonpositive or stale terminal prices and requires at least three 52-week spans for the fit. Factor history is cut at the valuation date; complete monthly vectors are used for historical scenario replay.
The first run saves a CSV and request/download metadata with a SHA-256 digest. Subsequent
runs verify and reuse those bytes without another price download. --refresh explicitly
requests a new download. Historical Yahoo values can be revised: a fixed cutoff alone does
not guarantee byte-identical future downloads. Keep the cache and provenance to reproduce
the numerical exhibit. No prices, API credentials or operational portfolios are committed.
Teaching contract construction¶
For each stock, the example buys the largest number of 100-share lots within USD 2m. It sells the same number of call contracts, and 1.5 times as many put contracts rounded down. Strikes are rounded to USD 5 increments. The per-stock call targets are 103%, 105%, 107%, 104% and 108% of spot; put targets are 97%, 95%, 93%, 96% and 92%.
Maturities are the third Fridays two, three, four, five and eight months after the valuation
month. These are synthetic teaching identifiers, formatted like
AAPL US 02/20/26 C280 Equity; they are not assertions that a matching exchange contract
is listed or tradable. An override of --as-of rebuilds strikes and maturities consistently.
There is no exchange-holiday adjustment in the teaching calendar.
A 63-trading-day EWMA realised volatility is annualised with 252 observations/year. The assumed call IV is the larger of 15% and 1.15 times that realised volatility. The put IV adds four volatility percentage points. These transparent assumptions introduce a modest premium and downside skew; neither is calibrated to a historical option surface.
Methodology¶
1. Estimate the joint EWMA risk model¶
Write \(\xi_t=(x_t^\top,y_t^\top)^\top\). With span \(N=52\), zero initial moments and no mean subtraction, the EWMA moment recursion is
The latest joint regression and annual factor covariance are
The model uses the complete factor covariance, not four independent univariate regressions.
It fits no intercept: moments are about zero, not de-meaned covariances. This is the explicit
MeanAdjType.NONE convention, and no drift or estimated alpha is added to a stress.
The latest \(B\) is applied to the estimation sample to calculate residuals
\(\varepsilon_t=y_t-Bx_t\) and their EWMA second moments:
estimate_ewm_factor_model supplies the loadings; compute_ewm_covar supplies factor and
residual moments; the complete snapshot is assigned to RiskModel. Residual covariance
between different stocks is discarded. Stocks and options on the same stock retain
shared residual risk through their aggregated dollar delta.
The supplied fit diagnostic is the non-centred EWMA \(R^2\):
It describes the weighted historical fit of the final loadings, not out-of-sample accuracy.
3. Price the options with VOP¶
For each contract define the forward \(\mathrm{Fwd}=S\exp((r_{\mathrm{d}}-q)\tau)\) and discount factor \(\mathrm{DF}=\exp(-r_{\mathrm{d}}\tau)\). The European Black-Scholes-Merton formulas are
Here \(\Phi\) is the standard normal distribution function. VOP’s compiled forward-grid pricer evaluates all shocked spots for one option. Values are per share; signed holding marks multiply by contracts times 100, once. See Black and Scholes (1973) and the VOP implementation.
The option holding change and total portfolio return are
Stocks use their signed share counts and spot changes. Option marks are negative for short positions. The denominator is the sum of the fifteen signed current marks, not gross stock exposure, option notional or a sum of absolute marks. Premium proceeds are not added a second time as a separate asset. There is no additional cash/debt position in this teaching book.
Current source marks are set equal to VOP model marks, so the QIS mark-to-model basis offset is zero. Zero shock gives zero P&L and preserves all fifteen source marks.
4. Convert Greeks correctly and measure convexity¶
VOP returns discounted forward delta but undiscounted forward gamma. If \(c=\exp((r_{\mathrm{d}}-q)\tau)\), their spot equivalents are
Multiplying gamma by the discount factor twice, omitting the forward-to-spot chain rule, or applying the contract multiplier twice would misstate risk while still producing plausible-looking prices.
For each holding, the shared-response dollar derivative is
For a stock holding it is shares times spot. Aggregate \(J_i=\sum_lJ_{li}\) before computing risk. In a small underlying simple-return move \(h\), the option contribution is approximately
Long vanilla gamma is positive; the signed gamma of every sold option is negative. The overlay’s quadratic term therefore detracts for both signs of \(h\). The separate option-sleeve panels isolate this effect. The difference between the full portfolio and its frozen log-delta approximation also includes the stock model’s exponential return mapping.
5. Compute conditional risk bands with stressed deltas¶
The conditional covariance, padded with zero anchor rows and columns, is
At each scenario re-evaluate the option deltas and form \(e(z)=B^\top J(z)/V\). For horizon \(\tau_{\mathrm{h}}=1/12\) year, QIS computes
The standard report displays \(R(z)\pm\sqrt{v(z)}\) and \(R(z)\pm2\sqrt{v(z)}\). The exported 95% pointwise bounds use approximately 1.96 standard deviations. These are scenario-local, linearised Gaussian bands, not exact nonlinear P&L quantiles. They do not include gamma/vega dispersion, volatility-surface shifts, jumps or uncertainty in the fit. The horizon scales covariance; option TTM and the central valuation date stay fixed.
Worked example¶
The frozen 2025-12-31 sample gives net marked value USD 8,726,094. The following option
lines illustrate the identifiers and signed quantities; the complete ten-row contract and
pricing table is exported as option_inventory.csv and included in the report appendix.
Synthetic Bloomberg-style identifier |
Contracts |
IV |
VOP value per share |
|---|---|---|---|
AAPL US 02/20/26 C280 Equity |
-73 |
19.38% |
USD 5.09 |
AAPL US 02/20/26 P265 Equity |
-109 |
23.38% |
USD 5.75 |
MSFT US 03/20/26 C510 Equity |
-41 |
20.62% |
USD 9.92 |
MSFT US 03/20/26 P460 Equity |
-61 |
24.62% |
USD 10.42 |
AMZN US 04/17/26 C245 Equity |
-86 |
31.93% |
USD 11.24 |
AMZN US 04/17/26 P215 Equity |
-129 |
35.93% |
USD 9.53 |
GOOGL US 05/15/26 C325 Equity |
-63 |
32.73% |
USD 21.65 |
GOOGL US 05/15/26 P300 Equity |
-94 |
36.73% |
USD 19.23 |
NVDA US 08/21/26 C200 Equity |
-107 |
39.18% |
USD 19.73 |
NVDA US 08/21/26 P170 Equity |
-160 |
43.18% |
USD 15.11 |
The main exhibit uses correlated SPY shocks. Values below are percentage points of current net marked value. The other ETF factors follow the latest EWMA conditional co-moves.
SPY move |
Full option repricing |
Current log-delta approximation |
Stocks |
Short calls |
Short puts |
|---|---|---|---|---|---|
-30% |
-84.15% |
-58.05% |
-43.69% |
+5.96% |
-46.42% |
-20% |
-51.54% |
-36.31% |
-29.98% |
+5.75% |
-27.31% |
-10% |
-21.70% |
-17.15% |
-15.41% |
+4.48% |
-10.77% |
0% |
0.00% |
0.00% |
0.00% |
0.00% |
0.00% |
+10% |
+11.27% |
+15.51% |
+16.26% |
-9.93% |
+4.95% |
+20% |
+15.73% |
+29.67% |
+33.36% |
-24.41% |
+6.78% |
+30% |
+17.26% |
+42.70% |
+51.30% |
-41.45% |
+7.41% |
At SPY -20%, short puts add a loss of 27.31 percentage points. Gains on sold calls offset only 5.75 points. At SPY +20%, the calls absorb most of the stock gain. The exact portfolio curve is therefore strongly asymmetric and bends below the current-delta approximation. Rounded components may differ from the rounded total by 0.01 percentage point.
These results were computed with VOP 2.2.0 and the QIS checkout on 2026-09-14, using the
Yahoo cache SHA-256
1e366949dd117c5ef2a62e810811598ada619f33fbf1e5dbbb4add7154e0f98b.
Generation date and data cutoff are distinct. The run records the actual QIS source hashes
and installed distribution metadata separately, because editable-install metadata can lag
checkout code. Recompute tables when changing the cache, sizing or option assumptions.
Implementation in qis¶
Use an environment with the instrument stress-report APIs (qis>=5.30.1), the data extra,
and the separate VOP package. From a QIS checkout:
python -m pip install -e ".[data]" "vanilla-option-pricers==2.2.0"
python -c "from examples.portfolios.stress_testing_with_options import Locals, run_local; run_local(Locals.REPORT, input_path='/absolute/cache/options_stress', output_path='/absolute/output/options_stress')"
On the maintainer’s Windows host, use the existing external environment and C-local paths:
. '..\ArturSepp\scripts\repo_governance\Enter-AgentRepo.ps1'
& 'C:\Python\QuantInvestStrats312\Scripts\python.exe' -c "from examples.portfolios.stress_testing_with_options import Locals, run_local; run_local(Locals.REPORT)"
The directory defaults
come from settings.yaml beside qis.local_path: ~/.qis/resources and ~/.qis/outputs.
For a one-run destination, pass C-local input_path and output_path arguments to
run_local; no process environment setting selects the configuration file.
The default cache is RESOURCE_PATH/options_stress; the default report destination is
OUTPUT_PATH/options_stress. Supply a fresh output_path to replay the cached input
on subsequent runs. Select Locals.CHECK without an output override to calculate and print
the key results without saving a report. The Python arguments as_of='YYYY-MM-DD' and
refresh=True select another frozen date and request another Yahoo download, respectively.
The example raises an error if data acquisition fails; it does not silently substitute
synthetic prices.
Step |
Public API or example function |
Output |
|---|---|---|
Download and freeze |
|
Raw and adjusted daily closes, metadata and hash |
Estimate |
|
Five-stock/four-factor EWMA snapshot and fit diagnostics |
Price options |
|
Signed BSM values and baseline/stressed response Jacobians |
Build positions |
|
Fifteen holdings sharing five underlying responses |
Stress |
|
Independent/correlated requests, historical ranking and four grids |
Report |
|
Standard PDF, numerical workbook, previews and hashed tables |
Explain convexity |
|
Four-panel teaching exhibit and full-precision CSV curves |
The output directory contains:
short_convexity.pdfand.png: full repricing versus log delta, stock/call/put contributions, short-option contributions by stock, and current signed option Greeks.spy_convexity.csv,spy_option_contributions.csv,option_inventory.csvandfit_diagnostics.csv: full-precision inputs to those exhibits.source_prices.csvandexample_provenance.json: observed sample, version/source identity, option-example hash, reporting denominator and numerical verification.report/portfolio_stress_report.pdf, the QIS workbook, individual page previews andreport/manifest.json: the complete standard report and artifact hashes.
The report includes the ten worst complete historical months, conditional covariance pages, scenario-local bands, and the option-terms appendix. EWMA does not supply fitted clustering topology, so the standard cluster pages explicitly report it as unavailable. No clusters are invented solely to fill those pages. TLT, GLD and USO requests are ETF-return shocks; a TLT move does not automatically change the option discount rate.
Verification¶
Every run checks the final betas against independent exponentially weighted least squares, residual variances against explicit weighted residual sums, unit delta/gamma against price finite differences, and put-call parity at matched terms. It also checks fifteen holdings, five calls/five puts, negative signed option gamma, zero-shock marks, full factor-delta finite differences and P&L attribution. The example harness checks parsing and public API usage; this yfinance example is intentionally excluded from unattended offline execution.
Ordinary source link: examples/portfolios/stress_testing_with_options.py.
"""Five yfinance stocks and ten short VOP-priced options under a four-factor EWMA model.
Run python -m examples.portfolios.stress_testing_with_options; select Locals.REPORT to export.
The first run downloads Yahoo data; subsequent runs replay a hashed local cache.
Set refresh=True to replace the cache. No Bloomberg access or client data is used.
"""
from enum import Enum
from dataclasses import dataclass, replace
from datetime import datetime, timezone
import hashlib
from importlib.metadata import version
import json
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import qis
# User-facing example dependency only; VOP is never imported by the qis package.
import vanilla_option_pricers as vop # noqa: TID251
STOCKS = ("AAPL", "MSFT", "AMZN", "GOOGL", "NVDA")
FACTORS = ("SPY", "TLT", "GLD", "USO")
AS_OF = "2025-12-31"
START = "2015-01-01"
SPAN = 52
ANNUALISATION = 52.0
def load_prices(cache_dir=None, as_of=AS_OF, refresh=False):
"""Download explicit raw/adjusted closes once, then replay their checked CSV bytes."""
import yfinance as yf
if cache_dir is None:
cache_dir = Path(qis.get_resource_path(create=True)) / 'options_stress'
cache = Path(qis.get_resource_path(cache_dir, create=True))
cut = pd.Timestamp(as_of).normalize()
path = cache / f"yahoo_{START}_{cut.date()}.csv"
record = path.with_suffix(".json")
expected = {"tickers": list(STOCKS + FACTORS), "start": START,
"as_of": str(cut.date()), "auto_adjust": False, "repair": False}
if refresh or not path.exists():
if path.exists() != record.exists() and not refresh:
raise ValueError("Incomplete cache; use refresh=True to rebuild it")
yf.set_tz_cache_location(str(cache / "yfinance"))
frame = yf.download(
list(STOCKS + FACTORS), start=START, end=str((cut + pd.Timedelta(days=1)).date()),
auto_adjust=False, repair=False, actions=False, threads=False, progress=False,
group_by="column", timeout=30,
)
if frame is None or frame.empty:
raise ValueError("Yahoo returned no prices; retry later or use an existing cache")
frame = frame.loc[:, pd.MultiIndex.from_product(
[["Close", "Adj Close"], STOCKS + FACTORS])].loc[:cut]
if frame.notna().sum().min() < 260:
raise ValueError("Every stock and factor needs at least 260 observed daily prices")
frame.to_csv(path)
record.write_text(json.dumps({**expected, "yfinance": version("yfinance"),
"downloaded_at_utc": datetime.now(timezone.utc).isoformat(),
"sha256": hashlib.sha256(path.read_bytes()).hexdigest()}, indent=2), encoding="utf-8")
metadata = json.loads(record.read_text(encoding="utf-8"))
if any(metadata.get(key) != value for key, value in expected.items()):
raise ValueError("Cache request metadata differs; use the matching cache or refresh=True")
if hashlib.sha256(path.read_bytes()).hexdigest() != metadata["sha256"]:
raise ValueError("Cached prices changed; use refresh=True for an intentional new download")
frame = pd.read_csv(path, header=[0, 1], index_col=0, parse_dates=True,
float_precision="round_trip")
frame.index = pd.DatetimeIndex(frame.index).tz_localize(None)
frame = frame.loc[:cut].sort_index()
if frame.index.has_duplicates:
raise ValueError("Duplicate price dates")
frame = frame.dropna()
if frame.empty or (cut - frame.index[-1]).days > 4 or (frame <= 0).any().any():
raise ValueError("Missing, stale or nonpositive common price panel")
return frame, metadata
def fit_risk_model(prices):
"""Fit joint EWMA betas and annual factor/residual moments on weekly log returns."""
adjusted = prices["Adj Close"]
fit = qis.estimate_ewm_factor_model(
asset_prices=adjusted[list(STOCKS)], factor_prices=adjusted[list(FACTORS)],
freq="W-WED", span=SPAN, mean_adj_type=qis.MeanAdjType.NONE,
)
date = fit.x.index[fit.x.index <= adjusted.index[-1]].max()
x, y = fit.x.loc[:date], fit.y.loc[:date]
if len(x) < 3 * SPAN or not np.isfinite(x.to_numpy()).all():
raise ValueError("Need at least three EWMA spans of complete weekly observations")
beta = fit.get_loadings_at_date(date).T.loc[list(STOCKS), list(FACTORS)]
residuals = y - x @ beta.T
factor_covar = pd.DataFrame(
ANNUALISATION * qis.compute_ewm_covar(x.to_numpy(), span=SPAN),
index=FACTORS, columns=FACTORS,
)
residual_var = pd.Series(np.diag(
ANNUALISATION * qis.compute_ewm_covar(residuals.to_numpy(), span=SPAN)), index=STOCKS)
# Assemble the assigned factor model; portfolio risk is computed exclusively by RiskModel.
covariance = beta @ factor_covar @ beta.T + pd.DataFrame(
np.diag(residual_var), index=STOCKS, columns=STOCKS)
risk_model = qis.RiskModel(
covar={date: covariance}, factor_loadings={date: beta},
factor_covar={date: factor_covar}, residual_vars={date: residual_var},
)
raw_var = np.diag(ANNUALISATION * qis.compute_ewm_covar(y.to_numpy(), span=SPAN))
diagnostics = pd.DataFrame({"r2": 1.0 - residual_var / raw_var,
"weekly_observations": len(x)}, index=STOCKS)
history = qis.to_returns(adjusted[list(FACTORS)], freq="ME", is_log_returns=True,
drop_first=True).loc[:adjusted.index[-1]].dropna()
return risk_model, date, history, diagnostics, x, y
@dataclass(frozen=True)
class BsmOptionPayoff:
"""Example-owned, USD European option mark with signed exchange-contract quantity.
Attributes:
underlying: Yahoo stock symbol identifying the actual USD quote.
option_type: C or P; the direction is carried by contracts, not the type.
strike: Strike in USD per share.
expiry: Synthetic contract expiry date, strictly after valuation_date.
valuation_date: Frozen mark date; no time elapses during instantaneous stresses.
volatility: Assumed annual lognormal implied volatility, fixed under shocks.
contracts: Signed number of contracts; negative for the short overlay.
multiplier: Shares per contract, normally 100.
rate: Continuously compounded USD rate, held fixed.
dividend_yield: Continuously compounded dividend yield, held fixed.
"""
underlying: str
option_type: str
strike: float
expiry: pd.Timestamp
valuation_date: pd.Timestamp
volatility: float
contracts: int
multiplier: int = 100
rate: float = 0.04
dividend_yield: float = 0.0
implementation_id = "qis.example.vop_european_option.v1"
coverage = "European BSM mark; fixed IV/rate/TTM; no American exercise or margin model."
boundary_policy = "Smooth BSM delta with positive TTM and volatility; no expiry crossing."
def __post_init__(self):
"""Reject invalid pricing terms before any report computation."""
if self.option_type not in ("C", "P") or self.ttm <= 0:
raise ValueError("Use C/P and an expiry after the frozen valuation date")
if self.strike <= 0 or self.volatility <= 0 or self.multiplier <= 0:
raise ValueError("Strike, volatility and multiplier must be positive")
@property
def ttm(self):
"""Return ACT/365 time remaining at the frozen valuation date."""
return (self.expiry - self.valuation_date).days / 365.0
def unit_prices(self, spots):
"""Call the compiled VOP forward-grid pricer, returning USD per underlying share."""
forwards = np.asarray(spots, dtype=float) * np.exp(
(self.rate - self.dividend_yield) * self.ttm)
return vop.compute_bsm_forward_grid_prices(
ttm=self.ttm, forwards=forwards, strike=self.strike, vol=self.volatility,
optiontype=self.option_type, discfactor=np.exp(-self.rate * self.ttm),
)
def spot_greeks(self, spot):
"""Convert VOP discounted forward delta and undiscounted forward gamma to spot Greeks."""
carry = np.exp((self.rate - self.dividend_yield) * self.ttm)
forward = float(spot * carry)
discount = np.exp(-self.rate * self.ttm)
delta = carry * vop.compute_bsm_vanilla_delta(
self.ttm, forward, self.strike, self.volatility, self.option_type, discount)
gamma = discount * carry**2 * vop.compute_bsm_vanilla_gamma(
self.ttm, forward, self.strike, self.volatility)
return delta, gamma
def evaluate(self, context: qis.PayoffContext) -> pd.Series:
"""Return signed scenario option marks; all quotes in this example are USD."""
if (context.reference_currency != "USD"
or context.quote_currencies[self.underlying] != "USD"):
raise ValueError("This example payoff supports USD quotes and reference currency only")
quotes = context.quotes[self.underlying]
values = self.contracts * self.multiplier * self.unit_prices(quotes.to_numpy())
return pd.Series(values, index=quotes.index)
def _jacobian(self, context, spot):
"""Apply the spot-to-log-quote chain rule and the public shared-response mapping."""
delta, _ = self.spot_greeks(spot)
dollars = self.contracts * self.multiplier * delta * spot
return dollars * context.quote_response_jacobian.loc[self.underlying]
def response_jacobian(self, context: qis.PayoffContext) -> pd.Series:
"""Return current signed dollar delta by underlying response."""
return self._jacobian(context, context.baseline_quotes[self.underlying])
def scenario_response_jacobian(self, context: qis.PayoffContext) -> pd.Series:
"""Recompute delta at the stressed spot for QIS conditional risk bands."""
return self._jacobian(context, context.quotes.iloc[0][self.underlying])
def build_portfolio(prices, model, risk_date):
"""Buy round lots of five stocks and sell one call/put line per stock."""
date = prices.index[-1]
spots = prices["Close"].iloc[-1]
returns = qis.to_returns(prices["Adj Close"][list(STOCKS)], is_log_returns=True,
drop_first=True)
realised = qis.compute_ewm_vol(returns, span=63, annualize=True,
annualization_factor=252).iloc[-1]
quotes = {stock: qis.Underlying(stock, float(spots[stock]), "USD", stock,
qis.ResponseBasis.LOCAL) for stock in STOCKS}
holdings, inventory = [], []
for i, stock in enumerate(STOCKS):
spot = float(spots[stock])
lots = int(2_000_000 / (100 * spot))
if lots < 1:
raise ValueError("Stock price exceeds the per-name teaching budget")
shares = 100 * lots
holdings.append(qis.PortfolioHolding(
f"{stock} US Equity", stock, shares * spot,
(qis.InstrumentLeg(qis.InstrumentType.DELTA_1, stock, shares),),
metadata={"short_name": stock, "sleeve": "Stocks"},
))
month = date.to_period("M") + (2, 3, 4, 5, 8)[i]
expiry = pd.date_range(month.start_time, month.end_time, freq="W-FRI")[2]
for kind, moneyness, quantity, skew in (
("C", (1.03, 1.05, 1.07, 1.04, 1.08)[i], -lots, 0.0),
("P", (0.97, 0.95, 0.93, 0.96, 0.92)[i], -int(1.5 * lots), 0.04),
):
strike = float(5 * np.round(spot * moneyness / 5))
option = BsmOptionPayoff(stock, kind, strike, expiry, date,
float(max(0.15, 1.15 * realised[stock]) + skew), quantity)
ticker = f"{stock} US {expiry:%m/%d/%y} {kind}{strike:g} Equity"
unit_price = float(option.unit_prices(np.array([spot]))[0])
delta, gamma = option.spot_greeks(spot)
mark = quantity * 100 * unit_price
holdings.append(qis.PortfolioHolding(
ticker, ticker, mark, payoff=option,
metadata={"short_name": f"{stock} {expiry:%b} {kind}{strike:g}",
"sleeve": "Short calls" if kind == "C" else "Short puts",
"expiry": str(expiry.date()), "strike": str(strike),
"contracts": str(quantity), "multiplier": "100",
"iv": str(option.volatility)},
))
inventory.append({"ticker": ticker, "underlying": stock, "type": kind,
"expiry": str(expiry.date()), "strike": strike, "contracts": quantity,
"multiplier": 100, "iv": option.volatility, "unit_price": unit_price,
"mtm_usd": mark, "spot": spot, "unit_spot_delta": delta,
"dollar_delta": quantity * 100 * delta * spot,
"dollar_gamma": quantity * 100 * gamma * spot**2})
denominator = sum(holding.observed_mtm for holding in holdings)
portfolio = qis.InstrumentPortfolio(
tuple(holdings), quotes, model, risk_date, date, "USD", denominator,
denominator_label="Net marked portfolio value",
)
return portfolio, pd.DataFrame(inventory).set_index("ticker")
def scenario_inputs():
"""Use independent requests, joint conditional comparisons and four correlated grids."""
anchors = {f"{factor} {bump:+.0%}": {factor: bump}
for factor, bumps in (("SPY", (-.3, -.2, -.1, .1, .2, .3)),
("TLT", (-.1, .1)), ("GLD", (-.2, .2)),
("USO", (-.3, .3))) for bump in bumps}
anchors["No move"] = {factor: 0.0 for factor in FACTORS}
requests = qis.StressScenarios(pd.DataFrame.from_dict(anchors, orient="index"),
convention=qis.ShockConvention.SIMPLE)
grids = {}
for factor in FACTORS:
limit = 30 if factor == "SPY" else 20
axis = pd.Index(np.arange(-limit, limit + 1) / 100.0, name=f"{factor} simple return")
grids[factor] = qis.StressScenarios(
pd.DataFrame({factor: axis.to_numpy()}, index=axis),
mode=qis.ScenarioMode.CONDITIONAL, convention=qis.ShockConvention.SIMPLE,
)
return requests, grids
def verify_example(portfolio, result, inventory, x, y):
"""Independently check EWMA least squares, option Greeks, parity and portfolio attribution."""
decay = 1.0 - 2.0 / (SPAN + 1)
weights = (1 - decay) * decay**np.arange(len(x) - 1, -1, -1)
root_w = np.sqrt(weights)[:, None]
reference_beta = np.linalg.lstsq(x.to_numpy() * root_w, y.to_numpy() * root_w, rcond=None)[0]
np.testing.assert_allclose(result.factor_loadings, reference_beta.T, atol=1e-10)
reference_residuals = y.to_numpy() - x.to_numpy() @ reference_beta
np.testing.assert_allclose(result.residual_variances,
ANNUALISATION * weights @ reference_residuals**2, rtol=1e-10)
assert len(portfolio.holdings) == 15
assert inventory.type.value_counts().to_dict() == {"C": 5, "P": 5}
assert inventory.contracts.lt(0).all() and inventory.dollar_gamma.lt(0).all()
zero = pd.Series(0.0, index=FACTORS)
np.testing.assert_allclose(portfolio.get_pnl(zero), 0.0, atol=1e-8)
for holding in portfolio.holdings:
if holding.payoff is None:
continue
option = holding.payoff
spot = portfolio.underlyings[option.underlying].spot0
h = spot * 1e-3
values = option.unit_prices(np.array([spot - h, spot, spot + h]))
delta, gamma = option.spot_greeks(spot)
np.testing.assert_allclose(delta, (values[2] - values[0]) / (2*h), atol=2e-5)
np.testing.assert_allclose(gamma, (values[2] - 2*values[1] + values[0]) / h**2,
rtol=5e-4, atol=1e-6)
call = replace(option, option_type="C").unit_prices(np.array([spot]))[0]
put = replace(option, option_type="P").unit_prices(np.array([spot]))[0]
parity = spot * np.exp(-option.dividend_yield * option.ttm) - option.strike * np.exp(
-option.rate * option.ttm)
np.testing.assert_allclose(call - put, parity, atol=1e-8)
for factor in FACTORS:
z = zero.copy()
z[factor] = 1e-5
derivative = (portfolio.get_pnl(z) - portfolio.get_pnl(-z)) / 2e-5
np.testing.assert_allclose(derivative, result.holding_factor_exposures[factor],
rtol=2e-5, atol=0.1)
for name, value in result.valuations.items():
np.testing.assert_allclose(result.attribution[name].sum(axis=1),
value.portfolio_pnl, atol=1e-7)
return {"status": "passed", "holdings": 15, "calls": 5, "puts": 5,
"checks": ["weighted least-squares betas", "weighted residual moments",
"zero-shock marks", "spot delta/gamma finite differences",
"put-call parity", "factor delta finite differences", "P&L attribution"]}
def convexity_exhibit(portfolio, result, inventory):
"""Plot full repricing, frozen-delta comparison and option-sleeve contributions through QIS."""
grid = result.grids["SPY"]
nav = portfolio.reporting_denominator
linear = grid.factor_log_shocks @ result.factor_exposures / nav
curves = pd.DataFrame({"Full option repricing": grid.portfolio_pnl / nav,
"Current log-delta approximation": linear})
sleeves = pd.DataFrame({name: grid.pnl[[holding.holding_id for holding in portfolio.holdings
if holding.metadata["sleeve"] == name]].sum(axis=1) / nav
for name in ("Stocks", "Short calls", "Short puts")})
stock_options = pd.DataFrame({stock: grid.pnl[inventory.index[
inventory.underlying.eq(stock)]].sum(axis=1) / nav for stock in STOCKS})
table = inventory.groupby("underlying").agg(
short_contracts=("contracts", "sum"), delta_usd=("dollar_delta", "sum"),
gamma_usd=("dollar_gamma", "sum")).reindex(STOCKS)
table["delta_usd"] = table.delta_usd.map(lambda x: f"{x/1e6:.2f}")
table["gamma_usd"] = table.gamma_usd.map(lambda x: f"{x/1e6:.2f}")
table.columns = ["Short contracts", "Option delta\n(USDm)", "Gamma x spot²\n(USDm)"]
fig, axes = plt.subplots(2, 2, figsize=(15, 10))
for ax, data, title in ((axes[0, 0], curves, "Correlated SPY: value versus current delta"),
(axes[0, 1], sleeves, "Stock and short-option contributions"),
(axes[1, 0], stock_options, "Short-option contribution by underlying")):
qis.plot_line(data, ax=ax, title=title, xlabel="SPY simple return",
ylabel="P&L / current net portfolio value", xvar_format="{:.0%}",
yvar_format="{:.0%}", linewidth=2, fontsize=10)
qis.plot_df_table(table, ax=axes[1, 1], fontsize=10,
title="Short-option overlay: signed current Greeks")
fig.suptitle("Five stocks + ten short options: the cost of negative convexity", fontsize=16)
fig.text(.06, .025, "Other ETFs follow EWMA conditional co-moves. Fixed IV, rates and TTM. "
"Gamma is signed option gamma multiplied by spot squared; premiums are model prices.",
fontsize=10)
fig.tight_layout(rect=(.02, .06, .98, .94))
return fig, curves.join(sleeves), stock_options
def run_example(cache_dir=None, output_dir=None, as_of=AS_OF, refresh=False):
"""Compute the reproducible book; optionally save a standard report and convexity exhibit."""
output = (Path(qis.get_output_path(output_dir, create=False))
if output_dir is not None else None)
if output is not None and output.exists():
raise FileExistsError("Use a fresh example output directory")
prices, source = load_prices(cache_dir, as_of, refresh)
model, date, history, diagnostics, x, y = fit_risk_model(prices)
portfolio, inventory = build_portfolio(prices, model, date)
requests, grids = scenario_inputs()
result = qis.run_portfolio_stress_test(
portfolio, requests, history, grids,
qis.StressTestConfig(horizon_years=1/12, confidence=.95),
)
verification = verify_example(portfolio, result, inventory, x, y)
fig, curves, contributions = convexity_exhibit(portfolio, result, inventory)
if output is not None:
output.mkdir(parents=True)
appendix = inventory[["expiry", "strike", "contracts", "iv", "unit_price"]].copy()
for column in ("strike", "unit_price"):
appendix[column] = appendix[column].map(lambda value: f"{value:.2f}")
appendix.iv = appendix.iv.map(lambda value: f"{value:.1%}")
config = qis.StressReportConfig(
title="Five-stock short-option portfolio", model_name="EWMA",
model_label="SPY / TLT / GLD / USO; weekly span 52", selected_grids=FACTORS,
response_diagnostics=diagnostics, write_previews=True,
appendix_table=appendix, appendix_title="Synthetic option terms and VOP prices",
appendix_notes=(
"Bloomberg-style IDs are synthetic teaching contracts, not fetched quotes.",
"100 shares/contract. Covered calls; puts are 1.5x stock lots, rounded down.",
"Fixed-IV European proxy; American exercise, margin and volatility shocks omitted.",
),
notes=("Observed Yahoo stock/ETF history; synthetic option positions and model prices.",
"Risk uses adjusted closes; option marks use unadjusted closing spot quotes.",
"Local Gaussian bands exclude gamma, vega, parameter and regime uncertainty."),
)
artifacts = qis.generate_portfolio_stress_report(result, output / "report", config)
fig.savefig(output / "short_convexity.pdf")
fig.savefig(output / "short_convexity.png", dpi=150)
inventory.to_csv(output / "option_inventory.csv")
diagnostics.to_csv(output / "fit_diagnostics.csv")
curves.to_csv(output / "spy_convexity.csv")
contributions.to_csv(output / "spy_option_contributions.csv")
prices.to_csv(output / "source_prices.csv")
provenance = {"source": source, "valuation_date": str(portfolio.valuation_date.date()),
"risk_date": str(date.date()), "span_weeks": SPAN, "annualisation": ANNUALISATION,
"reference_currency": "USD", "net_marked_value": portfolio.reporting_denominator,
"qis_distribution_version": version("qis"),
"qis_file": str(Path(qis.__file__).resolve()),
"qis_source_sha256": {str(path.relative_to(Path(qis.__file__).parent)):
hashlib.sha256(path.read_bytes()).hexdigest()
for path in sorted(Path(qis.__file__).parent.rglob("*.py"))},
"vop_version": version("vanilla-option-pricers"),
"example_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
"verification": verification}
(output / "example_provenance.json").write_text(
json.dumps(provenance, indent=2), encoding="utf-8")
print("Report:", artifacts.pdf_path)
print("Convexity exhibit:", output / "short_convexity.pdf")
plt.close(fig)
print(f"Valuation {portfolio.valuation_date.date()}; risk {date.date()}; "
f"net marked value USD {portfolio.reporting_denominator:,.0f}; "
"5 stocks + 5 short calls + 5 short puts; verification passed.")
print(curves.loc[[-.3, -.2, -.1, 0., .1, .2, .3]].to_string(float_format="{:.2%}".format))
return portfolio, result, inventory
class Locals(Enum):
CHECK = 1
REPORT = 2
def run_local(local: Locals, input_path: str = None, output_path: str = None,
as_of: str = AS_OF, refresh: bool = False):
"""Use YAML RESOURCE_PATH/OUTPUT_PATH, with explicit cache and report overrides."""
if local not in (Locals.CHECK, Locals.REPORT):
raise ValueError(local)
output = None
if local == Locals.REPORT or output_path is not None:
output = Path(qis.get_output_path(output_path, create=False))
if output_path is None:
output /= 'options_stress'
return run_example(cache_dir=input_path, output_dir=output, as_of=as_of, refresh=refresh)
if __name__ == "__main__":
run_local(local=Locals.CHECK)
Interpretation and limitations¶
The option positions, maturities, IVs, flat rates and zero dividend yields are teaching assumptions. The downloaded series are stock/ETF history, not historical option quotes.
US equity options are represented by European BSM marks. American exercise, discrete dividends, settlement, transaction costs, margin and liquidity are not modelled.
Contract terms and IV remain fixed across instantaneous shocks. Large downside scenarios can be more severe if implied volatility rises; this four-factor model does not estimate or condition a volatility-surface factor.
There are no knockout, autocall, accumulator or path-dependent states in this vanilla example. Such contracts need their own
HoldingPayoffimplementation and state assumptions.Current EWMA betas are extrapolated across large shocks. Idiosyncratic covariance between different stocks is omitted; historical-scenario ranking is a stress diagnostic, not a probability forecast or backtest of the short-option strategy.
Baseline volatility and scenario-local bands remain first-order risk measures. Neither negates the negative convexity revealed by full repricing. The Gaussian bands can cross -100%; they are not margin limits or exact loss quantiles.
See also¶
Factor stress testing: log-shock conversion and conditional covariance.
Instrument portfolios and stress reports: the public custom-payoff contract.
Tracking error and benchmark-relative risk:
RiskModelconventions.Composite-payoff example: a separate terminal-knockout teaching wrapper.
References¶
Black, F., and Scholes, M. (1973). The Pricing of Options and Corporate Liabilities. Journal of Political Economy, 81(3), 637–654. DOI: 10.1086/260062.
Kupiec, P. H. (1998). Stress testing in a value at risk framework. Journal of Derivatives, 6(1), 7–24. DOI: 10.3905/jod.1998.408008.
Anderson, T. W. (2003). An Introduction to Multivariate Statistical Analysis, 3rd edition. Wiley. Section 2.5: conditional distributions of the multivariate normal.
Sepp, A. VanillaOptionPricers. Software. Repository. Forward-price and Greek implementation; the example was verified with version 2.2.0.
Aroussi, R., and contributors. yfinance. Software. Download API.
Sepp, A. qis: Performance analytics, portfolio backtesting, risk analysis, and factsheet reporting in Python. Software citation metadata.