Coverage for data_pipeline/finra_short_volume.py: 100%

34 statements  

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

1"""FINRA's daily short sale volume files (V6.6.0, free, no account): the consolidated `CNMS` file, Date|Symbol|ShortVolume|... per day. 

2 

3Short volume isn't short interest: market makers' short sales fill much of it, so its level says little. A name's ratio against its 

4own past is what the literature (Boehmer, Jones and Zhang) reads. The files begin in 2018-08; earlier dates return 403. 

5""" 

6 

7from __future__ import annotations 

8 

9import io 

10from collections.abc import Callable, Iterable 

11 

12import numpy as np 

13import pandas as pd 

14 

15FILE_URL = "https://cdn.finra.org/equity/regsho/daily/CNMSshvol{day}.txt" 

16 

17 

18def finra_symbol(ticker: str) -> str: 

19 """BRK.B here is BRK/B there.""" 

20 return str(ticker).replace(".", "/") 

21 

22 

23def parse_day(text: str, wanted: dict[str, str] | None = None) -> dict[str, float]: 

24 """{ticker: short volume / total volume}. A file ends with a record count, and a row with no volume says nothing.""" 

25 frame = pd.read_csv(io.StringIO(text), sep="|", dtype={"Symbol": str}, keep_default_na=False) 

26 if not {"Symbol", "ShortVolume", "TotalVolume"} <= set(frame.columns): 

27 return {} 

28 short = pd.to_numeric(frame["ShortVolume"], errors="coerce") 

29 total = pd.to_numeric(frame["TotalVolume"], errors="coerce") 

30 usable = total.gt(0.0) & short.notna() 

31 out: dict[str, float] = {} 

32 for symbol, ratio in zip(frame.loc[usable, "Symbol"], (short[usable] / total[usable]).to_numpy(), strict=False): 

33 name = wanted.get(symbol) if wanted is not None else symbol 

34 if name is not None: 

35 out[name] = float(ratio) 

36 return out 

37 

38 

39def fetch_ratios(days: Iterable[str], get_text: Callable[[str], str | None], tickers: Iterable[str]) -> pd.DataFrame: 

40 """Day x ticker. A day with no file (a holiday, or before the series began) is simply absent. `days` are YYYY-MM-DD.""" 

41 wanted = {finra_symbol(ticker): ticker for ticker in tickers} 

42 rows: dict[str, dict[str, float]] = {} 

43 for day in days: 

44 text = get_text(FILE_URL.format(day=day.replace("-", ""))) 

45 if text: 

46 values = parse_day(text, wanted) 

47 if values: 

48 rows[day] = values 

49 return pd.DataFrame.from_dict(rows, orient="index").sort_index() 

50 

51 

52def short_ratio_table(ratios: pd.DataFrame, sessions: list[str], columns: list[str], *, window: int = 20, lag_sessions: int = 1) -> pd.DataFrame: 

53 """Session x ticker: the mean daily short ratio over `window` sessions, a session late, since the file posts in the evening. A gap 

54 stays NaN: a file that never arrived isn't a ratio of zero.""" 

55 table = ratios.reindex(index=sessions, columns=columns) 

56 return table.rolling(window, min_periods=max(5, window // 2)).mean().shift(lag_sessions).astype(np.float64)