Module contents
Stage 1 of 8Advanced 100 min

Quotes, implied forward and implied volatility

Set up daily option-chain capture using free tools for personal use and, in parallel, a synthetic surface generator with known parameters to validate the project. Clean quotes, extract implied forward and discount via put-call parity, and implement implied-volatility inversion accurate across strikes.

After this lesson you can

  • Capture and store daily option-chain snapshots with their dates and times.
  • Filter quotes for liquidity, spread, and consistency and retain out-of-the-money options.
  • Estimate implied forward and discount by put-call parity regression.
  • Implement implied-volatility inversion with error below 1e-10, including in the wings.

Before you start

The project’s data contract

A surface begins with a snapshot, not a last traded price. Retain contract identifier, maturity and settlement time, strike, type, bid, ask, quote time, and capture time. The last trade may precede the current market; the midpoint is also an approximation and not necessarily an executable price.

The laboratory offers three paths: a synthetic chain with known parameters, a free historical sample, and a capture function for the official Alpaca endpoint. Its free indicative feed modifies quotes and delays trades; it requires an account and personal keys and must not be confused with the OPRA tape. The function paginates and saves Parquet plus JSON metadata; it does not save keys. Readers activate capture with their own credentials. Its fixture checks the code, while the historical sample below does contain observed quotes without individual times available.

The endpoint returns the latest quote, but the snapshot response does not provide daily volume or open interest under the contract used here. They are retained as unknown, not zero. Strict cleaning requires both; unknown values may be explicitly allowed for exploration, but that set must not be presented as liquidity-filtered. Settlement times are provided by maturity in UTC: they are not inferred from a date without knowing convention and calendar.

Chain cleaning rejects negative bids, crossed markets, zero midpoints, excessive relative spreads, stale quotes, and, where available, low volume and open interest. It also requires synchronized call-put pairs and avoids mixing duplicate contracts. These filters are sample choices: recording exclusions and thresholds matters as much as recording prices.

Forward and discount from parity

For European options with the same underlying, strike, and maturity,

C(K,T)−P(K,T)=D(T) [F(T)−K]=a−bK,b=D,F=a/b.C(K,T)-P(K,T)=D(T)\,[F(T)-K]=a-bK,\qquad b=D,\quad F=a/b.

Forward and discount estimation fits the intercept and slope of that line using available pairs. Using several strikes reduces sensitivity to one pair; it does not eliminate timing, spread, or early-exercise errors. For American options the European equality is not exact: use compatible European contracts or interpret the regression as an approximate diagnostic, not exact extraction. A bid-ask interval may contain a consistent relationship even when midpoints do not satisfy it.

Once F,DF,D are estimated, the out-of-the-money call for K≥FK\ge F and out-of-the-money put for K<FK<F represent time value without subtracting a large intrinsic amount. Check each type’s bounds before inversion. A relative-spread filter can systematically eliminate cheap wings; retain exclusions to avoid confusing selection with economic information.

Inverting the price

With v=σTv=\sigma\sqrt T, d1=log⁡(F/K)/v+v/2d_1=\log(F/K)/v+v/2 and d2=d1−vd_2=d_1-v, the Black price of a call is D(FΦ(d1)−KΦ(d2))D(F\Phi(d_1)-K\Phi(d_2)). The put price is D(KΦ(−d2)−FΦ(−d1))D(K\Phi(-d_2)-F\Phi(-d_1)). For T,F,K,D>0T,F,K,D>0, vega is

∂C∂σ=DFϕ(d1)T>0.\frac{\partial C}{\partial\sigma}=DF\phi(d_1)\sqrt T>0.

This monotonicity guarantees a unique finite solution for a price strictly inside its bounds, but does not guarantee it is easy to find. In wings or short maturities vega can be near zero: a tiny price error can imply a large volatility error. Uncontrolled Newton can leave the domain; the safeguarded inverter maintains a bracket and uses bisection when a step is unsafe. The upper bound is asymptotic and has no finite solution.

InteractiveWhere Newton gets lost
  • Blue: iterations
  • Red: failure
