Coverage for lab/data_explore.py: 100%

66 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""A first look at a price table (`aq data info`, `aq data explore`): coverage and gaps per ticker, and a one-file HTML page 

2with return distributions, correlations, drawdowns, the gap map and rolling volatility. 

3 

4Input is a dates x tickers close table (a wide CSV: a date column, then one column per ticker), or a long one 

5(date, ticker, close), which is pivoted. 

6""" 

7 

8from __future__ import annotations 

9 

10from pathlib import Path 

11from typing import Any 

12 

13import numpy as np 

14import pandas as pd 

15 

16from lab import report_html as rh 

17 

18 

19def read_closes(path: Path) -> pd.DataFrame: 

20 """A dates x tickers float table from a wide or long CSV (or parquet), indexed by ISO date strings.""" 

21 path = Path(path) 

22 if path.suffix == ".parquet": 

23 frame = pd.read_parquet(path) 

24 if not isinstance(frame.index, pd.RangeIndex): 

25 frame = frame.reset_index() 

26 else: 

27 frame = pd.read_csv(path) 

28 lowered = {column.lower(): column for column in frame.columns} 

29 if {"date", "ticker", "close"} <= set(lowered): 

30 frame = frame.pivot(index=lowered["date"], columns=lowered["ticker"], values=lowered["close"]) 

31 else: 

32 frame = frame.set_index(frame.columns[0]) 

33 frame.index = pd.to_datetime(frame.index).strftime("%Y-%m-%d") 

34 frame.columns = [str(column) for column in frame.columns] 

35 return frame.sort_index().apply(pd.to_numeric, errors="coerce").astype(float) 

36 

37 

38def calendar_kind(index: pd.Index) -> str: 

39 """'7-day' when weekends carry rows (crypto), else 'weekdays'.""" 

40 days = pd.to_datetime(index).day_of_week 

41 return "7-day" if (days >= 5).any() else "weekdays" 

42 

43 

44def longest_gaps(series: pd.Series) -> int: 

45 """The longest run of missing values after the ticker's first value.""" 

46 values = series.loc[series.first_valid_index():] if series.first_valid_index() is not None else series.iloc[0:0] 

47 missing = values.isna().to_numpy() 

48 best = current = 0 

49 for flag in missing: 

50 current = current + 1 if flag else 0 

51 best = max(best, current) 

52 return int(best) 

53 

54 

55def info(closes: pd.DataFrame) -> dict[str, Any]: 

56 """Shape, date range, calendar, and per ticker: first and last date, missing share and longest gap after its start.""" 

57 tickers = {} 

58 for ticker in closes.columns: 

59 series = closes[ticker] 

60 first, last = series.first_valid_index(), series.last_valid_index() 

61 live = series.loc[first:last] if first is not None else series.iloc[0:0] 

62 tickers[ticker] = {"first": first, "last": last, "missing": round(float(live.isna().mean()), 4) if len(live) else 1.0, "longest_gap": longest_gaps(series)} 

63 return {"rows": int(len(closes)), "tickers": int(closes.shape[1]), "start": str(closes.index.min()) if len(closes) else None, 

64 "end": str(closes.index.max()) if len(closes) else None, "calendar": calendar_kind(closes.index) if len(closes) else None, 

65 "gaps_over_3": sorted(ticker for ticker, row in tickers.items() if row["longest_gap"] > 3), "per_ticker": tickers} 

66 

67 

68def render_info(data: dict[str, Any]) -> str: 

69 """`aq data info`'s text: shape, window, calendar, coverage and gaps.""" 

70 lines = [f"{data['rows']} dates x {data['tickers']} tickers, {data['start']} to {data['end']} ({data['calendar']} calendar)"] 

71 for ticker, row in data["per_ticker"].items(): 

72 lines.append(f" {ticker:<10} {row['first']} .. {row['last']} missing {row['missing']:.1%} longest gap {row['longest_gap']}") 

73 if data["gaps_over_3"]: 

74 lines.append(f"gaps over 3 rows: {', '.join(data['gaps_over_3'])}") 

75 return "\n".join(lines) 

76 

77 

78def explore(closes: pd.DataFrame, *, title: str = "Data") -> dict[str, Any]: 

79 """The numbers behind the page: return moments, the correlation matrix, drawdowns, rolling volatility.""" 

80 returns = closes.pct_change(fill_method=None) 

81 periods = 365.0 if calendar_kind(closes.index) == "7-day" else 252.0 

82 moments = {} 

83 for ticker in closes.columns: 

84 values = returns[ticker].dropna() 

85 if len(values) < 3: 

86 continue 

87 moments[ticker] = {"mean_annual": float(values.mean() * periods), "vol_annual": float(values.std() * np.sqrt(periods)), 

88 "skew": float(values.skew()), "kurtosis": float(values.kurt()), "p01": float(values.quantile(0.01)), "p99": float(values.quantile(0.99))} 

89 drawdown = closes / closes.cummax() - 1.0 

90 return {"title": title, "periods": periods, "moments": moments, "correlation": returns.corr(min_periods=20), 

91 "max_drawdown": {ticker: float(drawdown[ticker].min()) for ticker in closes.columns if drawdown[ticker].notna().any()}, 

92 "rolling_vol": returns.rolling(60, min_periods=40).std() * np.sqrt(periods), "returns": returns, "closes": closes} 

93 

94 

95def render_explore_html(data: dict[str, Any]) -> str: 

96 """The exploration report as one self-contained HTML page.""" 

97 moments = [[ticker, row["mean_annual"], row["vol_annual"], row["skew"], row["kurtosis"], row["p01"], row["p99"], data["max_drawdown"].get(ticker)] 

98 for ticker, row in data["moments"].items()] 

99 closes = data["closes"] 

100 normalised = [series / series.dropna().iloc[0] for _, series in closes.items() if series.notna().any()] 

101 vol = data["rolling_vol"] 

102 gaps = {ticker: float(closes[ticker].loc[closes[ticker].first_valid_index():].isna().mean()) for ticker in closes.columns if closes[ticker].notna().any()} 

103 pooled = data["returns"].stack().to_numpy() 

104 sections = [ 

105 ("Growth of 1", rh.svg_lines(normalised, label="Growth of 1") + rh.legend(list(closes.columns))), 

106 ("Returns", rh.table(moments, ["ticker", "mean/yr", "vol/yr", "skew", "kurtosis", "1st pct", "99th pct", "max drawdown"])), 

107 ("Pooled daily returns", rh.svg_histogram(pooled, label="Pooled daily returns")), 

108 ("Correlation of daily returns", rh.svg_heatmap(data["correlation"].fillna(0.0))), 

109 ("Rolling 60-row volatility (annualised)", rh.svg_lines([vol[column] for column in vol.columns], label="Rolling volatility") + rh.legend(list(vol.columns))), 

110 ("Missing share after each ticker's start", rh.svg_bars(gaps, label="Missing share")), 

111 ] 

112 return rh.page(data["title"], sections, subtitle=f"{closes.shape[0]} dates x {closes.shape[1]} tickers, {closes.index.min()} to {closes.index.max()}")