How do I read Shiller’s Excel workbook without losing October?
Read the monthly rows of a Shiller-style workbook, turn decimal dates such as 1871.1 into the right month, and check one CAPE against ten years of real earnings.
After this lesson, you can read a Shiller-style workbook, keep January and October as separate months, and check one cyclically adjusted price-to-earnings ratio, CAPE, against the earnings behind it.
How do I read the monthly rows?
pd.read_excel(workbook, sheet_name="Data", skiprows=7, usecols="A,H,K,M") skips the seven rows above the header and reads the date, real price, real earnings and CAPE columns, and pd.to_numeric(..., errors="coerce") turns the note below the data into a missing date, so the 122 rows read become 121 months. October 1871 arrives as the number 1871.1.
Robert Shiller’s workbook labels each month as year.month and gives the price and earnings of the S&P index in constant dollars. The made-up workbook has the same layout from January 1871, with a real price of 100, real earnings of 4 for five years, 6 for the next five and 12 in January 1881, and a CAPE of 20 in that month. usecols takes Excel’s column letters. pandas reads .xlsx files with openpyxl and Shiller’s .xls file with xlrd.
Multiplying the date by 100 and rounding gives a whole number, 187110 for October 1871, and divmod(187110, 100) splits it into the year 1871 and the month 10. Splitting the text of the number at the dot reads "1871.1" as January, so January and October would become the same month.
round turns the product into the whole number that divmod needs. pd.Period(year=..., month=..., freq="M") builds the month.
The following box converts the January and October dates both ways.
def year_month_to_period(value): year, month =divmod(round(value *100), 100)return pd.Period(year=year, month=month, freq="M")first_months = monthly["Date"].iloc[[0, 9]]print(pd.DataFrame({"number": first_months,"text": first_months.astype(str),"from_text": [pd.Period(text.replace(".", "-"), freq="M") for text in first_months.astype(str)],"from_number": first_months.map(year_month_to_period),}))
number text from_text from_number
0 1871.01 1871.01 1871-01 1871-01
9 1871.10 1871.1 1871-01 1871-10
How do I check one CAPE value?
CAPE divides the month’s real price by the mean of the real earnings of the 120 months before it, so the CAPE of January 1881 is 100 / ((60 × 4 + 60 × 6) / 120) = 100 / 5 = 20, the same as the workbook’s value.
Here \(P_t\) is the real price in month \(t\) and \(E_s\) the real annual earnings reported in month \(s\). .reindex() takes the 120 months in calendar order and leaves an absent month missing, and .mean(skipna=False) then gives a missing mean. verify_integrity=True checks that each month appears once. A trading signal also needs the date each figure became known, as in the CAPE backtest.
The following box labels the rows by month and computes the CAPE of January 1881.