QuantConnect
Cash Indices
Introduction
The Cash Indices dataset by QuantConnect covers 125 US Indices and 3 International indices. The data starts on various dates from January 1998 and is delivered on any frequency from minute to daily.
For more information about the Cash Indices 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.
Live Data
The Cash Indices dataset does not provide a live data feed. To receive Cash Indices' data in your live algorithm, you must add a brokerage or a third-party data provider (see Cloud Platform > Datasets).
Data Summary
The following table describes the dataset properties:
Property | Value |
---|---|
Start Date | January 1998 |
Coverage | 125 US Indices and 3 International indices (HSI, SX5E and N225) |
Data Density | Dense |
Resolution | Minute, Hour, & Daily |
Timezone | New York for US Indices, refer to Supported Assets below for International indices |
Market Hours | Regular Only |
Requesting Data
To add Cash Indices data to your algorithm, call the AddIndex
add_index
method. Save a reference to the Index Symbol
so you can access the data later in your algorithm.
class CashIndexAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2020, 6, 1) self.set_end_date(2021, 6, 1) self.set_cash(100000) self.vix = self.add_index("VIX").symbol
public class CashIndexAlgorithm : QCAlgorithm { private Symbol _symbol; public override void Initialize() { SetStartDate(2020, 6, 1); SetEndDate(2021, 6, 1); SetCash(100000); _symbol = AddIndex("VIX").Symbol; } }
For more information about creating Index subscriptions, see Requesting Data.
Accessing Data
To get the current Cash Indices data, index the Bars
bars
property of the current Slice
with the Index Symbol
. Slice objects deliver unique events to your algorithm as they happen, but the Slice
may not contain data for your security 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 self.vix in slice.bars: trade_bar = slice.bars[self.vix] self.log(f"{self.vix} close at {slice.time}: {trade_bar.close}")
public override void OnData(Slice slice) { if (slice.Bars.ContainsKey(_symbol)) { var tradeBar = slice.Bars[_symbol]; Log($"{_symbol} price at {slice.Time}: {tradeBar.Close}"); } }
You can also iterate through all of the data objects in the current Slice
.
def on_data(self, slice: Slice) -> None: for symbol, trade_bar in slice.bars.items(): self.log(f"{symbol} close at {slice.time}: {trade_bar.close}")
public override void OnData(Slice slice) { foreach (var kvp in slice.Bars) { var symbol = kvp.Key; var tradeBar = kvp.Value; Log($"{symbol} price at {slice.Time}: {tradeBar.Close}"); } }
For more information about accessing Index data, see Handling Data.
Historical Data
To get historical Cash Indices data, call the History
history
method with the Index Symbol
. If there is no data in the period you request, the history result is empty.
# DataFrame history_df = self.history(self.vix, 100, Resolution.DAILY) # TradeBar objects history_bars = self.history[TradeBar](self.vix, 100, Resolution.DAILY)
// TradeBar objects var historyBars = History(_symbol, 100, Resolution.Daily);
For more information about historical data, see History Requests.
Supported Indices
US Cash Indices
The following table shows the US Cash indices with Index Option support:
Ticker | Index | Expiry | Start Date |
---|---|---|---|
VIX | S&P500 | 30 Days | Jul 2003 |
SPX | S&P500 | - | Jan 1998 |
NDX | NASDAQ-100 | - | Jan 1998 |
RUT | Russell 2000 | - | Jan 2008 |
VIX - CBOE Volatility Index
The Cboe Volatility Index (VIX) is a real-time index that represents the market's expectations for the relative strength of near-term price changes of the S&P 500 Index (SPX). Because it's derived from the prices of SPX index Options with near-term expiration dates, it generates a 30-day forward projection of volatility. Volatility, or how fast prices change, is often seen as a way to gauge market sentiment, and in particular, the degree of fear among market participants.
SPX - S&P 500 Index
The S&P 500 Index, or the Standard & Poor's 500 Index, is a market-capitalization-weighted index of the 500 largest publicly-traded companies in the U.S. It is not an exact list of the top 500 U.S. companies by market capitalization because there are other criteria included in the index. The index is widely regarded as the best gauge of large-cap U.S. Equities.
NDX - Nasdaq 100 Index
The Nasdaq-100 Index is a modified market-capitalization-weighted index composed of securities issued by 100 of the largest non-financial companies listed on the Nasdaq Stock Market (Nasdaq). The index includes companies from various industries except for the financial industry, like commercial and investment banks. These non-financial sectors include retail, biotechnology, industrial, technology, health care, and others.
RUT - Russell 2000 Index
The Russell 2000 Index is a small-cap U.S. stock market index that makes up the smallest 2,000 stocks in the Russell Index. It was started by the Frank Russell Company in 1984. The index is maintained by FTSE Russell, a subsidiary of the London Stock Exchange Group (LSEG).
All US Cash Indices
The following table shows all US Cash indices:International Cash Indices
The following table shows the International Cash indices:
Ticker | Index | Start Date | Time Zone | Currency | HSI | Hang Seng Index | Dec 2006 | Asia/Hong Kong | HKD |
---|---|---|---|---|
SX5E | EUREX EU STOXX | Jul 2003 | Europe/Berlin | EUR |
N225 | Nikkei 225 | Jul 2003 | Asia/Tokyo | JPY |
Example Applications
The Cash Indices enable you to incorporate popular indices into your trading algorithms. Examples include the following use cases:
- Exploring the difference between the Index and the ETF that tracks it
- Using these indices as the underlying asset fo Index Options strategies
- Understanding the stock market's level of expected forward-looking volatility, also known as the "fear index". When the VIX starts moving higher, it tells you that traders are getting nervous. When the VIX starts moving lower, it tells you that traders are gaining confidence.
Classic Algorithm Example
The following example algorithm tracks the 80-day EMA and 200-day EMA of SPX. When the short EMA crosses above the long EMA, the algorithm buys SPY. Otherwise, it holds cash.
from AlgorithmImports import * from QuantConnect.DataSource import * class IndexDataAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2020, 1, 1) self.set_end_date(2021, 7, 8) self.set_cash(100000) # Request SPY data as a trading vehicle for SPX self.spy = self.add_equity("SPY").symbol # Request SPX data for trade signal generation spx = self.add_index("SPX").symbol # Create short and long-term EMA indicators for trend estimation to trade self.ema_fast = self.EMA(spx, 80, Resolution.DAILY) self.ema_slow = self.EMA(spx, 200, Resolution.DAILY) self.set_warm_up(200, Resolution.DAILY) # Historical data history = self.history(spx, 60, Resolution.DAILY) self.debug(f'We got {len(history.index)} items from our history request') def on_data(self, slice: Slice) -> None: # Trade signals required indicators to be ready if self.is_warming_up or not self.ema_slow.is_ready: return # If short-term EMA is above long-term, it indicates an up trend, so we buy SPY if not self.portfolio.invested and self.ema_fast > self.ema_slow: self.set_holdings(self.spy, 1) # If it is the reverse, it indicates a downtrend, and we liquidate any position elif self.ema_fast < self.ema_slow: self.liquidate()
public class IndexDataAlgorithm : QCAlgorithm { private Symbol _spy; private ExponentialMovingAverage _emaSlow; private ExponentialMovingAverage _emaFast; public override void Initialize() { SetStartDate(2020, 1, 1); SetEndDate(2021, 7, 8); SetCash(1000000); // Request SPY data as trading vehicle for SPX _spy = AddEquity("SPY").Symbol; // Request SPX data for trade signal generation var spx = AddIndex("SPX").Symbol; // Create short and long-term EMA indicators for trend estimation to trade _emaFast = EMA(spx, 80, Resolution.Daily); _emaSlow = EMA(spx, 200, Resolution.Daily); SetWarmUp(200, Resolution.Daily); // Historical data var history = History(spx, 60, Resolution.Daily); Debug($"We got {history.Count()} items from our history request"); } public override void OnData(Slice slice) { // Trade signals required indicators to be ready if (IsWarmingUp || !_emaSlow.IsReady) { return; } // If short-term EMA is above long-term, it indicates an up trend, so we buy SPY if (!Portfolio.Invested && _emaFast > _emaSlow) { SetHoldings(_spy, 1); } // If it is the reverse, it indicates a downtrend, and we liquidate any position else if (_emaFast < _emaSlow) { Liquidate(); } } }
Framework Algorithm Example
The following example algorithm tracks the 80-day EMA and 200-day EMA of SPX. When the short EMA crosses above the long EMA, the algorithm buys SPY. Otherwise, it holds cash.
from AlgorithmImports import * from QuantConnect.DataSource import * class IndexDataAlgorithm(QCAlgorithm): def initialize(self) -> None: self.set_start_date(2020, 1, 1) self.set_end_date(2021, 7, 8) self.set_cash(100000) # Universe contains only SPY as a trading vehicle for SPX self.set_universe_selection(ManualUniverseSelectionModel ( Symbol.create("SPY", SecurityType.EQUITY, Market.USA) )) # Custom alpha model that emits insights based on SPX index data self.set_alpha(SpxEmaCrossAlphaModel(self)) # Equally investing can dissipate non-systematic risky event's capital concentration risk evenly self.set_portfolio_construction(EqualWeightingPortfolioConstructionModel(Expiry.END_OF_MONTH)) class SpxEmaCrossAlphaModel(AlphaModel): def __init__(self, algorithm: QCAlgorithm) -> None: # Request SPX data for trade signal generation spx = algorithm.add_index("SPX").symbol # Create short and long-term EMA indicators for trend estimation to trade self.ema_fast = algorithm.EMA(spx, 80, Resolution.DAILY) self.ema_slow = algorithm.EMA(spx, 200, Resolution.DAILY) algorithm.set_warm_up(200, Resolution.DAILY) # Historical data history = algorithm.history(spx, 60, Resolution.DAILY) algorithm.debug(f'We got {len(history.index)} items from our history request') def update(self, algorithm: QCAlgorithm, slice: Slice) -> List[Insight]: # Trade signals required indicators to be ready if algorithm.is_warming_up or not self.ema_slow.is_ready: return [] # If short-term EMA is above long-term, it indicates an up trend, so we buy SPY if not algorithm.portfolio.invested and self.ema_fast > self.ema_slow: return [Insight.price(kvp.key, Expiry.END_OF_MONTH, InsightDirection.UP) for kvp in algorithm.active_securities if kvp.value.is_tradable] # If it is the reverse, it indicates downtrend, and we liquidate any position elif self.ema_fast < self.ema_slow: return [Insight.price(kvp.key, Expiry.END_OF_MONTH, InsightDirection.FLAT) for kvp in algorithm.active_securities if kvp.value.is_tradable] return []
public class IndexDataAlgorithm : QCAlgorithm { public override void Initialize() { SetStartDate(2020, 1, 1); SetEndDate(2021, 7, 8); SetCash(1000000); // Universe contains only SPY as a trading vehicle for SPX SetUniverseSelection(new ManualUniverseSelectionModel ( QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA) )); // Custom alpha model that emits insights based on SPX index data SetAlpha(new SpxEmaCrossAlphaModel(this)); // Equally invests can dissipate non-systematic risky event's capital concentration risk evenly SetPortfolioConstruction(new EqualWeightingPortfolioConstructionModel(Expiry.EndOfMonth)); } } public class SpxEmaCrossAlphaModel : AlphaModel { private ExponentialMovingAverage _emaSlow; private ExponentialMovingAverage _emaFast; public SpxEmaCrossAlphaModel(QCAlgorithm algorithm) { // Request SPX data for trade signal generation var spx = algorithm.AddIndex("SPX").Symbol; // Create short and long-term EMA indicators for trend estimation to trade _emaFast = algorithm.EMA(spx, 80, Resolution.Daily); _emaSlow = algorithm.EMA(spx, 200, Resolution.Daily); algorithm.SetWarmUp(200, Resolution.Daily); // Historical data var history = algorithm.History(spx, 60, Resolution.Daily); algorithm.Debug($"We got {history.Count()} items from our history request"); } public override IEnumerable<Insight> Update(QCAlgorithm algorithm, Slice slice) { // Trade signals required indicators to be ready if (algorithm.IsWarmingUp || !_emaSlow.IsReady) { return Enumerable.Empty<Insight>(); } // If short-term EMA is above long-term, it indicates an up trend, so we buy SPY if (!algorithm.Portfolio.Invested && _emaFast > _emaSlow) { return algorithm.ActiveSecurities .Where(kvp => kvp.Value.IsTradable) .Select(kvp => Insight.Price(kvp.Key, Expiry.EndOfMonth, InsightDirection.Up)); } // If it is the reverse, it indicates downtrend, and we liquidate any position else if (_emaFast < _emaSlow) { return algorithm.ActiveSecurities .Where(kvp => kvp.Value.IsTradable) .Select(kvp => Insight.Price(kvp.Key, Expiry.EndOfMonth, InsightDirection.Flat)); } return Enumerable.Empty<Insight>(); } }