Fear and greed index backtest since 1927: buying in fear trailed staying invested
In 2008, Warren Buffett wrote: “Be fearful when others are greedy, and be greedy when others are fearful.” On 20 November 2026, CNN’s Fear & Greed Index showed extreme fear, so I turned his advice into a rule and tested it in Python on my own fear and greed index, back to 1927.
Daily US stock returns go back to 1926
I use two daily files from Kenneth French’s data library, both with dividends included. One gives the US stock market return above T-bills and the T-bill return, and the other gives the returns of 12 value-weighted industry portfolios. I add the T-bill return to get the market return:
\[\text{market return} = \text{market return above T-bills} + \text{T-bill return}. \tag{1}\]
import hashlib
import io
import urllib.request
import zipfile
from itertools import takewhile
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.ticker import FuncFormatter
LIBRARY = "https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/ftp/"
def download(name):
with urllib.request.urlopen(LIBRARY + name) as response:
content = response.read()
archive = zipfile.ZipFile(io.BytesIO(content))
print(name, "| sha256", hashlib.sha256(content).hexdigest())
member = next(file for file in archive.namelist() if file.lower().endswith(".csv"))
return archive.read(member).decode("latin-1")
def daily_table(text, title=""):
lines = text.splitlines()
first = next(number for number, line in enumerate(lines) if title in line)
start = next(number for number in range(first, len(lines)) if lines[number].startswith(","))
rows = list(takewhile(str.strip, lines[start:]))
table = pd.read_csv(io.StringIO("\n".join(rows)), index_col=0)
table.index = pd.to_datetime(table.index.astype(str).str.strip(), format="%Y%m%d")
table.columns = table.columns.str.strip()
return table.replace([-99.99, -999], float("nan")) / 100
factors = daily_table(download("F-F_Research_Data_Factors_daily_CSV.zip"))
industries = daily_table(download("12_Industry_Portfolios_Daily_CSV.zip"),
"Average Value Weighted Returns -- Daily")
market = factors["Mkt-RF"] + factors["RF"]
bills = factors["RF"]
dates = market.index
if not (dates.is_unique and dates.is_monotonic_increasing and industries.index.equals(dates)
and industries.shape[1] == 12):
raise ValueError("the two files do not match: other dates or not 12 industries")
if market.isna().any() or industries.isna().any().any():
raise ValueError("a return is missing")
print("downloaded", pd.Timestamp.today().date(), "|", market.index[0].date(), "to",
market.index[-1].date(), "|", len(market), "trading days")F-F_Research_Data_Factors_daily_CSV.zip | sha256 96c23b88e651cbfff3740a53f8225e59ee39893371e96385a1d8125ec2cd9c89
12_Industry_Portfolios_Daily_CSV.zip | sha256 d11f87b42f301ea931d1ddc823d3e2125aba4c8310eeeec43f96554e98b1ebb4
downloaded 2026-11-23 | 1926-07-01 to 2026-09-30 | 26338 trading days
The two files cover the same 26,338 trading days, from 1 July 1926 to 30 September 2026.
My fear and greed index was 2.6 on 10 October 2008
CNN combines seven measures. To reach 1927, I built my own fear and greed index from three measures of US stock returns. Momentum measures how far the value of $1 in the market is above or below its 125-day average:
\[\text{momentum} = \frac{\text{value of \$1 in the market}}{\text{its average over the last 125 trading days}} - 1, \tag{2}\]
where the value of $1 grows with the daily market returns from 1 July 1926. Participation is the share of the 12 industries whose value of $1 is above its own 125-day average:
\[\text{participation} = \frac{\text{number of industries above their 125-day average}}{12}. \tag{3}\]
Calm is higher when daily market returns vary less, so I use minus their sample standard deviation over 20 trading days:
\[\text{calm} = -\,\text{sample standard deviation of the last 20 daily market returns}. \tag{4}\]
The three measures have different scales, so I score each measure against its own previous 252 trading days and average the three scores:
\[\begin{aligned}\text{score} &= 100 \times \frac{\text{days below today} + \tfrac{1}{2} \times \text{days equal to today}}{252}, \\[4pt] \text{index} &= \frac{\text{score of momentum} + \text{score of participation} + \text{score of calm}}{3}, \end{aligned} \tag{5}\]
where “below” and “equal” compare the measure on each of the previous 252 trading days with its value today, and a tie counts half. The first 125-day average needs another 252 trading days before it can be scored, so the first index value is on 1 October 1927. The animation works out the index for 10 October 2008.
wealth = (1 + market).cumprod()
industry_wealth = (1 + industries).cumprod()
industry_average = industry_wealth.rolling(125).mean()
above = (industry_wealth > industry_average).astype(float).where(industry_average.notna())
inputs = pd.DataFrame({"momentum": wealth / wealth.rolling(125).mean() - 1,
"participation": above.mean(axis=1, skipna=False),
"calm": -market.rolling(20).std()})
ranks = inputs.rolling(253, min_periods=253).rank(method="average")
fear_greed = (100 * (ranks - 1).sum(axis=1, min_count=3) / (252 * 3)).dropna()
if not fear_greed.index.equals(dates[dates >= fear_greed.index[0]]):
raise ValueError("a score is missing after the first score")
print("first score", fear_greed.index[0].date(), "| last score", fear_greed.index[-1].date(),
round(fear_greed.iloc[-1], 1))
print(fear_greed.reindex(pd.to_datetime(["1987-10-19", "2008-10-10", "2020-03-23"])).round(1))
day = pd.Timestamp("2008-10-10")
earlier = inputs["participation"].loc[:day].iloc[-253:-1]
today = inputs["participation"][day]
print(day.date(), "| industries above their 125-day average:", int(above.loc[day].sum()), "of 12")
print("participation lower on", int((earlier < today).sum()), "and equal on",
int((earlier == today).sum()), "of the previous 252 days")
print("scores:", (100 * (ranks.loc[day] - 1) / 252).round(1).to_dict(), "| index",
round(fear_greed[day], 1))first score 1927-10-01 | last score 2026-09-30 29.6
1987-10-19 0.0
2008-10-10 2.6
2020-03-23 0.8
dtype: float64
2008-10-10 | industries above their 125-day average: 0 of 12
participation lower on 0 and equal on 38 of the previous 252 days
scores: {'momentum': 0.0, 'participation': 7.5, 'calm': 0.4} | index 2.6
The index was below 25 on each of the three crash days in the output: 0.0 on 19 October 1987, 2.6 on 10 October 2008 and 0.8 on 23 March 2020.
The rule held stocks on 49.0% of trading days
The rule starts in T-bills. If the index is below 25, I view the market as fearful and invest the money in the market. If it is above 75, I consider the market greedy, sell, and put the money in T-bills. Between 25 and 75, the rule keeps its holding:
\[\text{holding for the next day} = \begin{cases}\text{stocks} & \text{if the index closes below 25} \\ \text{T-bills} & \text{if the index closes above 75} \\ \text{the current holding} & \text{otherwise}\end{cases} \tag{6}\]
I create the signal using the previous day’s close, so the new holding earns the next trading day’s return:
\[\text{rule return over the next trading day} = \begin{cases}\text{next market return} & \text{in stocks} \\ \text{next T-bill return} & \text{in T-bills}\end{cases} \tag{7}\]
The other strategy, staying invested, is to stay invested in the market all the time, regardless of what the index shows. I invest only $1 at the start for both methods, at the close of 1 October 1927.
days = fear_greed.index
decision = pd.Series(float("nan"), index=days)
decision[fear_greed < 25] = 1
decision[fear_greed > 75] = 0
target = decision.ffill().fillna(0)
in_stocks = target.shift(1, fill_value=0)
timing = market[days].where(in_stocks == 1, bills[days])
returns = pd.DataFrame({"Staying invested": market[days], "Buy in fear, sell in greed": timing})
returns.iloc[0] = 0.0
growth = (1 + returns).cumprod()
switches = int(in_stocks.diff().abs().sum())
print("$1 invested at the close of", days[0].date(), "| last close", days[-1].date())
print("days in stocks:", f"{in_stocks.iloc[1:].mean():.1%}", "| switches:", switches)$1 invested at the close of 1927-10-01 | last close 2026-09-30
days in stocks: 49.0% | switches: 220
The rule held stocks on 49.0% of trading days and switched 220 times.
Staying invested turned $1 into $12,919
For this backtest, you earn more by staying in the market than by timing it. Staying invested earned 10.0% a year, and $1 grew to $12,919, but your worst drawdown was −84.1%. Buying in fear and selling in greed earned 6.5% a year, $1 grew to $512, and its worst drawdown was −64.5%. The Sharpe ratio was 0.45 for staying invested and 0.30 for the rule. I also compare the daily log return of stocks with that of T-bills, which shows on which days the gap arose:
\[\text{stock advantage in basis points} = 10{,}000 \times \left[\ln(1 + \text{market return}) - \ln(1 + \text{T-bill return})\right], \tag{8}\]
and average the stock advantage over the days the rule held stocks and over the days it held T-bills.
years = (days[-1] - days[0]).days / 365.25
per_year = (len(days) - 1) / years
drawdown = growth / growth.cummax() - 1
excess = returns.iloc[1:].sub(bills[days].iloc[1:], axis=0)
summary = pd.DataFrame({"return a year": growth.iloc[-1] ** (1 / years) - 1,
"volatility a year": returns.iloc[1:].std() * per_year ** 0.5,
"Sharpe ratio": excess.mean() / excess.std() * per_year ** 0.5,
"worst drawdown": drawdown.min(),
"$1 grew to": growth.iloc[-1]})
formats = {"return a year": "{:.1%}".format, "volatility a year": "{:.1%}".format,
"Sharpe ratio": "{:.2f}".format, "worst drawdown": "{:.1%}".format,
"$1 grew to": "${:,.2f}".format}
print(summary.to_string(formatters=formats))
after_costs = growth["Buy in fear, sell in greed"].iloc[-1] * (1 - 0.001) ** switches
one_day_later = market[days].where(target.shift(2, fill_value=0) == 1, bills[days])
one_day_later.iloc[0] = 0.0
print("buy in fear, sell in greed: $1 grew to", f"${after_costs:,.2f}", "after 0.1% per switch,",
"and to", f"${(1 + one_day_later).prod():,.2f}", "when every trade waits one more day")
held = in_stocks.iloc[1:] == 1
edge = np.log1p(market[days].iloc[1:]) - np.log1p(bills[days].iloc[1:])
in_stocks_edge, in_bills_edge = 10_000 * edge[held].mean(), 10_000 * edge[~held].mean()
print("log stock return minus log bill return, basis points a trading day: on days in stocks",
round(in_stocks_edge, 2), "| on days in bills", round(in_bills_edge, 2))
print("the last close says:", "stocks" if target.iloc[-1] == 1 else "Treasury bills") return a year volatility a year Sharpe ratio worst drawdown $1 grew to
Staying invested 10.0% 17.5% 0.45 -84.1% $12,919.48
Buy in fear, sell in greed 6.5% 14.0% 0.30 -64.5% $512.29
buy in fear, sell in greed: $1 grew to $411.08 after 0.1% per switch, and to $553.83 when every trade waits one more day
log stock return minus log bill return, basis points a trading day: on days in stocks 2.46 | on days in bills 2.44
the last close says: Treasury bills
This chart shows how $1 grew in each strategy, on a log scale, and how much each strategy lost in value compared with a prior high.
BACKGROUND, INK, GRID, FRAME, LABEL = "#FCEFE3", "#1F1F1F", "#EADCCC", "#D5C6B4", "#4a4a4a"
TEAL, ORANGE, GREY = "#17868A", "#D2822B", "#7a7168"
def site_style(figure, axes):
figure.patch.set_facecolor(BACKGROUND)
for axis in axes:
axis.set_facecolor(BACKGROUND)
axis.grid(True, axis="y", color=GRID, lw=1.0)
axis.set_axisbelow(True)
axis.spines[["top", "right"]].set_visible(False)
axis.spines[["left", "bottom"]].set_color(FRAME)
axis.tick_params(length=0, colors=GREY, labelsize=12.5, pad=6)
axis.xaxis.label.set(color=LABEL, fontsize=14)
axis.yaxis.label.set(color=LABEL, fontsize=14)
colors = {"Buy in fear, sell in greed": TEAL, "Staying invested": ORANGE}
figure, (top, bottom) = plt.subplots(2, 1, figsize=(12, 8), sharex=True, height_ratios=[2, 1])
for name, color in colors.items():
top.plot(growth.index, growth[name], color=color, lw=2.2, label=name)
top.text(growth.index[-1], growth[name].iloc[-1], f" ${growth[name].iloc[-1]:,.0f}",
va="center", ha="left", fontsize=13, fontweight="bold", color=color)
bottom.plot(drawdown.index, 100 * drawdown[name], color=color, lw=1.4)
top.set_yscale("log")
top.yaxis.set_major_formatter(FuncFormatter(lambda value, _: f"${value:,.0f}" if value >= 1
else f"${value:.1f}"))
top.tick_params(axis="y", which="minor", left=False)
top.set_ylabel("Value of $1 in nominal dollars (log scale)")
top.legend(loc="upper left", frameon=False, labelcolor="linecolor", fontsize=13)
lines = [f"{'':27}{'Return a year':>14}{'Volatility':>12}{'Sharpe ratio':>14}"]
for name, row in summary.loc[list(colors)].iterrows():
lines.append(f"{name:27}{row['return a year']:>14.1%}{row['volatility a year']:>12.1%}"
f"{row['Sharpe ratio']:>14.2f}")
top.text(0.98, 0.04, "\n".join(lines), transform=top.transAxes, ha="right", va="bottom",
family="monospace", fontsize=11, color=INK,
bbox=dict(boxstyle="round", facecolor="#FFFDF9", edgecolor=FRAME))
top.set_xlim(right=growth.index[-1] + pd.DateOffset(years=10))
bottom.set_ylabel("Drawdown (%)")
site_style(figure, [top, bottom])
figure.tight_layout()
figure.savefig("fear_greed_timing.png", dpi=200, facecolor=BACKGROUND)
plt.show()| Value of $1 | Below its high |
|---|
On average, the stock advantage was 2.46 basis points a day when the rule held stocks and 2.44 basis points when it held T-bills, suggesting that the rule did not hold stocks on better days. Both strategies earned the same return on the days in stocks, so the ratio of their values changed only on the days the rule held T-bills.
Limitations
My index uses only three measures, while CNN uses seven. The three measures I use focus solely on US stocks and exclude movements from options and bonds, which CNN includes.
The returns. All returns are before trading costs and taxes, which affect the returns, especially when the rule switches between T-bills and stocks.
Conclusion
So, staying invested earned a higher return than switching based on my fear-and-greed index, which goes back to the old saying that time in the market beats timing the market.
But this does not necessarily contradict what Buffett once said, because he also wrote in his 1986 Berkshire letter that they never tried to predict the timing of fear or greed.
References
Adinolfi, J. (2026, November 20). CNN’s “fear and greed” index flashes “extreme fear”. MarketWatch. https://www.marketwatch.com/livecoverage/stock-market-today-dow-s-p-500-nasdaq-anthropic-ipo-second-day-trading/card/cnn-s-fear-and-greed-index-flashes-extreme-fear--tsK0QImWOcCZe1Sz6KDx
Buffett, W. E. (1987). Chairman’s letter, 1986. Berkshire Hathaway. https://www.berkshirehathaway.com/letters/1986.html
Buffett, W. E. (2008, October 16). Buy American. I am. The New York Times. https://www.nytimes.com/2008/10/17/opinion/17buffett.html
French, K. R. (2026a). Fama/French 3 factors [Daily data set, September 2026 release]. Kenneth R. French Data Library. https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/Data_Library/f-f_factors.html
French, K. R. (2026b). 12 industry portfolios [Daily data set, September 2026 release]. Kenneth R. French Data Library. https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/Data_Library/det_12_ind_port.html
Morrow, A. (2025, April 7). A brief history of CNN’s Fear and Greed Index. CNN. https://www.cnn.com/2025/04/07/business/what-is-cnn-fear-and-greed-index
Read next
- Fear and greed, part 2: does smoothing the index help? Smoothing my fear and greed index reduces switching in a buy-in-fear, sell-in-greed rule. Only one version beat staying invested after a single switch in 1937.
- Kenneth French data in Python Monthly and daily returns of the Fama-French factors and of portfolios sorted on size, value, industry and other variables, for the US and other regions.
- CAPE ratio backtest: time in the market vs timing the market since 1891 From 1891 to 2026, time in the market turned $1 into $8,587 after inflation, against $350 for timing the market with CAPE.
- How to use Kenneth French’s data library
Disclaimer: simplified, hypothetical backtest without trading costs or taxes, for discussion purposes only. Not investment advice. Past performance does not guarantee future returns.
Data: Kenneth R. French, Data Library, daily Fama/French factors and 12 industry portfolios (value-weighted), September 2026 release, July 1926 to September 2026, downloaded on 23 November 2026. The printed output gives the files’ SHA-256 hashes. I publish only results computed from the data.