Newton without safeguards
Newton with bisection
0.10
Newton failures across 651 points454
Safeguarded failures0
Synthetic Black data with F = 100 and volatility 0.27. The horizontal axis is log(K/F)/(0.27√T), from −3 to 3; the vertical runs from one week at the bottom to two years at the top. Red marks failure in 25 steps. Both maps generate and invert prices with the same CDF approximation; they diagnose iterations, not machine precision.

The implementation of Jäckel, Let’s Be Rational uses specialized approximations and reformulations for high accuracy. This lesson’s method is Newton with bisection; it is not presented as an implementation of that algorithm. It is compared with Brent and, when available, the Jäckel reference. Price and volatility tolerances are different quantities.

Local laboratory: capture and synthetic chain

The cell implements the complete pipeline and runs the synthetic workflow. It requires NumPy, SciPy, pandas, and a Parquet engine such as PyArrow. Local cells share a session in this lesson. Alpaca capture is activated when the reader supplies keys and settlement times; the independent historical sample is downloaded below.

[ ]Chain, parity, and inverterLocal GPU
from pathlib import Path
import os,json,re,urllib.parse,urllib.request,datetime
import numpy as np
import pandas as pd
from scipy.special import ndtr
from scipy.optimize import brentq

def black(F,K,T,df,sigma,is_call):
 F,K,T,df,sigma,is_call=np.broadcast_arrays(F,K,T,df,sigma,is_call); vol=sigma*np.sqrt(T); d1=np.log(F/K)/vol+vol/2;d2=d1-vol
 call=F*ndtr(d1)-K*ndtr(d2);put=K*ndtr(-d2)-F*ndtr(-d1)
 return df*np.where(is_call,call,put)
def implied_vol(price,F,K,T,df,is_call,tol=2e-14,maxiter=100):
 P,F,K,T,df,is_call=np.broadcast_arrays(np.asarray(price,float),np.asarray(F,float),np.asarray(K,float),np.asarray(T,float),np.asarray(df,float),np.asarray(is_call,bool))
 if np.any(F<=0) or np.any(K<=0) or np.any(T<=0) or np.any(df<=0): raise ValueError('Entradas positivas requeridas')
 intrinsic=df*np.where(is_call,np.maximum(F-K,0),np.maximum(K-F,0));upper=df*np.where(is_call,F,K)
 invalid=(~np.isfinite(P))|(P<intrinsic)|(P>=upper);at_lower=~invalid&(P==intrinsic);active=~invalid&~at_lower
 lo=np.zeros(P.shape);hi=np.full(P.shape,8.);sigma=np.full(P.shape,.2);result=np.where(at_lower,0.,np.nan);iters=np.zeros(P.shape,int)
 bracket=black(F,K,T,df,hi,is_call)>=P;active &= bracket
 for n in range(maxiter):
  if not np.any(active):break
  v=sigma*np.sqrt(T);d1=np.log(F/K)/v+v/2;value=black(F,K,T,df,sigma,is_call);res=value-P;vega=df*F*np.exp(-d1*d1/2)*np.sqrt(T)/np.sqrt(2*np.pi)
  lo=np.where(active&(res<0),sigma,lo);hi=np.where(active&(res>=0),sigma,hi)
  done=active&((np.abs(res)<=tol*np.maximum(1,np.abs(P)))|((hi-lo)<=tol));result=np.where(done,sigma,result);iters=np.where(done,n+1,iters);active &= ~done
  step=sigma-res/np.maximum(vega,1e-300);sigma=np.where(active,np.where((step>lo)&(step<hi)&(vega>1e-14),step,(lo+hi)/2),sigma)
 status=np.where(at_lower,'limite cero',np.where(np.isfinite(result),'ok',np.where(invalid,'fuera o cota superior','sin convergencia')))
 return result,status,iters

