QuantConnect
Fear and Greed
Introduction
The Fear and Greed dataset by QuantConnect provides data points to quantify the degree of fear and greed in the US Equity market. The data starts in 2014 and is delivered on a daily frequency. This dataset is created by aggregating seven indicators, including market volatility, stock market breadth, and put-call ratios.
For more information about the Fear and Greed dataset, including CLI commands and pricing, see the dataset listing.
About the Provider
QuantConnect was founded in 2012 to serve quants everywhere with the best possible algorithmic trading technology. Seeking to disrupt a notoriously closed-source industry, QuantConnect takes a radically open-source approach to algorithmic trading. Through the QuantConnect web platform, more than 50,000 quants are served every month.
Data Summary
The following table describes the dataset properties:
Property | Value |
---|---|
Start Date | July 2014 |
Data Density | Dense |
Resolution | Daily |
Timezone | New York |
The latest daily data points are about two days since the VIX and SPX prices are inputs into the index and their latest daily prices are also two days old.
Requesting Data
To add Fear and Greed data to your algorithm, call the AddData<FearGreedIndex>
add_data
method. Save a reference to the dataset Symbol
so you can access the data later in your algorithm.
class FearAndGreedDataAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2019, 1, 1) self.set_end_date(2020, 6, 1) self.set_cash(100000) self._symbol = self.add_equity("SPY", Resolution.DAILY).symbol self._dataset_symbol = self.add_data(FearGreedIndex, "FG").symbol
public class FearAndGreedDataAlgorithm : QCAlgorithm { private Symbol _symbol, _datasetSymbol; public override void Initialize() { SetStartDate(2019, 1, 1); SetEndDate(2020, 6, 1); SetCash(100000); _symbol = AddEquity("SPY", Resolution.Daily).Symbol; _datasetSymbol = AddData<FearGreedIndex>("FG").Symbol; } }
Accessing Data
To get the current Fear and Greed data, index the current Slice
with the dataset Symbol
. Slice
objects deliver unique events to your algorithm as they happen, but the Slice
may not contain data for your dataset at every time step. To avoid issues, check if the Slice
contains the data you want before you index it.
def on_data(self, slice: Slice) -> None: if slice.contains_key(self._dataset_symbol): data_point = slice[self._dataset_symbol] self.log(f"{self._dataset_symbol} value at {slice.time}: {data_point.value}")
public override void OnData(Slice slice) { if (slice.ContainsKey(_datasetSymbol)) { var dataPoint = slice[_datasetSymbol]; Log($"{_datasetSymbol} value at {slice.Time}: {dataPoint.Value}"); } }
Historical Data
To get historical Fear and Greed data, call the History
history
method with the dataset Symbol
. If there is no data in the period you request, the history result is empty.
# DataFrame history_df = self.history(self._dataset_symbol, 100, Resolution.DAILY) # Dataset objects history = self.history[FearGreedIndex](self._dataset_symbol, 100, Resolution.DAILY)
var history = History<FearGreedIndex>(_datasetSymbol, 100, Resolution.Daily);
For more information about historical data, see History Requests.
Example Applications
The Fear and Greed dataset quantifies the degree of fear and greed in the US Equity market. Example use cases include the following strategies:
- Accumulate long-term positions when the market is fearful (the index is low).
- Short risky assets when the market is greedy.
- Trade butterfly Option strategies based on the market volatility indicator.
Classic Algorithm Example
The following example algorithm buys SPY when the Fear and Greed index is less than 25 (extreme fear) and sells when it's above 75 (extreme greed).
class FearAndGreedExampleAlgorithm(QCAlgorithm):
def initialize(self) -> None:
self.set_start_date(2020, 1, 1)
self.set_end_date(2024, 10, 1)
self.set_cash(100000)
# Add the market index to trade.
self._equity = self.add_equity('SPY', Resolution.DAILY)
# Add the Fear and Greed dataset.
self._dataset_symbol = self.add_data(FearGreedIndex, 'FG').symbol
def on_data(self, data: Slice) -> None:
# Wait until the Fear and Greed dataset has new data.
if self._dataset_symbol not in data:
return
value = data[self._dataset_symbol].value
# Buy when the market is fearful.
if not self._equity.invested and value < 25:
self.set_holdings(self._equity.symbol, 1)
# Sell when the market is greedy.
elif self._equity.invested and value > 75:
self.liquidate()
public class FearAndGreedExampleAlgorithm : QCAlgorithm
{
private Equity _equity;
private Symbol _datasetSymbol;
public override void Initialize()
{
SetStartDate(2020, 1, 1);
SetEndDate(2024, 10, 1);
SetCash(100000);
// Add the market index to trade.
_equity = AddEquity("SPY", Resolution.Daily);
// Add the Fear and Greed dataset.
_datasetSymbol = AddData<FearGreedIndex>("FG").Symbol;
}
public override void OnData(Slice data)
{
// Wait until the Fear and Greed dataset has new data
if (!data.ContainsKey(_datasetSymbol))
{
return;
}
var value = data[_datasetSymbol].Value;
// Buy when the market is fearful.
if (!_equity.Invested && value < 25)
{
SetHoldings(_equity.Symbol, 1);
}
// Sell when the market is greedy.
else if (_equity.Invested && value > 75)
{
Liquidate();
}
}
}
Framework Example
The following example algorithm buys SPY when the Fear and Greed index is less than 25 (extreme fear) and sells when it's above 75 (extreme greed).
class FearAndGreedExampleAlgorithm(QCAlgorithm):
def initialize(self) -> None:
self.set_start_date(2020, 1, 1)
self.set_end_date(2024, 10, 1)
self.set_cash(100000)
# Trade SPY on a daily basis.
self.universe_settings.resolution = Resolution.DAILY
symbols = [Symbol.create('SPY', SecurityType.EQUITY, Market.USA)]
self.add_universe_selection(ManualUniverseSelectionModel(symbols))
# Add a custom Alpha model that emits insights based on the Fear and Greed dataset.
self.add_alpha(FearAndGreedAlphaModel(self))
# Set the equal weighted PCM so the algorithm places trades.
self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel())
# Define the custom alpha model.
class FearAndGreedAlphaModel(AlphaModel):
def __init__(self, algorithm):
# Create a list to track the current universe.
self._securities = []
# Add the Fear and Greed dataset.
self._dataset_symbol = algorithm.add_data(FearGreedIndex, 'FG').symbol
def update(self, algorithm: QCAlgorithm, data: Slice) -> list[Insight]:
# Wait until the Fear and Greed dataset has new data.
if self._dataset_symbol not in data:
return []
# Wait until the Fear and Greed index is extreme.
value = data[self._dataset_symbol].value
if 25 <= value <= 75:
return []
insights = []
for security in self._securities:
# Buy when the market is fearful.
if not security.invested and value < 25:
direction = InsightDirection.UP
# Sell when the market is greedy.
elif security.invested and value > 75:
direction = InsightDirection.FLAT
else:
continue
insights.append(Insight.price(security.symbol, timedelta(2*365), direction))
return insights
def on_securities_changed(self, algorithm: QCAlgorithm, changes: SecurityChanges) -> None:
# When assets enter the universe, save them.
for security in changes.added_securities:
self._securities.append(security)
# When assets leave the universe, remove them.
for security in changes.removed_securities:
if security in self._securities:
self._securities.remove(security)
public class FearAndGreedExampleAlgorithm : QCAlgorithm
{
public override void Initialize()
{
SetStartDate(2020, 1, 1);
SetEndDate(2024, 10, 1);
SetCash(100000);
// Trade SPY on a daily basis.
UniverseSettings.Resolution = Resolution.Daily;
var symbols = new[] { QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA) };
AddUniverseSelection(new ManualUniverseSelectionModel(symbols));
// Add a custom Alpha model that emits insights based on the Fear and Greed dataset.
AddAlpha(new FearAndGreedAlphaModel(this));
// Set the equal weighted PCM so the algorithm places trades.
SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel());
}
}
// Define the custom Alpha model.
public class FearAndGreedAlphaModel : AlphaModel
{
// Create a list to track the current universe.
private List<Security> _securities = new List<Security>();
private Symbol _datasetSymbol;
public FearAndGreedAlphaModel(QCAlgorithm algorithm)
{
// Add the Fear and Greed dataset.
_datasetSymbol = algorithm.AddData<FearGreedIndex>("FG").Symbol;
}
public override IEnumerable<Insight> Update(QCAlgorithm algorithm, Slice data)
{
// Wait until the Fear and Greed dataset has new data.
if (!data.ContainsKey(_datasetSymbol))
{
return Enumerable.Empty<Insight>();
}
// Wait until the Fear and Greed index is extreme.
var value = data[_datasetSymbol].Value;
if (value >= 25 && value <= 75)
{
return Enumerable.Empty<Insight>();
}
var insights = new List<Insight>();
foreach (var security in _securities)
{
InsightDirection direction;
// Buy when the market is fearful.
if (!security.Invested && value < 25)
{
direction = InsightDirection.Up;
}
// Sell when the market is greedy.
else if (security.Invested && value > 75)
{
direction = InsightDirection.Flat;
}
else
{
continue;
}
insights.Add(Insight.Price(security.Symbol, TimeSpan.FromDays(2 * 365), direction));
}
return insights;
}
public override void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes)
{
// When assets enter the universe, save them.
foreach (var security in changes.AddedSecurities)
{
_securities.Add(security);
}
// When assets leave the universe, remove them.
foreach (var security in changes.RemovedSecurities)
{
_securities.Remove(security);
}
}
}