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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# compute_volatility_labels.py
|
| 2 |
+
# Computes lagged_vol_30d and fwd_vol_30d for every filing in filings_index.csv
|
| 3 |
+
# where has_pickle=True.
|
| 4 |
+
#
|
| 5 |
+
# Price sources (in priority order):
|
| 6 |
+
# 1. FINSABER all_sp500_prices_2000_2024_delisted_include.csv (2000-2024)
|
| 7 |
+
# 2. WRDS CRSP crsp_2025_daily.csv (2025)
|
| 8 |
+
# 3. yfinance fallback for ETN / PARA (no PERMNO in CCM)
|
| 9 |
+
#
|
| 10 |
+
# Volatility definition:
|
| 11 |
+
# vol = std(log_returns over 30 trading days) * sqrt(252) [annualised]
|
| 12 |
+
# lagged_vol_30d : 30 trading days strictly BEFORE filing_date
|
| 13 |
+
# fwd_vol_30d : 30 trading days strictly AFTER filing_date
|
| 14 |
+
#
|
| 15 |
+
# Output: datasets/volatility_labels.csv
|
| 16 |
+
# Run: python scripts/compute_volatility_labels.py
|
| 17 |
+
|
| 18 |
+
import math
|
| 19 |
+
import numpy as np
|
| 20 |
+
import pandas as pd
|
| 21 |
+
from tqdm import tqdm
|
| 22 |
+
|
| 23 |
+
# ── Paths ──────────────────────────────────────────────────────────────────────
|
| 24 |
+
FILINGS_PATH = r"D:\UoE AI\Dissertation\IPP Draft\datasets\filings_index.csv"
|
| 25 |
+
FINSABER_PATH = r"D:\UoE AI\Dissertation\IPP Draft\datasets\all_sp500_prices_2000_2024_delisted_include.csv"
|
| 26 |
+
CRSP_PATH = r"D:\UoE AI\Dissertation\IPP Draft\datasets\crsp_2025_daily.csv"
|
| 27 |
+
OUT_PATH = r"D:\UoE AI\Dissertation\IPP Draft\datasets\volatility_labels.csv"
|
| 28 |
+
|
| 29 |
+
WINDOW = 30 # trading-day window
|
| 30 |
+
ANNUALIZE = math.sqrt(252) # annualisation factor
|
| 31 |
+
|
| 32 |
+
# Tickers with no PERMNO in CCM that have Item 1A pickles -> yfinance fallback
|
| 33 |
+
YFINANCE_TICKERS = {'ETN', 'PARA'}
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# ── Helper ─────────────────────────────────────────────────────────────────────
|
| 37 |
+
def compute_vol(series: pd.Series, filing_date: pd.Timestamp, window: int = 30):
|
| 38 |
+
"""
|
| 39 |
+
series : pd.Series, DatetimeIndex ascending, values = daily log-returns
|
| 40 |
+
Returns (lagged_vol, fwd_vol) as Python floats; np.nan if < window days.
|
| 41 |
+
"""
|
| 42 |
+
# Ensure 1-D Series (guards against yfinance returning DataFrame column)
|
| 43 |
+
if isinstance(series, pd.DataFrame):
|
| 44 |
+
series = series.iloc[:, 0]
|
| 45 |
+
|
| 46 |
+
dates = series.index
|
| 47 |
+
before = dates[dates < filing_date]
|
| 48 |
+
after = dates[dates > filing_date]
|
| 49 |
+
|
| 50 |
+
lagged_vol = float(series.loc[before[-window:]].std()) * ANNUALIZE \
|
| 51 |
+
if len(before) >= window else np.nan
|
| 52 |
+
fwd_vol = float(series.loc[after[:window]].std()) * ANNUALIZE \
|
| 53 |
+
if len(after) >= window else np.nan
|
| 54 |
+
|
| 55 |
+
return lagged_vol, fwd_vol
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# ── 1. Load filings (pickle only) ─────────────────────────────────────────────
|
| 59 |
+
print("Loading filings index...")
|
| 60 |
+
filings = pd.read_csv(FILINGS_PATH)
|
| 61 |
+
filings = filings[filings['has_pickle'] == True].copy()
|
| 62 |
+
filings['filing_date'] = pd.to_datetime(filings['filing_date'])
|
| 63 |
+
print(f" Filings with pickle : {len(filings):,}")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
# ── 2. Load FINSABER (2000-2024) ──────────────────────────────────────────────
|
| 67 |
+
print("\nLoading FINSABER prices (2000-2024)...")
|
| 68 |
+
fin = pd.read_csv(FINSABER_PATH, usecols=['date', 'adjusted_close', 'symbol'])
|
| 69 |
+
fin['date'] = pd.to_datetime(fin['date'])
|
| 70 |
+
fin['symbol'] = fin['symbol'].str.upper().str.strip()
|
| 71 |
+
fin = fin.sort_values(['symbol', 'date'])
|
| 72 |
+
|
| 73 |
+
# Log-return from adjusted close
|
| 74 |
+
fin['log_ret'] = fin.groupby('symbol')['adjusted_close'].transform(
|
| 75 |
+
lambda x: np.log(x / x.shift(1))
|
| 76 |
+
)
|
| 77 |
+
# Drop NaN and -inf/-inf rows (adjusted_close == 0 produces log(0) = -inf)
|
| 78 |
+
fin = fin[fin['log_ret'].notna() & np.isfinite(fin['log_ret'])][['symbol', 'date', 'log_ret']]
|
| 79 |
+
fin.rename(columns={'symbol': 'ticker'}, inplace=True)
|
| 80 |
+
print(f" Rows after log-ret : {len(fin):,} | Tickers: {fin['ticker'].nunique()}")
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
# ── 3. Load CRSP 2025 ─────────────────────────────────────────────────────────
|
| 84 |
+
print("\nLoading CRSP 2025 daily...")
|
| 85 |
+
crsp = pd.read_csv(CRSP_PATH, usecols=['Ticker', 'DlyCalDt', 'DlyRet'])
|
| 86 |
+
crsp.columns = ['ticker', 'date', 'dlyret']
|
| 87 |
+
crsp['date'] = pd.to_datetime(crsp['date'])
|
| 88 |
+
crsp['ticker'] = crsp['ticker'].str.upper().str.strip()
|
| 89 |
+
crsp = crsp[crsp['dlyret'].notna()].copy()
|
| 90 |
+
crsp['log_ret'] = np.log(1 + crsp['dlyret'])
|
| 91 |
+
crsp = crsp[['ticker', 'date', 'log_ret']]
|
| 92 |
+
print(f" Rows : {len(crsp):,} | Tickers: {crsp['ticker'].nunique()}")
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# ── 4. Combine into a single lookup dict ──────────────────────────────────────
|
| 96 |
+
print("\nMerging price sources...")
|
| 97 |
+
prices = pd.concat([fin, crsp], ignore_index=True)
|
| 98 |
+
prices = (prices
|
| 99 |
+
.sort_values(['ticker', 'date'])
|
| 100 |
+
.drop_duplicates(subset=['ticker', 'date']))
|
| 101 |
+
|
| 102 |
+
# dict: ticker (upper) -> pd.Series(log_ret, index=DatetimeIndex)
|
| 103 |
+
price_dict = {
|
| 104 |
+
tkr: grp.set_index('date')['log_ret']
|
| 105 |
+
for tkr, grp in prices.groupby('ticker')
|
| 106 |
+
}
|
| 107 |
+
print(f" Unique tickers in price dict: {len(price_dict):,}")
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
# ── 5. yfinance fallback for ETN / PARA ───────────────────────────────────────
|
| 111 |
+
yf_needed = YFINANCE_TICKERS & set(filings['ticker'].str.upper())
|
| 112 |
+
if yf_needed:
|
| 113 |
+
import yfinance as yf
|
| 114 |
+
print(f"\nFetching yfinance for: {yf_needed}")
|
| 115 |
+
for tkr in sorted(yf_needed):
|
| 116 |
+
hist = yf.download(tkr, start='2005-01-01', end='2026-06-01',
|
| 117 |
+
auto_adjust=True, progress=False)
|
| 118 |
+
if hist.empty:
|
| 119 |
+
print(f" {tkr}: no data returned")
|
| 120 |
+
continue
|
| 121 |
+
# Newer yfinance returns hist['Close'] as a DataFrame; squeeze to Series
|
| 122 |
+
close = hist['Close']
|
| 123 |
+
if isinstance(close, pd.DataFrame):
|
| 124 |
+
close = close.iloc[:, 0]
|
| 125 |
+
s = np.log(close / close.shift(1)).dropna()
|
| 126 |
+
s = s[np.isfinite(s)] # drop any -inf from zero prices
|
| 127 |
+
s.index = pd.to_datetime(s.index)
|
| 128 |
+
s.index.name = 'date'
|
| 129 |
+
s.name = 'log_ret'
|
| 130 |
+
price_dict[tkr] = s.sort_index()
|
| 131 |
+
print(f" {tkr}: {len(s):,} rows ({s.index[0].date()} -> {s.index[-1].date()})")
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
# ── 6. Compute volatility for every filing ────────────────────────────────────
|
| 135 |
+
print("\nComputing volatility windows...")
|
| 136 |
+
records = []
|
| 137 |
+
|
| 138 |
+
for _, row in tqdm(filings.iterrows(), total=len(filings), desc="Vol"):
|
| 139 |
+
ticker = str(row['ticker']).upper().strip()
|
| 140 |
+
filing_date = row['filing_date']
|
| 141 |
+
|
| 142 |
+
if ticker in price_dict:
|
| 143 |
+
lagged_vol, fwd_vol = compute_vol(price_dict[ticker], filing_date, WINDOW)
|
| 144 |
+
else:
|
| 145 |
+
lagged_vol, fwd_vol = np.nan, np.nan
|
| 146 |
+
|
| 147 |
+
records.append({
|
| 148 |
+
'ticker': row['ticker'],
|
| 149 |
+
'cik': row['cik'],
|
| 150 |
+
'sic': row['sic'],
|
| 151 |
+
'sic_description': row['sic_description'],
|
| 152 |
+
'fiscal_year': row['fiscal_year'],
|
| 153 |
+
'filing_date': row['filing_date'].date(),
|
| 154 |
+
'report_date': row['report_date'],
|
| 155 |
+
'lagged_vol_30d': round(lagged_vol, 6) if pd.notna(lagged_vol) else np.nan,
|
| 156 |
+
'fwd_vol_30d': round(fwd_vol, 6) if pd.notna(fwd_vol) else np.nan,
|
| 157 |
+
})
|
| 158 |
+
|
| 159 |
+
df = pd.DataFrame(records)
|
| 160 |
+
df = df.sort_values(['ticker', 'filing_date']).reset_index(drop=True)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
# ── 7. Summary ────────────────────────────────────────────────────────────────
|
| 164 |
+
total = len(df)
|
| 165 |
+
has_both = (df['lagged_vol_30d'].notna() & df['fwd_vol_30d'].notna()).sum()
|
| 166 |
+
lagged_only = (df['lagged_vol_30d'].notna() & df['fwd_vol_30d'].isna()).sum()
|
| 167 |
+
fwd_only = (df['lagged_vol_30d'].isna() & df['fwd_vol_30d'].notna()).sum()
|
| 168 |
+
neither = (df['lagged_vol_30d'].isna() & df['fwd_vol_30d'].isna()).sum()
|
| 169 |
+
|
| 170 |
+
print(f"\nTotal filings processed : {total:,}")
|
| 171 |
+
print(f" Both vol computed : {has_both:,}")
|
| 172 |
+
print(f" Lagged only : {lagged_only:,} (fwd window crosses data gap)")
|
| 173 |
+
print(f" Forward only : {fwd_only:,}")
|
| 174 |
+
print(f" Neither (no prices) : {neither:,}")
|
| 175 |
+
|
| 176 |
+
df.to_csv(OUT_PATH, index=False)
|
| 177 |
+
print(f"\nSaved -> {OUT_PATH}")
|
| 178 |
+
print(df.head(10).to_string(index=False))
|