Coverage for data_pipeline/factor_library.py: 100%

47 statements  

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

1"""Published daily factor returns (V6.6.0): Kenneth French's library and AQR's data sets, free, no account. 

2 

3A sleeve can earn more than SPY, AGG and BTC explain and still be a known premium anyone can buy. `evaluation.factor_spanning.factor_alpha` 

4reads these to tell the two apart. Reported beside a result, never blocking. These series lag: one ending before a window is reported as 

5such, never filled. 

6""" 

7 

8from __future__ import annotations 

9 

10import io 

11import zipfile 

12from collections.abc import Callable 

13 

14import numpy as np 

15import pandas as pd 

16 

17FRENCH_URL = "https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/ftp/" 

18FRENCH_FIVE = FRENCH_URL + "F-F_Research_Data_5_Factors_2x3_daily_CSV.zip" 

19FRENCH_MOMENTUM = FRENCH_URL + "F-F_Momentum_Factor_daily_CSV.zip" 

20AQR_URL = "https://www.aqr.com/-/media/AQR/Documents/Insights/Data-Sets/" 

21AQR_QMJ = AQR_URL + "Quality-Minus-Junk-Factors-Daily.xlsx" 

22AQR_BAB = AQR_URL + "Betting-Against-Beta-Equity-Factors-Daily.xlsx" 

23 

24 

25def parse_french_zip(payload: bytes) -> pd.DataFrame: 

26 """Decimal returns by YYYY-MM-DD. The file has prose before its header and after its data; only dated rows are kept. The library 

27 states returns in percent and marks a missing value with -99.99 or -999.""" 

28 with zipfile.ZipFile(io.BytesIO(payload)) as archive: 

29 text = archive.read(archive.namelist()[0]).decode("utf-8", errors="replace") 

30 header = None 

31 rows: dict[str, list[float]] = {} 

32 for line in text.splitlines(): 

33 parts = [part.strip() for part in line.split(",")] 

34 if header is None: 

35 if len(parts) >= 2 and parts[0] == "" and all(name for name in parts[1:]): 

36 header = parts[1:] 

37 continue 

38 if len(parts) == len(header) + 1 and parts[0].isdigit() and len(parts[0]) == 8: 

39 rows[f"{parts[0][:4]}-{parts[0][4:6]}-{parts[0][6:]}"] = [float(value) for value in parts[1:]] 

40 frame = pd.DataFrame.from_dict(rows, orient="index", columns=header, dtype=float).sort_index() 

41 return frame.where(frame > -99.0) / 100.0 

42 

43 

44def parse_aqr_sheet(payload: bytes, *, sheet: str, name: str, column: str = "USA") -> pd.Series: 

45 """One factor's daily return from an AQR workbook, whose table starts below some prose. Dates are MM/DD/YYYY or real dates.""" 

46 raw = pd.read_excel(io.BytesIO(payload), sheet_name=sheet, header=None, engine="openpyxl") 

47 header_row = next(index for index, value in enumerate(raw.iloc[:, 0].astype(str)) if value.strip().upper() == "DATE") 

48 table = raw.iloc[header_row + 1:].copy() 

49 table.columns = [str(value).strip() for value in raw.iloc[header_row]] 

50 dates = pd.to_datetime(table["DATE"], errors="coerce", format="mixed") 

51 values = pd.to_numeric(table[column], errors="coerce").to_numpy(dtype=float) 

52 series = pd.Series(values, index=dates.dt.strftime("%Y-%m-%d"), name=name) 

53 return series[series.index.notna()].dropna().sort_index() 

54 

55 

56def fetch_factors(get_bytes: Callable[[str], bytes]) -> pd.DataFrame: 

57 """Date x factor: Mkt-RF, SMB, HML, RMW, CMA, RF, Mom, and QMJ and BAB when the workbooks read. AQR's are optional: a failure there 

58 must not cost the French factors.""" 

59 five = parse_french_zip(get_bytes(FRENCH_FIVE)) 

60 momentum = parse_french_zip(get_bytes(FRENCH_MOMENTUM)) 

61 momentum.columns = [str(column).strip() for column in momentum.columns] 

62 frame = five.join(momentum.rename(columns={momentum.columns[0]: "Mom"}), how="left") 

63 for url, sheet, name in ((AQR_QMJ, "QMJ Factors", "QMJ"), (AQR_BAB, "BAB Factors", "BAB")): 

64 try: 

65 frame[name] = parse_aqr_sheet(get_bytes(url), sheet=sheet, name=name).reindex(frame.index) 

66 except Exception as error: 

67 print(f"{name} left out: {type(error).__name__}: {error}") 

68 return frame.astype(np.float64)