Data Science in Personal Finance: Stock Returns Tested
Data science in personal finance is mostly about being honest with history. Instead of predicting prices, this article takes 150 years of US stock data and answers four practical questions: how bad can a bad year, decade or lifetime of saving be, does investing in instalments beat investing at once, and what do fees cost over 30 years. Every figure is output from the code shown. This is an educational analysis of past data, not financial advice, and past returns do not guarantee future ones.

The data: monthly US stock prices, dividends and inflation
The file is Robert Shiller’s long-run US stock series (the S&P composite index), published as open data in the datasets/s-and-p-500 repository. It has monthly prices, dividends, earnings and the consumer price index, with inflation-adjusted columns. The inflation-adjusted columns stop in mid-2023 even though prices run to 2026 (they are zero after that), so the analysis uses 1,830 months from January 1871 to June 2023. Total return is built from the real price change plus one twelfth of the real annual dividend each month, with dividends reinvested and no fees or taxes.
import pandas as pd, numpy as np
url = "https://raw.githubusercontent.com/datasets/s-and-p-500/main/data/data.csv"
d = pd.read_csv(url, parse_dates=["Date"])
print(len(d), "rows; zeros mark months with no inflation-adjusted data")
d = d[(d["Real Price"] > 0) & (d["Real Dividend"] > 0) & (d["Consumer Price Index"] > 0)].reset_index(drop=True)
print(len(d), "usable months,", d.Date.min().date(), "to", d.Date.max().date())
# monthly real total return: price change plus one twelfth of the (annual) dividend
p, div = d["Real Price"].to_numpy(), d["Real Dividend"].to_numpy()
r = np.zeros(len(d)); r[1:] = (p[1:] + div[1:] / 12) / p[:-1] - 1
tri = (1 + r).cumprod() # value of 1 invested, in constant dollars
years = (d.Date.iloc[-1] - d.Date.iloc[0]).days / 365.25
print("real annual growth, price only:", round((p[-1] / p[0]) ** (1 / years) - 1, 4),
"| with dividends:", round(tri[-1] ** (1 / years) - 1, 4))
print("cash kept since 1871 keeps", round(100 * d["Consumer Price Index"].iloc[0] / d["Consumer Price Index"].iloc[-1], 1), "% of its purchasing power")
1869 rows; zeros mark months with no inflation-adjusted data
1830 usable months, 1871-01-01 to 2023-06-01
real annual growth, price only: 0.0245 | with dividends: 0.069
cash kept since 1871 keeps 4.1 % of its purchasing powerAfter inflation, the index price alone grew about 2.5% a year over these 152 years, while reinvested dividends lifted the total to about 6.9%. Cash kept under the mattress since 1871 would keep only 4.1% of its purchasing power. Both numbers are long-run averages that hide very uneven stretches, which the next step measures.
How bad can it get? Every holding period since 1871
for n in (1, 5, 10, 20, 30):
m = n * 12
g = pd.Series((tri[m:] / tri[:-m]) ** (1 / n) - 1, index=d.Date[:-m])
print(f"{n:>2}-year windows: {len(g)} | median {g.median():.3f} | worst {g.min():.3f}"
f" (start {g.idxmin():%Y-%m}) | negative {100 * (g < 0).mean():.1f}%")
peak = np.maximum.accumulate(tri); dd = tri / peak - 1
i = dd.argmin(); pk = tri[:i + 1].argmax()
back = np.where((np.arange(len(tri)) > i) & (tri >= tri[pk]))[0][0]
print("worst drawdown", round(dd.min(), 3), "peak", d.Date[pk].date(), "trough", d.Date[i].date(),
"recovered", d.Date[back].date())
1-year windows: 1818 | median 0.087 | worst -0.581 (start 1931-06) | negative 31.0%
5-year windows: 1770 | median 0.072 | worst -0.132 (start 1929-09) | negative 19.0%
10-year windows: 1710 | median 0.069 | worst -0.059 (start 1999-03) | negative 11.3%
20-year windows: 1590 | median 0.067 | worst -0.002 (start 1901-06) | negative 0.1%
30-year windows: 1470 | median 0.067 | worst 0.019 (start 1902-06) | negative 0.0%
worst drawdown -0.768 peak 1929-09-01 trough 1932-06-01 recovered 1936-11-01The median return barely changes with the holding period (8.7% a year for one year, 6.7% for thirty), but the spread shrinks dramatically. Nearly a third of one-year windows lost money after inflation, 11.3% of ten-year windows did, and only 0.1% of twenty-year windows did (a handful of windows, the worst starting in 1901 at about −0.2% a year). The worst thirty-year stretch still grew by 1.9% a year. The deepest fall was 76.8% from September 1929 to June 1932 in inflation-adjusted terms, and it took until November 1936 to get back to the old peak. Overlapping windows are not independent, so these percentages describe history, not probabilities. They also describe the United States, one of the best-performing markets of the period, which is a form of survivorship bias.
Lump sum or monthly instalments?
The next test compares investing 12 units at once with investing one unit a month for 12 months, then measuring the value ten years after the start, for every possible start month.
H = 120; lump_wins = []; adv = []
for s in range(len(tri) - H - 12):
lump = 12 * tri[s + H] / tri[s]
dca = sum(tri[s + H] / tri[s + k] for k in range(12))
lump_wins.append(lump > dca); adv.append(lump / dca - 1)
print("lump sum beat monthly instalments in", round(np.mean(lump_wins), 3),
"of", len(adv), "windows; median advantage", round(np.median(adv), 4))
lump sum beat monthly instalments in 0.656 of 1698 windows; median advantage 0.0352Investing everything at once won in 65.6% of 1,698 windows, with a median advantage of 3.5%. That is what you would expect when markets rise more often than they fall, because instalments keep part of the money out of the market longer. Instalments still have a place: they limit regret and match how most people are paid, and in the other 34.4% of windows they came out ahead.
Saving every month, and what fees do
# saving 500 a month for 30 years, in constant dollars, every possible start month
m = 360
final = pd.Series([sum(500 * tri[s + m] / tri[s + k] for k in range(m)) for s in range(len(tri) - m)],
index=d.Date[:len(tri) - m])
print("paid in 180,000 | median", round(final.median()), "| worst", round(final.min()),
f"(start {final.idxmin():%Y-%m}) | best", round(final.max()))
for fee in (0, 0.005, 0.01, 0.02):
print(f"annual fee {fee:.3f}: 1 grows to {(1 + (tri[-1] ** (1 / years) - 1) - fee) ** 30:.2f} in 30 years")
paid in 180,000 | median 550102 | worst 199897 (start 1890-12) | best 1290698
annual fee 0.000: 1 grows to 7.41 in 30 years
annual fee 0.005: 1 grows to 6.44 in 30 years
annual fee 0.010: 1 grows to 5.59 in 30 years
annual fee 0.020: 1 grows to 4.20 in 30 yearsPaying in 500 a month for 30 years (180,000 in total, in inflation-adjusted dollars) ended with a median of about 550,000, but the spread was wide: the worst start month, December 1890, ended at roughly 200,000, barely above what was paid in, and the best ended near 1.29 million. On fees, the same long-run 6.9% real growth turns 1 into 7.41 over 30 years with no fee, 6.44 at 0.5% a year, 5.59 at 1% and 4.20 at 2%. A 1% fee takes about a quarter of the final value. The fee calculation applies one constant rate, so it shows scale, not a forecast.
What this does not tell you
The data is US-only and ends in 2023 for real returns, the index has changed definition over time, and the code ignores taxes, trading costs and the fact that nobody invests in the index exactly as modelled. A different country or period could look very different. For related work, see our portfolio analysis in data science in finance, the time series analysis guide for why price prediction is hard, and data literacy for reading statistics like these critically. If you do your own version, the NumPy documentation covers the array operations used above.
Frequently asked questions
How is data science used in personal finance?
Common uses are budgeting analysis, spending categorisation, credit scoring, fraud detection and testing strategies against historical data, as in this article. Most of the value comes from checking claims against data rather than from prediction.
Does a longer holding period reduce risk?
In this US dataset the range of outcomes narrowed sharply as the period lengthened, with every thirty-year window positive after inflation. That is a historical pattern in one market, not a guarantee.
Where can I get data to test my own strategy?
The datasets repository used here is free, and Shiller’s series is widely used in textbooks. Check the real-versus-nominal columns carefully before you compute returns.