def snapshot_alpaca(symbol,key,secret,request=None):
 if not re.fullmatch(r'[A-Z.]{1,8}',symbol): raise ValueError('Símbolo inválido')
 if not key or not secret: raise ValueError('Faltan credenciales de Alpaca')
 root='https://data.alpaca.markets/v1beta1/options/snapshots/'+symbol;pages=[];token=None;seen=set();started=datetime.datetime.now(datetime.timezone.utc).isoformat()
 def fetch(url):
  req=urllib.request.Request(url,headers={'APCA-API-KEY-ID':key,'APCA-API-SECRET-KEY':secret,'Accept':'application/json'})
  with urllib.request.urlopen(req,timeout=30) as resp:return json.load(resp)
 fetch=request or fetch
 for _ in range(200):
  params={'feed':'indicative','limit':1000}
  if token:params['page_token']=token
  page=fetch(root+'?'+urllib.parse.urlencode(params))
  if not isinstance(page,dict) or 'snapshots' not in page:raise RuntimeError('Respuesta incompleta o error del proveedor')
  pages.append(page);token=page.get('next_page_token')
  if not token:break
  if token in seen:raise RuntimeError('Paginación repetida')
  seen.add(token)
 else:raise RuntimeError('Demasiadas páginas; instantánea incompleta')
 rows=[];unparsed=0
 for page in pages:
  for contract,entry in page.get('snapshots',{}).items():
   match=re.fullmatch(r'([A-Z.]+)(\d{6})([CP])(\d{8})',contract)
   if not match:unparsed+=1;continue
   root_symbol,expiry,kind,strike=match.groups(); quote=entry.get('latestQuote') or {}
   rows.append({'contract':contract,'expiry':pd.to_datetime(expiry,format='%y%m%d',utc=True),'kind':'call' if kind=='C' else 'put','K':int(strike)/1000,'bid':quote.get('bp'),'ask':quote.get('ap'),'bid_size':quote.get('bs'),'ask_size':quote.get('as'),'quote_time':quote.get('t'),'volume':np.nan,'open_interest':np.nan})
 if not rows:raise RuntimeError('No hay contratos reconocibles en la respuesta')
 frame=pd.DataFrame(rows);meta={'symbol':symbol,'started_utc':started,'captured_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'feed':'indicative','pages':len(pages),'unparsed_contracts':unparsed,'volume_open_interest':'no proporcionados por snapshots'}
 return frame,meta

def save_snapshot(frame,meta,directory):
 directory=Path(directory);directory.mkdir(parents=True,exist_ok=True);stamp=meta['captured_utc'].replace(':','-');stem=directory/(meta['symbol']+'-'+stamp)
 if Path(str(stem)+'.parquet').exists() or Path(str(stem)+'.json').exists():raise FileExistsError('La instantánea ya existe')
 frame.to_parquet(str(stem)+'.parquet',index=False);Path(str(stem)+'.json').write_text(json.dumps(meta,ensure_ascii=False,indent=2),encoding='utf8');return stem

def prepare_snapshot(frame,meta,expiries_utc):
 x=frame.copy();asof=pd.Timestamp(meta['captured_utc']);quote=pd.to_datetime(x.quote_time,utc=True,errors='coerce')
 dates=x.expiry.dt.strftime('%Y-%m-%d');expiry=pd.to_datetime(dates.map(expiries_utc),utc=True,errors='coerce')
 if expiry.isna().any():raise ValueError('Falta hora de liquidación UTC para algún vencimiento')
 x['T']=(expiry-asof).dt.total_seconds()/(365*86400);x['quote_age_s']=(asof-quote).dt.total_seconds()
 return x

def synthetic():
 rng=np.random.default_rng(30301);records=[]
 for T in [.25,.5,1.]:
  F=100*np.exp(.02*T);df=np.exp(-.03*T)
  for K in np.linspace(75,130,23):
   k=np.log(K/F);sigma=.22-.08*k+.15*k*k
   for kind in ['call','put']:
    P=float(black(F,K,T,df,sigma,kind=='call'));spread=max(.02,.015*P);mid=max(0.,P+rng.uniform(-spread*.05,spread*.05))
    records.append(dict(T=T,K=K,kind=kind,bid=max(0,mid-spread/2),ask=mid+spread/2,volume=100,open_interest=1000,quote_age_s=0))
 rows=pd.DataFrame(records);rows.loc[0,'ask']=rows.loc[0,'bid']-.1;rows.loc[1,'volume']=0;return rows

def clean(rows,max_rel_spread=.5,min_volume=1,min_oi=10,allow_unknown_liquidity=False):
 x=rows.copy();required=['T','K','kind','bid','ask','volume','open_interest','quote_age_s'];missing=set(required)-set(x.columns)
 if missing: raise ValueError('Faltan columnas: '+str(missing))
 x['mid']=(x.bid+x.ask)/2; spread=x.ask-x.bid;known=x.volume.notna()&x.open_interest.notna()
 liquid=(x.volume.isna()|(x.volume>=min_volume))&(x.open_interest.isna()|(x.open_interest>=min_oi))&(known|allow_unknown_liquidity)
 x['ok']=(x['T']>0)&(x.K>0)&x.kind.isin(['call','put'])&(x.bid>=0)&(x.ask>=x.bid)&(x.mid>0)&(spread/x.mid<=max_rel_spread)&(x.quote_age_s>=0)&(x.quote_age_s<=900)&liquid
 return x[x.ok].copy()

def parity(group):
 if group.duplicated(['K','kind']).any():raise ValueError('Contratos duplicados: selecciona el mismo estilo y vencimiento')
 pairs=group.pivot(index='K',columns='kind',values=['mid','quote_age_s']).dropna()
 pairs=pairs[(pairs['quote_age_s']['call']-pairs['quote_age_s']['put']).abs()<=60]
 K=pairs.index.to_numpy();y=(pairs['mid']['call']-pairs['mid']['put']).to_numpy()
 if len(K)<3:raise ValueError('No hay pares suficientes')
 a,slope=np.linalg.lstsq(np.column_stack([np.ones(len(K)),K]),y,rcond=None)[0];df=-slope;F=a/df
 if df<=0 or F<=0:raise ValueError('Forward o descuento no válidos')
 return F,df,len(K),float(np.sqrt(np.mean((y-(a+slope*K))**2)))

def make_otm(group,F,df):
 x=group.copy();intrinsic=pd.Series(df*np.where(x.kind=='call',np.maximum(F-x.K,0),np.maximum(x.K-F,0)),index=x.index);upper=pd.Series(df*np.where(x.kind=='call',F,x.K),index=x.index)
 otm=((x.kind=='call')&(x.K>=F))|((x.kind=='put')&(x.K<F))
 return x[otm&(x.mid>=intrinsic)&(x.mid<upper)].copy()

raw=synthetic();filtered=clean(raw);print('synthetic rows',len(raw),'clean',len(filtered))
for T,group in filtered.groupby('T'):
 F,df,n,rmse=parity(group);otm=make_otm(group,F,df);iv,status,it=implied_vol(otm.mid,F,otm.K,T,df,otm.kind=='call');print('T',T,'F',round(F,6),'df',round(df,6),'parity pairs',n,'RMSE',round(rmse,6),'OTM ok',np.count_nonzero(status=='ok'),'of',len(otm))
fixture1={'snapshots':{'TEST270101C00100000':{'latestQuote':{'bp':2.,'ap':2.2,'bs':5,'as':6,'t':'2026-11-17T15:00:00Z'}}},'next_page_token':'second'}
fixture2={'snapshots':{'TEST270101P00100000':{'latestQuote':{'bp':1.9,'ap':2.1,'bs':7,'as':8,'t':'2026-11-17T15:00:05Z'}}},'next_page_token':None}
frame,meta=snapshot_alpaca('TEST','fake-key','fake-secret',request=lambda url:fixture2 if 'page_token=' in url else fixture1)
assert len(frame)==2 and meta['pages']==2 and frame.iloc[0]['K']==100 and pd.isna(frame.iloc[0]['volume'])
fixture_meta={**meta,'captured_utc':'2026-11-17T15:01:00Z'}
prepared_fixture=prepare_snapshot(frame,fixture_meta,{'2027-01-01':'2027-01-01T21:00:00Z'})
assert len(clean(prepared_fixture))==0 and len(clean(prepared_fixture,allow_unknown_liquidity=True))==2
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
 stem=save_snapshot(frame,meta,folder);saved=pd.read_parquet(str(stem)+'.parquet');assert len(saved)==2
print('fixture sintética, paginación y almacenamiento',len(frame),meta['feed'])
F=100;df=.97;vol=.27; rows=[]
for T in [7/365,30/365,.25,.5,1,2]:
 for z in np.linspace(-3,3,61):
  K=F*np.exp(z*vol*np.sqrt(T));is_call=K>=F;P=black(F,K,T,df,vol,is_call);v,status,it=implied_vol(P,F,K,T,df,is_call);ref=brentq(lambda x:float(black(F,K,T,df,x,is_call)-P),.001,4,xtol=1e-14)
  rows.append((abs(v-vol),abs(v-ref),abs(float(black(F,K,T,df,v,is_call)-P)),it))
a=np.array(rows);print('rejilla',len(a),'máximos error σ, Brent, precio, iteraciones',a.max(axis=0))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The synthetic run generated 138 rows and the filter retained 135. For T = 0.25, 0.5, and 1 year, regression returned F = 100.502117, 101.009225, and 102.020815 respectively, with D = 0.992638, 0.985156, and 0.970388; introduced noise prevents them from being exactly the generating parameters. The two-page and Parquet test uses synthetic responses, not provider data.

The grid contains 366 OTM options, six maturities between one week and two years, and 61 values between −3 and 3 normalized deviations. With generating volatility 0.27 and discount 0.97, maximum error was 2.36e-13 in volatility against the generator, 2.36e-13 against Brent, and 1.10e-13 in round-trip price. The maximum iteration count was 12. These bounds apply to that identifiable grid, not to quotes arbitrarily close to the bounds.

[ ]Optional capture with personal credentialsLocal GPU
# Cambia RUN_LIVE solo en tu laboratorio. No imprimas ni guardes las claves.
RUN_LIVE=False
if RUN_LIVE:
    symbol=os.environ['ALPACA_SYMBOL']
    frame,meta=snapshot_alpaca(symbol,os.environ['APCA_API_KEY_ID'],os.environ['APCA_API_SECRET_KEY'])
    # Introduce las horas de liquidación reales en UTC según las condiciones del contrato.
    expiries_utc=json.loads(os.environ['OPTION_EXPIRIES_UTC_JSON'])
    prepared=prepare_snapshot(frame,meta,expiries_utc)
    path=save_snapshot(prepared,meta,'capturas')
    print('Instantánea guardada:',path,'filas:',len(prepared),'feed:',meta['feed'])
    print('Liquidez desconocida:',int(prepared.volume.isna().sum()))
    for expiry,group in clean(prepared,allow_unknown_liquidity=True).groupby('expiry'):
        try:
            F,D,n,rmse=parity(group); otm=make_otm(group,F,D)
            v,status,_=implied_vol(otm.mid,F,otm.K,otm['T'],D,otm.kind=='call')
            print('vencimiento',expiry,'pares',n,'forward',F,'descuento',D,'RMSE paridad',rmse,'IV válidas',np.count_nonzero(status=='ok'))
        except ValueError as error:
            print('vencimiento descartado',expiry,':',error)
else:
    print('Captura real desactivada; solo se ejecutó la prueba sintética.')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Do not assume a snapshot satisfies parity: select European contracts with the same settlement, check corporate adjustments and times, and compare results within their spreads. For a chain with unknown liquidity, using allow_unknown_liquidity=True is an explicit relaxation. It does not concatenate histories from different days as if simultaneous.

To automate daily capture outside this session, the next cell builds a standalone script from the functions just run. It first checks in a temporary directory that it can be imported. If you enable WRITE_CAPTURE_SCRIPT, it writes captura_opciones.py without overwriting it. Schedule it on your system on market days, with keys and symbol in the process environment. Each run saves UTC time, feed, and pages; respect provider limits and terms.

[ ]Prepare daily scriptLocal GPU
import inspect,importlib.util
def build_capture_script(path):
    preamble="from pathlib import Path\nimport os,json,re,urllib.parse,urllib.request,datetime\nimport numpy as np\nimport pandas as pd\n"
    functions="\n".join(inspect.getsource(f) for f in (snapshot_alpaca,save_snapshot))
    main="""
if __name__ == '__main__':
    frame,meta=snapshot_alpaca(os.environ['ALPACA_SYMBOL'],os.environ['APCA_API_KEY_ID'],os.environ['APCA_API_SECRET_KEY'])
    path=save_snapshot(frame,meta,'capturas')
    print('Instantánea guardada:',path,'filas:',len(frame),'feed:',meta['feed'])
"""
    path=Path(path)
    with path.open('x',encoding='utf8') as out:out.write(preamble+functions+main)
    return path
with TemporaryDirectory() as folder:
    script=build_capture_script(Path(folder)/'captura_opciones.py')
    spec=importlib.util.spec_from_file_location('captura_prueba',script);module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
    simulated,info=module.snapshot_alpaca('TEST','x','y',request=lambda url:fixture2 if 'page_token=' in url else fixture1)
    assert len(simulated)==2 and info['pages']==2
    print('Script independiente importado y paginación sintética comprobada.')
WRITE_CAPTURE_SCRIPT=False
if WRITE_CAPTURE_SCRIPT:
    print('Script creado:',build_capture_script('captura_opciones.py'))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Install vollib in the laboratory environment for the independent comparison. Its Black function takes the continuous rate equivalent to the discount, which here is −log(D)/T. The implementation is based on Jäckel and is evaluated on the same OTM prices; accuracy is not extrapolated to rounded prices or more extreme tails.

[ ]Comparison with JäckelLocal GPU
from vollib.black.implied_volatility import implied_volatility_of_discounted_option_price as jackel
F=100.;df=.97;vol=.27;errors=[];roundtrip=[]
for T in [7/365,30/365,.25,.5,1,2]:
 for z in np.linspace(-3,3,61):
  K=F*np.exp(z*vol*np.sqrt(T));flag='c' if K>=F else 'p'
  P=float(black(F,K,T,df,vol,flag=='c'));ours,_,_=implied_vol(P,F,K,T,df,flag=='c')
  ref=jackel(P,F,K,-np.log(df)/T,T,flag)
  errors.append(abs(float(ours)-ref));roundtrip.append(abs(float(black(F,K,T,df,ref,flag=='c'))-P))
print('casos',len(errors),'máximo error de σ frente a Jäckel',max(errors),'máximo error de precio de ida y vuelta',max(roundtrip))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In the run with vollib 1.0.11, maximum volatility error against the reference was 2.35e-13 and the reference round-trip price error was 1.73e-14 in those 366 cases. This figure belongs to the experiment reproduced here, not a guarantee for all quotes.

An observed historical chain

The free HistoricalData.net provider sample contains contracts from September 15, 2022. Download only the daily ZIP member using range requests and save the CSV and provenance metadata, including actual UTC download time and SHA-256. Check the file license before reuse. Download time is not quote time: in this file quote_time is empty, so age and bid-ask simultaneity across contracts cannot be checked.

In the November 17, 2026 capture, 354 European PM SPXW contracts expiring September 30, 2022 were filtered for volume of at least one and open interest of at least ten. Regression on 81 pairs at strikes 3600 to 4200 produced forward 3912.0782, discount 0.9990083, and RMSE 0.0995. Using 15/365 as an explicit approximation to time to maturity, 244 OTM options with relative spread up to 0.5 admitted Black inversion, with median 0.26877. The exact observation or settlement time used in that approximation is unknown and quotes have not been verified as simultaneous. These are exploratory diagnostics, not executable prices or arbitrage evidence. The cell requires network access and runs explicitly; Alpaca capture remains the route for strict age controls.

[ ]Download and analyze the historical sampleLocal GPU
import io, urllib.request, zipfile, hashlib, json, datetime
from pathlib import Path
import numpy as np
import pandas as pd
from scipy.special import ndtr
from scipy.optimize import brentq

url='https://historicaldata.net/file/options_sample_2022H2.zip'
member='day_by_date/2022-09-15_options.csv'
digest='054acc61106b15a21a2b166e975a506fb0559b9a8d7ec896817ab5e6eb8c208a'
class RemoteZip(io.RawIOBase):
 def __init__(self,url):
  self.url=url;self.pos=0
  with urllib.request.urlopen(urllib.request.Request(url,method='HEAD'),timeout=30) as response:self.size=int(response.headers['Content-Length'])
 def seekable(self):return True
 def readable(self):return True
 def tell(self):return self.pos
 def seek(self,offset,whence=0):
  self.pos=offset if whence==0 else self.pos+offset if whence==1 else self.size+offset
  return self.pos
 def read(self,n=-1):
  if n<0:n=self.size-self.pos
  if n==0:return b''
  end=min(self.size-1,self.pos+n-1)
  request=urllib.request.Request(self.url,headers={'Range':f'bytes={self.pos}-{end}'})
  with urllib.request.urlopen(request,timeout=60) as response:
   if response.status!=206:raise RuntimeError('El servidor no admite rangos')
   data=response.read()
  self.pos+=len(data);return data

with zipfile.ZipFile(RemoteZip(url)) as archive:
 data=archive.read(member)
assert hashlib.sha256(data).hexdigest()==digest
captured=datetime.datetime.now(datetime.timezone.utc).isoformat()
folder=Path('historical_options');folder.mkdir(exist_ok=True)
(folder/'2022-09-15_options.csv').write_bytes(data)
metadata={'source':url,'member':member,'sha256':digest,'captured_utc':captured,'quote_date':'2022-09-15',
          'quote_time':'not supplied in the CSV','scope':'historical sample; not simultaneous quotes'}
(folder/'2022-09-15_metadata.json').write_text(json.dumps(metadata,indent=2),encoding='utf-8')
raw=pd.read_csv(io.BytesIO(data))
d=raw[(raw.underlying=='SPXW')&(raw['style']=='E')&(raw.settlement_time=='PM')&(raw.expiration=='2022-09-30')].copy()
d=d[(d.bid>=0)&(d.ask>=d.bid)&(d.ask>0)&(d.volume>=1)&(d.open_interest>=10)]
assert d.quote_time.notna().sum()==0
assert not d.duplicated(['strike','type']).any()
p=d.pivot(index='strike',columns='type',values=['bid','ask']).dropna()
mid=(p['bid']+p['ask'])/2
ii=(p.index>=3600)&(p.index<=4200)
K=p.index.to_numpy()[ii];y=(mid['call']-mid['put']).to_numpy()[ii]
a,slope=np.linalg.lstsq(np.c_[np.ones(len(K)),K],y,rcond=None)[0]
D=-slope;F=a/D;rmse=np.sqrt(np.mean((y-(a+slope*K))**2))
print('captura UTC',captured,'filas',len(d),'pares',len(K),'hora quote disponible',d.quote_time.notna().sum())
print('forward exploratorio',F,'descuento exploratorio',D,'RMSE',rmse)
T=(pd.Timestamp('2022-09-30')-pd.Timestamp('2022-09-15')).days/365
d['mid']=(d.bid+d.ask)/2
liquid=d[(d.ask-d.bid)/d.mid<=.5].copy()
liquid=liquid[((liquid['type']=='call')&(liquid.strike>=F))|((liquid['type']=='put')&(liquid.strike<F))]
def price(k,sigma,call):
 z=np.log(F/k)/(sigma*np.sqrt(T))+sigma*np.sqrt(T)/2
 return D*((F*ndtr(z)-k*ndtr(z-sigma*np.sqrt(T))) if call else (k*ndtr(-z+sigma*np.sqrt(T))-F*ndtr(-z)))
ivs=[]
for row in liquid.itertuples():
 call=row.type=='call';p=row.mid;k=row.strike
 intrinsic=D*(max(F-k,0) if call else max(k-F,0));upper=D*(F if call else k)
 if intrinsic<p<upper and price(k,.00001,call)<=p<=price(k,8.,call):
  ivs.append(brentq(lambda s:price(k,s,call)-p,.00001,8.))
print('OTM con spread relativo <= 0.5',len(liquid),'IV invertidas',len(ivs),'mediana',float(np.median(ivs)))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofMonotonicity and uniqueness
Prove: Prove uniqueness of a finite implied volatility for a price inside the bounds.
0
F, K, T and D are positive and remain fixed.

Step 1 of 3. What is the sign of Black vega for σ > 0?

NumericForward from parity
A call costs 7, a put 3, both with K = 100 and D = 0.98. What is the implied forward?
QuizSelecting OTM options
Why use out-of-the-money calls and puts when inverting the surface?
CodeVectorized inverter
Implement implied_vol(price,F,K,T,df,is_call), accepting scalars or arrays with broadcasting. Return only volatility: NaN for prices outside bounds or at the upper bound, zero at the lower bound, and the interior root using safeguarded Newton with bisection.
def implied_vol(price,F,K,T,df,is_call):
  raise NotImplementedError()
Shift+Enter to run

Ideas to remember

Save the capture date and each quote date, distinguish observed from synthetic data, and do not confuse missing data with zero liquidity. Parity, OTM, and a safeguarded inverter are the start of a pipeline, not certification that the resulting surface is arbitrage-free.