How do I read one section of a Kenneth French file?
Open a Kenneth French ZIP, cut the monthly section out of a CSV that also holds annual returns, recognise the missing codes, and convert the returns from percent to decimals.
After this lesson, you can open a Kenneth French ZIP and produce a table of monthly factor returns for a regression, even when the same CSV also holds annual returns.
Where does the monthly section end?
The monthly table starts at its header line, ,Mkt-RF,SMB,HML,RF, and ends at the first blank line, so takewhile(str.strip, lines[start:]) keeps the lines from the header up to that blank line, here the three months from October to December 2025. The annual table below it has the same header and is left out.
The made-up ZIP has the layout of the French files, a note, the monthly table, and the annual table, with Mkt-RF the market return above the risk-free rate, SMB the size factor, HML the value factor and RF the risk-free rate, all in percent. io.BytesIO(payload) opens the downloaded bytes as a file, .decode("latin-1") turns the CSV bytes into text, because Latin-1 gives every byte a character, and .index(header) finds the header’s line number. The French data guide describes the source.
Code: the made-up ZIP
import iofrom zipfile import ZipFilebuffer= io.BytesIO()with ZipFile(buffer, "w") as archive: archive.writestr("factors.csv", """Factor returns in percent,Mkt-RF,SMB,HML,RF202510,1.25,0.40,0.70,0.25202511,-99.99,0.20,-0.50,0.25202512,-0.50,-999,0.15,0.25Annual Factors: January-December,Mkt-RF,SMB,HML,RF2025,8.10,1.20,2.50,3.00""")payload =buffer.getvalue()
The following box, which does not run on this page, downloads the monthly US three-factor file.
from urllib.request import urlopenwith urlopen("https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/ftp/F-F_Research_Data_Factors_CSV.zip", timeout=30) as response: payload = response.read()
The following box opens the CSV inside the ZIP and cuts out the monthly section.
from itertools import takewhilewith ZipFile(io.BytesIO(payload)) as archive: text = archive.read(archive.namelist()[0]).decode("latin-1")lines = text.splitlines()start = lines.index(",Mkt-RF,SMB,HML,RF")section ="\n".join(takewhile(str.strip, lines[start:]))print(section)
How do I read the months, missing codes and units?
pd.read_csv with na_values=[-99.99, -999] reads the section with both missing codes as NaN, pd.PeriodIndex(..., freq="M") turns 202510 into the month October 2025, and dividing by 100 turns percent into decimals. October’s Mkt-RF of 1.25% becomes 0.0125.
io.StringIO(section) gives pandas the section as a file, and index_col=0 makes the first field the row label. A daily French file needs daily dates instead. The posts on factor regressions and Fama-French factors use the returns in these units.
The following box reads the section and converts it.