QuantConnect

Factors

Introduction

Factors by QuantConnect provides precomputed factors for individual US Equities plus unlinked factors that aren't tied to a tradable security, such as US Treasury yield curve rates. The data starts in 1998, covers hundreds of US Equities, and is delivered on a daily frequency. This dataset is created by computing each factor from our own datasets with the same LEAN tooling an algorithm would use, so backtest and precomputed values match exactly.

For more information about the Factors 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.

Getting Started

The following snippet demonstrates how to request data from the Factors dataset:

# Factors linked to a specific stock:
self._equity = self.add_equity("AAPL", Resolution.DAILY)
self._equity.factors = self.add_data(Factors, self._equity.symbol).symbol
# Unlinked factors:
self._unlinked_factors = self.add_data(Factors, Factors.UNLINKED).symbol
# All factors:
self._universe = self.add_universe(FactorsUniverse, self._select_assets)
// Factors linked to a specific stock:
_equity = AddEquity("SPY", Resolution.Daily);
_equityFactors = AddData<Factors>(_equity.Symbol).Symbol;
// Unlinked factors:
_unlinkedFactors = AddData<Factors>(Factors.Unlinked).Symbol;
// All factors:
_universe = AddUniverse<FactorsUniverse>(SelectAssets);

Data Summary

The following table describes the dataset properties:

PropertyValue
Start DateJanuary 1998
Data DensityDense
Asset Coverage100s of US Equities, plus unlinked factors
ResolutionDaily
TimezoneNew York

Requesting Data

To add Factors data to your algorithm, call the AddDataadd_data method. For the factors linked to a specific Equity, pass the underlying Equity Symbol. For the unlinked factors, which aren't tied to any tradable security, pass Factors.UnlinkedFactors.UNLINKED. Save a reference to each dataset Symbol so you can access the data later in your algorithm.

class FactorsDataAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2014, 3, 25)
        self.set_end_date(2014, 4, 8)
        self.set_cash(100000)
        self._equity = self.add_equity("AAPL", Resolution.DAILY)
        self._equity.factors = self.add_data(Factors, self._equity.symbol).symbol
        self._unlinked_factors = self.add_data(Factors, Factors.UNLINKED).symbol
public class FactorsDataAlgorithm : QCAlgorithm
{
    private Equity _equity;
    private Symbol _equityFactors, _unlinkedFactors;

    public override void Initialize()
    {
        SetStartDate(2014, 3, 25);
        SetEndDate(2014, 4, 8);
        SetCash(100000);
        _equity = AddEquity("SPY", Resolution.Daily);
        _equityFactors = AddData<Factors>(_equity.Symbol).Symbol;
        _unlinkedFactors = AddData<Factors>(Factors.Unlinked).Symbol;
    }
}

Accessing Data

To get the current factor 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. Each Factors object behaves like a dictionary, mapping the factor name to its value. Index the object with a factor name constant (for example, Factors.Technical.Roc1DayFactors.Technical.ROC_1_DAY is "technical_roc_1d") to get the value.

def on_data(self, data: Slice) -> None:
    equity_factors = data.get(Factors).get(self._equity.factors)
    if equity_factors:
        value = equity_factors[Factors.ROC_1_DAY]

    unlinked_factors = data.get(Factors).get(self._unlinked_factors)
    if unlinked_factors:
        ust_yield = unlinked_factors[Factors.UST_YIELD_1_MONTH]
public override void OnData(Slice data)
{
    if (data.Get<Factors>().TryGetValue(_equityFactors, out var equityFactors))
    {
        var value = equityFactors[Factors.Roc1Day];
    }

    if (data.Get<Factors>().TryGetValue(_unlinkedFactors, out var unlinkedFactors))
    {
        var ustYield = unlinkedFactors[Factors.UstYield1Month];
    }
}

Historical Data

To get historical factor data, call the Historyhistory method with the dataset Symbol. If there is no data in the period you request, the history result is empty.

# DataFrames
equity_factors_history_df = self.history(self._equity.factors, 100, Resolution.DAILY)
unlinked_factors_history_df = self.history(self._unlinked_factors, 100, Resolution.DAILY)

# Dataset objects
equity_factors_history = self.history[Factors](self._equity.factors, 100, Resolution.DAILY)
market_factors_history = self.history[Factors](self._unlinked_factors, 100, Resolution.DAILY)
var equityFactorsHistory = History<Factors>(_equityFactors, 100, Resolution.Daily);
var unlinkedFactorsHistory = History<Factors>(_marketFactors, 100, Resolution.Daily);

For more information about historical data, see History Requests.

Universe Selection

To select a dynamic universe of US Equities based on factor values, call the AddUniverseadd_universe method with the FactorsUniverse class and a selection function.

def initialize(self) -> None:
    self._universe = self.add_universe(FactorsUniverse, self._select_assets)

def _select_assets(self, data: List[FactorsUniverse]) -> List[Symbol]:
    ust_yield = None
    positive = []
    negative = []
    for factors in data:
        if Factors.UST_YIELD_1_MONTH in factors.keys:
            ust_yield = factors[Factors.UST_YIELD_1_MONTH]
        elif Factors.ROC_1_DAY in factors.keys:
            if factors[Factors.ROC_1_DAY] > 0:
                positive.append(factors.symbol)
            else:
                negative.append(factors.symbol)
    return positive if ust_yield < 4 else negative
private Universe _universe;

public override void Initialize()
{
    _universe = AddUniverse<FactorsUniverse>(SelectAssets);
}

private IEnumerable<Symbol> SelectAssets(IEnumerable<BaseData> data)
{
    decimal? ustYield = null;
    var positive = new List<Symbol>();
    var negative = new List<Symbol>();
    foreach (var factors in data.OfType<FactorsUniverse>())
    {
        if (factors.ContainsKey(Factors.UstYield1Month))
        {
            ustYield = factors[Factors.UstYield1Month];
        }
        else if (factors.ContainsKey(Factors.Roc1Day))
        {
            if (factors[Factors.Roc1Day] > 0)
            {
                positive.Add(factors.Symbol);
            }
            else
            {
                negative.Add(factors.Symbol);
            }
        }
    }
    return ustYield < 4 ? positive : negative;
}

For more information about dynamic universes, see Universes.

Universe History

You can get historical universe data in an algorithm and in the Research Environment.

Historical Universe Data in Algorithms

To get historical universe data in an algorithm, call the Historyhistory method with the Universe object and the lookback period. If there is no data in the period you request, the history result is empty.

var universeHistory = History(_universe, 30, Resolution.Daily);
foreach (var universeDay in universeHistory)
{
    foreach (FactorsUniverse factors in universeDay)
    {
        if (factors.TryGetValue(Factors.Roc1Day, out var value))
        {
            // ...
        }
    }
}
# DataFrame example where the columns are the FactorsUniverse attributes:
history_df = self.history(self._universe, 30, Resolution.DAILY, flatten=True)

# Series example where the values are lists of FactorsUniverse objects:
universe_history = self.history(self._universe, 30, Resolution.DAILY)
for (_, time), universe_day in universe_history.items():
    for factors in universe_day:
        if Factors.ROC_1_DAY in factors.keys:
            value = factors[Factors.ROC_1_DAY]

Historical Universe Data in Research

To get historical universe data in research, call the UniverseHistoryuniverse_history method with the Universe object, a start date, and an end date. This method returns the filtered universe. If there is no data in the period you request, the history result is empty.

var universeHistory = qb.History(universe, qb.Time.AddDays(-30), qb.Time);
foreach (var universeDay in universeHistory)
{
    foreach (FactorsUniverse factors in universeDay)
    {
        if (factors.TryGetValue(Factors.Roc1Day, out var value))
        {
            // ...
        }
    }
}
# DataFrame example where the columns are the FactorsUniverse attributes:
history = qb.history(universe, qb.time - timedelta(30), qb.time, flatten=True)

You can call the Historyhistory method in Research.

Remove Subscriptions

To remove a subscription, call the RemoveSecurityremove_security method.

self.remove_security(self._equity.factors)
RemoveSecurity(_equityFactors);

If you subscribe to Factors data for assets in a dynamic universe, remove the dataset subscription when the asset leaves your universe. To view a common design pattern, see Track Security Changes.

Supported Factors

The Factors and FactorsUniverse objects behave like a dictionary, mapping the factor name to its value. The Factors class provides name constants for every factor.

Linked Factors

Linked factors are factors that are tied to a specific tradable security. The Factors dataset provides the following linked factors for US Equities:

  • Factors.ROC_1_DAYFactors.Roc1Day: 1-day rate of change of the close, close[t] / close[t-1] - 1, ranked each session among SPY's constituents. The factor holds the bottom tenth long and the top tenth short, equally weighted.
  • Factors.VOLATILITY_21_DAYFactors.Volatility21Day: 21-day realized volatility, the standard deviation of the 1-day close-to-close returns over the trailing 21 days, ranked each session among SPY's constituents. The factor holds the top tenth long and the bottom tenth short, equally weighted.
  • Factors.VOLUME_Z_21_DAYFactors.VolumeZ21Day: 21-day volume z-score, the number of standard deviations the session's volume sits above or below its trailing 21-day mean, ranked each session among SPY's constituents. The factor holds the top tenth long and the bottom tenth short, equally weighted.
  • Factors.FINRA_SHORT_SALE_VOLUME_SHORT_VOLUME_RATIO_SMA_21_DAYFactors.FinraShortSaleVolumeShortVolumeRatioSma21Day: 21-point mean of the FINRA Reg SHO daily short volume ratio, the share of a stock's off-exchange reported volume executed as short sales, ranked each session among SPY's constituents. The factor holds the bottom tenth long and the top tenth short, equally weighted.
  • Factors.SPECTRAL_TICK_FLOW_SIGNAL_EXECUTION_SCOREFactors.SpectralTickFlowSignalExecutionScore: Algorithmic execution-flow intensity, QuantConnect's Spectral Tick Flow Signal execution score: the normalized strength of the strongest recurring intraday execution rhythm in the stock's tick data, ranked each session among SPY's constituents. The factor holds the top tenth long and the bottom tenth short, equally weighted.
  • Factors.EARNING_YIELDFactors.EarningYield: Trailing earnings yield, Morningstar's ValuationRatios.EarningYield: diluted EPS over price, ranked each session among SPY's constituents. The factor holds the bottom tenth long and the top tenth short, equally weighted.
  • Factors.MFI_21_DAYFactors.Mfi21Day: 21-day Money Flow Index, the share of the typical price's money flow over 21 sessions that came on sessions the typical price rose, from 0 to 100, ranked each session among SPY's constituents. The factor holds the bottom tenth long and the top tenth short, equally weighted.
  • Factors.MOM_12_MONTHFactors.Mom12Month: Twelve-month momentum skipping the most recent month, the stock's return over months t-11 through t-1 with 21 sessions to a month, from Jegadeesh and Titman (1993, JF), ranked each session among SPY's constituents. The factor holds the bottom tenth long and the top tenth short, equally weighted.
  • Factors.INT_MOMFactors.IntMom: Intermediate momentum, the stock's return over months t-12 through t-7 with 21 sessions to a month, from Novy-Marx (2012, JFE), ranked each session among SPY's constituents. The factor holds the bottom tenth long and the top tenth short, equally weighted.
  • Factors.MOM_12_MONTH_OFF_SEASONFactors.Mom12MonthOffSeason: Momentum without the seasonal month, the mean of the monthly returns of months t-1 through t-10 with 21 sessions to a month, from Heston and Sadka (2008, JFE), ranked each session among SPY's constituents. The factor holds the top tenth long and the bottom tenth short, equally weighted.
  • Factors.VOLUME_TRENDFactors.VolumeTrend: Volume trend, the slope of a regression of monthly volume on a linear time trend over the trailing 60 months over the mean monthly volume, with 21 sessions to a month and at least 30 months, from Haugen and Baker (1996, JFE), ranked each session among SPY's constituents. The factor holds the bottom tenth long and the top tenth short, equally weighted.
  • Factors.MOM_SEASON_SHORTFactors.MomSeasonShort: Return seasonality last year, the stock's return over the 21 sessions from 252 to 231 sessions ago, from Heston and Sadka (2008, JFE), ranked each session among SPY's constituents. The factor holds the top tenth long and the bottom tenth short, equally weighted.
  • Factors.ILLIQUIDITYFactors.Illiquidity: Amihud illiquidity, the mean over the past 12 months of the daily ratio of the absolute return to the dollar volume traded, from Amihud (2002, JFM), ranked each session among SPY's constituents. The factor holds the top tenth long and the bottom tenth short, equally weighted.
  • Factors.GROSS_PROFITS_TO_ASSETSFactors.GrossProfitsToAssets: Gross profits to assets from Novy-Marx (2013, JFE). It's annual revenue minus cost of revenue over total assets from Morningstar's annual accounts, and financial firms are left out. A fiscal year is used from six months after it ends, for twelve months. Formed at each month's last close and ranked each session among SPY's constituents. The factor holds the top tenth long and the bottom tenth short, equally weighted.
  • Factors.RD_TO_MARKET_VALUEFactors.RdToMarketValue: R&D to market value from Chan, Lakonishok and Sougiannis (2001, JF). It's annual research and development expense from Morningstar's annual accounts over the month's market value, and a stock without R&D has no value. A fiscal year is used from six months after it ends, for twelve months. Formed at each month's last close and ranked each session among SPY's constituents. The factor holds the top tenth long and the bottom tenth short, equally weighted.
  • Factors.OPERATING_PROFITABILITY_RD_ADJUSTEDFactors.OperatingProfitabilityRdAdjusted: R&D-adjusted operating profitability from Ball et al. (2016, JFE). It's annual revenue minus cost of revenue and SG&A over total assets, from Morningstar's annual accounts. Morningstar's SG&A leaves out R&D, so R&D isn't counted as an expense. A filing without book equity has no value, and financial firms are left out. A fiscal year is used from six months after it ends, for twelve months. Formed at each month's last close and ranked each session among SPY's constituents. The factor holds the top tenth long and the bottom tenth short, equally weighted.
  • Factors.FABER_10_MONTH_SMA_SECTOR_ETFSFactors.Faber10MonthSmaSectorEtfs: The 10-month moving average timing rule from Faber (2007, Journal of Wealth Management), on the eleven Select Sector SPDR ETFs. An ETF's value is its month-end close over the mean of its last ten month-end closes, minus one. The factor holds an ETF long while its value is positive and nothing otherwise.
  • Factors.SALES_TO_PRICEFactors.SalesToPrice: Sales to price from Barbee, Mukherji and Raines (1996, Financial Analysts Journal). It's annual revenue from Morningstar's annual accounts over the month's market value. A fiscal year is used from six months after it ends, for twelve months. Formed at each month's last close and ranked each session among SPY's constituents. The factor holds the top tenth long and the bottom tenth short, equally weighted.
  • Factors.CASH_BASED_OPERATING_PROFITABILITYFactors.CashBasedOperatingProfitability: Cash-based operating profitability from Ball et al. (2016, JFE). Operating profitability is revenue minus cost of revenue and SG&A from Morningstar's annual accounts. The cash-based measure takes out the year's increase in receivables, inventory and prepaid assets and adds back the year's increase in deferred revenue, accounts payable and accrued expenses. It's then taken over total assets. A missing figure counts as zero. A stock without positive book equity or market value has no value, and financial firms are left out. A fiscal year is used from six months after it ends, for twelve months. Formed at each month's last close and ranked each session among SPY's constituents. The factor holds the top tenth long and the bottom tenth short, equally weighted.
  • Factors.INVESTMENT_TO_REVENUE_VS_OWN_MEANFactors.InvestmentToRevenueVsOwnMean: Abnormal investment from Titman, Wei and Xie (2004, JFQA). It's annual capital expenditure over revenue from Morningstar's annual accounts, over the stock's own mean of that ratio across the past 36 months, which needs at least 24. A stock with revenue under $10 million has no value. A fiscal year is used from six months after it ends, for twelve months. Formed at each month's last close and ranked each session among SPY's constituents. The factor holds the bottom tenth long and the top tenth short, equally weighted.
  • Factors.COMPOSITE_EQUITY_ISSUANCE_5_YEARFactors.CompositeEquityIssuance5Year: Composite equity issuance from Daniel and Titman (2006, JF). It's the log growth of market value over the past 60 months minus the stock's return over them, so it measures the equity issued net of buybacks. Market value is Morningstar's at each month's end, and the return comes from adjusted closes. A stock priced at $5 or less has no value. Formed at each month's last close and ranked each session among SPY's constituents. The factor holds the bottom tenth long and the top tenth short, equally weighted.
  • Factors.BID_ASK_SPREAD_CSFactors.BidAskSpreadCs: Bid-ask spread from Amihud and Mendelson (1986, JFE) with the high-low estimator from Corwin and Schultz (2012, JF). Each session's estimate compares the ranges of that session and the one before with the range over both, on adjusted daily bars. A range with the high equal to the low, a price that isn't positive or no volume is replaced from the last good range and the close. A range with the high over 8 times the low is dropped, and a range is shifted to take in the prior close when that close lies outside it. Negative estimates count as 0. A month's value is the mean of its daily estimates and needs at least 12 of them. Formed at each month's last close and ranked each session among SPY's constituents. The factor holds the top tenth long and the bottom tenth short, equally weighted.
  • Factors.VOLUME_SD_36_MONTHFactors.VolumeSd36Month: The standard deviation of a stock's monthly share volume over the past 36 months from Chordia, Subrahmanyam and Anshuman (2001, JFE). A stock needs at least 24 of those months, and a month's volume is the sum of its unadjusted daily volumes. Only stocks that Morningstar lists on the NYSE at the formation are ranked. Formed at each month's last close and ranked each session among SPY's constituents. The factor holds the top tenth long and the bottom tenth short, equally weighted.
  • Factors.SHORT_INTERESTFactors.ShortInterest: Short interest, from Dechow et al. (2001, JFE): the shares held short in FINRA's report over Morningstar's shares outstanding of the share class. Each month uses the report FINRA published in the month before on the 16th or later. Formed at the first update of SPY's constituents in each month and ranked then among them. The factor holds the fifth with the least short interest long and the fifth with the most short, equally weighted.
  • Factors.INTANGIBLE_RETURN_BMFactors.IntangibleReturnBm: The intangible return on book-to-market, from Daniel and Titman (2006, JF). Each month the 60-month returns of SPY's constituents are regressed on their log book-to-market from 60 months before and on its change over the 60 months plus the return. The residual is the factor's value. Book equity is common stock equity from Morningstar's annual accounts, used from six months after the fiscal year ends for twelve months. Market value is Morningstar's at formation, and the ratio must be positive. Returns come from month-end closes adjusted for splits and dividends. Returns below the 1st percentile of the month's constituents or above the 99th are left out of the regression, and stocks at $5 or less are left out after it. Formed at each month's last close and ranked each session among SPY's constituents. The factor holds the top tenth long and the bottom tenth short, equally weighted.
  • Factors.INTANGIBLE_RETURN_CFPFactors.IntangibleReturnCfp: The intangible return on cash flow to price, from Daniel and Titman (2006, JF). Each month the 60-month returns of SPY's constituents are regressed on their log cash flow to price from 60 months before and on its change over the 60 months plus the return. The residual is the factor's value. Cash flow is net income less discontinued operations plus depreciation and amortization, from Morningstar's annual accounts. Discontinued operations count as 0 when missing, and so does depreciation that's missing or from another period's cash flow statement. A fiscal year is used from six months after it ends for twelve months. Market value is Morningstar's at formation, and the ratio must be positive. Returns come from month-end closes adjusted for splits and dividends. Returns below the 1st percentile of the month's constituents or above the 99th are left out of the regression, and stocks at $5 or less are left out after it. Formed at each month's last close and ranked each session among SPY's constituents. The factor holds the bottom tenth long and the top tenth short, equally weighted.
  • Factors.INVESTMENT_PPE_INVENTORYFactors.InvestmentPpeInventory: Investment from Lyandres, Sun and Zhang (2008, RFS): the negative of the yearly change in gross PPE plus inventory over the total assets a year before. The figures are Morningstar's annual accounts from a 10-K, 20-F or 40-F filing. A fiscal year is used from 6 to 17 months after the month it ends and the latest one wins. Formed at each month's last close and carried to each session for SPY's constituents. Each constituent's position is the z-score of its value against all of its daily values so far. It needs 126 of them and is capped at 2 either way.
  • Factors.MOM_SEASON_6_TO_10_YEARFactors.MomSeason6To10Year: Return seasonality from Heston and Sadka (2008, JFE): the mean of a stock's returns in the same calendar month as the coming one over the years 6 to 10 before. A month's return runs from the last adjusted close of the month before to its own last close, and the mean takes the years that have one. Formed at each month's last close and ranked then among SPY's constituents listed on the NYSE or AMEX. A stock keeps its rank until the next formation while it stays in SPY. The factor holds the top tenth long and the bottom tenth short, equally weighted.
  • Factors.SPECULATIVE_PRESSURE_COMMODITY_ETFSFactors.SpeculativePressureCommodityEtfs: Speculative pressure from Fan et al. (2020, Journal of Futures Markets) on twelve commodity ETFs that stand in for the futures. A commodity's pressure is the mean over the past year of its speculators' long minus short positions over their sum, from the CFTC's legacy Commitments of Traders reports. A report counts from its release and the mean needs 26 of them. At each month's last close the pressures of the commodities whose ETF traded that month are standardized across them. Each value is a commodity's z-score over the sum of the z-scores' sizes, times the number of commodities. The values are the positions, held for the month.
  • Factors.TREASURY_FORWARD_SPREAD_ETFSFactors.TreasuryForwardSpreadEtfs: The forward-spot spread from Fama and Bliss (1987, American Economic Review) on four Treasury ETFs. The spread is the one-year forward rate from year n-1 to n minus the one-year yield, on the Treasury's par yield curve. Each ETF takes the n of the maturity it holds: 2 years for SHY and 5 for IEI, with 10 for IEF and 20 for TLT. A yield the curve lacks is interpolated linearly in maturity. The spread is taken on each month's last curve date and stamped at the midnight after it. Each ETF's position is the z-score of its spread against all of its monthly spreads so far. It needs 36 of them and is capped at 2 either way.
  • Factors.COMMODITY_MOMENTUM_ETFSFactors.CommodityMomentumEtfs: Commodity momentum from Miffre and Rallis (2007, Journal of Banking and Finance) on twelve commodity ETFs that stand in for the futures. At each month's last close the ETFs are ranked on their log return over the past 12 months, from each one's last close in the month a year before. The factor holds the top fifth long and the bottom fifth short for the month in equal weights. A fifth is a fifth of the ranked ETFs rounded, and at least one. Each value is the position times the number of ranked ETFs over the number in a fifth.
  • Factors.TREASURY_AUCTION_CYCLE_ETFSFactors.TreasuryAuctionCycleEtfs: The Treasury auction cycle from Lou, Yan and Zhang (2013, Review of Financial Studies) on four Treasury ETFs. Each ETF follows the auctions of the maturity it holds: SHY the 2-year note's and IEI the 5-year note's, with IEF the 10-year note's and TLT the 30-year bond's. The auction dates come from EODHD's economic events calendar from 2019. An auction counts once the calendar lists it. Each value is -1 in the 5 sessions before an auction and +1 in the 5 sessions after it, leaving out the auction's session, and 0 otherwise. The values are the positions.

Unlinked Factors

Unlinked factors are factors that aren't tied to a specific tradable security, like weather data or interest rates. The Factors dataset provides the following unlinked factors:

  • Factors.UST_YIELD_1_MONTHFactors.UstYield1Month: 1-month US Treasury yield curve rate, as published daily at 16:30 New York time. The positions rank each of SPY's constituents on its sensitivity to the yield: the slope on the yield's daily change when the stock's daily returns over the past 21 sessions are regressed on SPY's return and that change. The factor holds the bottom tenth long and the top tenth short, equally weighted.
  • Factors.VIXFactors.Vix: CBOE Volatility Index (VIX), the market's expectation of 30-day S&P 500 volatility. The series is VIX's daily close. The positions rank each of SPY's constituents on its sensitivity to VIX: the slope on VIX's daily change when the stock's daily returns over the past 21 sessions are regressed on SPY's return and that change. The factor holds the top tenth long and the bottom tenth short, equally weighted.
  • Factors.WTI_CRUDE_OILFactors.WtiCrudeOil: WTI crude oil price, the daily mid close of Oanda's West Texas Oil CFD in US dollars per barrel. The positions rank each of SPY's constituents on its sensitivity to the price: the slope on the price's daily change when the stock's daily returns over the past 21 sessions are regressed on SPY's return and that change. The factor holds the bottom tenth long and the top tenth short, equally weighted.
  • Factors.MONETARY_CYCLEFactors.MonetaryCycle: Monetary cycle, the monetary environment of Jensen, Mercer and Johnson (1996): +1 while the most recent change in the Federal Reserve's primary credit rate was a decrease and -1 while it was an increase, read from LEAN's risk-free interest rate model at midnight New York on every calendar day. The factor times SPY: it holds SPY short while the cycle is +1 and long while it's -1.
  • Factors.M_2_GROWTH_1_MONTHFactors.M2Growth1Month: M2 money supply growth from one monthly release to the next: the Federal Reserve's seasonally adjusted monthly M2 over its value for the month before, minus one, from FRED's series M2SL as currently revised, stamped at the midnight after the day the Federal Reserve's H.6 release first published it. The positions rank each of SPY's constituents on its sensitivity to the growth: the slope on the growth's change when the stock's returns between releases over the last 60 releases are regressed on SPY's return and that change. The factor holds the top tenth long and the bottom tenth short, equally weighted.
  • Factors.LUNAR_PHASE_COUNTRY_ETFSFactors.LunarPhaseCountryEtfs: The lunar cycle from Yuan, Zheng and Zhu (2006, Journal of Empirical Finance). The series is the lunar phase at midnight New York on every calendar day: -1 within 7 days of a full moon's date and +1 otherwise. Full moons are dated in UTC with Meeus's Astronomical Algorithms (1998). The factor gives each iShares MSCI single-country ETF and SPY the phase of each session from the session after its first close. It holds them long in new moon periods and short in full moon periods.

Pairs Factors

Pairs factors give a value and a position to pairs of securities, each with a hedge ratio. A pair held long is a dollar long its first security against the hedge ratio's dollars short its second. The Factors dataset provides the following pairs factors:

  • Factors.STAT_ARB_SECTOR_ETF_RESIDUALSFactors.StatArbSectorEtfResiduals: Statistical arbitrage from Avellaneda and Lee (2010, Quantitative Finance) on pairs of a stock and its Select Sector SPDR ETF, the one where the stock's weight is largest. Each day the stock's returns over the past 60 sessions are regressed on the ETF's, and the cumulative residuals are fit to a mean-reverting process. The s-score is the process's distance from its equilibrium level in equilibrium standard deviations, with the levels centered on their average across the stocks. The value is the negative s-score and the hedge ratio is the regression's beta. Each value uses the session's close and is stamped at the midnight after it. The factor holds a pair long from a value above 1.25 until it falls below 0.5, and short from a value below -1.25 until it rises above -0.75. It holds nothing while the residual takes more than 30 sessions to revert, and a pair starts flat after a day it isn't listed.

Example Applications

The QuantConnect Factors dataset enables researchers to accurately design strategies harnessing precomputed, point-in-time factor values. Examples include:

  • Factor momentum: form a portfolio that weighs each factor by its recent performance
  • Momentum rotation: rank the universe by 1-day rate of change and hold the leaders
  • Rate regime filters: scale Equity exposure with the level of the 1-month US Treasury yield

Classic Algorithm Example

The following example forms an equal-weighted portfolio of all the stocks that have a long position in the "roc_1d" factor.

# region imports
from AlgorithmImports import *
# endregion


class FactorsPortfolioAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2024, 11, 1)
        self.set_end_date(2026, 10, 1)
        self.set_cash(10_000_000)
        self.settings.seed_initial_prices = True
        self.universe_settings.resolution = Resolution.DAILY
        # Add a universe of the stocks that have a long position in the ROC_1_DAY factor.
        self._universe = self.add_universe(FactorsUniverse, lambda rows: [
                row.symbol for row in rows
                if not row.is_unlinked and not row.is_pair
                and row.has_position(Factors.ROC_1_DAY) and row.position(Factors.ROC_1_DAY) == 1
            ]
        )
        # Form an equal-weighted portfolio of the stocks in the universe.
        self.schedule.on(
            self.date_rules.every_day("SPY"), 
            self.time_rules.at(8, 0), 
            lambda: self.set_holdings([PortfolioTarget(symbol, 1/len(self._universe.selected)) for symbol in self._universe.selected], True)
        )
public class FactorsPortfolioAlgorithm : QCAlgorithm
{
    private Universe _universe;

    public override void Initialize()
    {
        SetStartDate(2024, 11, 1);
        SetEndDate(2026, 10, 1);
        SetCash(10_000_000);
        Settings.SeedInitialPrices = true;
        UniverseSettings.Resolution = Resolution.Daily;
        // Add a universe of the stocks that have a long position in the ROC_1_DAY factor.
        _universe = AddUniverse<FactorsUniverse>(rows => rows.OfType<Factors>()
            .Where(row => !row.IsUnlinked && !row.IsPair
                && row.HasPosition(Factors.Roc1Day) && row.Position(Factors.Roc1Day) == 1)
            .Select(row => row.Symbol));
        // Form an equal-weighted portfolio of the stocks in the universe.
        Schedule.On(
            DateRules.EveryDay("SPY"),
            TimeRules.At(8, 0),
            () => SetHoldings(_universe.Selected.Select(symbol => new PortfolioTarget(symbol, 1m / _universe.Selected.Count)).ToList(), true)
        );
    }
}

Framework Algorithm Example

The following example algorithm selects the SPY constituents, the dataset's coverage universe. The Alpha model emits daily ROC-weighted insights for the Equities that moved more than 1% over the last trading session, targeting only long positions while the 1-month US Treasury yield is below 4% and only short positions otherwise.

from AlgorithmImports import *


class FactorsFrameworkAlgorithm(QCAlgorithm):

    def initialize(self) -> None:
        self.set_start_date(2025, 9, 1)
        self.set_end_date(2025, 12, 31)
        self.set_cash(10_000_000)

        self.universe_settings.resolution = Resolution.DAILY
        self.add_universe_selection(ETFConstituentsUniverseSelectionModel("SPY"))
        self.add_alpha(FactorsAlphaModel(self))
        self.set_portfolio_construction(InsightWeightingPortfolioConstructionModel())


class FactorsAlphaModel(AlphaModel):

    def __init__(self, algorithm: QCAlgorithm) -> None:
        self._unlinked_factors = algorithm.add_data(Factors, Factors.UNLINKED).symbol
        self._roc_by_symbol = {}

    def update(self, algorithm: QCAlgorithm, data: Slice) -> List[Insight]:
        # Cache the Equities that moved more than 1%. Their factors arrive with
        # the session's 4PM close, ahead of the unlinked factors row.
        for symbol, factors in data.get(Factors).items():
            if Factors.ROC_1_DAY in factors.keys and abs(factors[Factors.ROC_1_DAY]) > 0.01:
                self._roc_by_symbol[symbol.underlying] = factors[Factors.ROC_1_DAY]

        # The unlinked factors arrive at 4:30PM, when the US Treasury publishes
        # the daily yield curve rates, completing the session's signals.
        unlinked_factors = data.get(Factors).get(self._unlinked_factors)
        if not unlinked_factors or Factors.UST_YIELD_1_MONTH not in unlinked_factors.keys:
            return []

        # Consume the session's cache so stale values never roll into the
        # next emission.
        roc_by_symbol = self._roc_by_symbol
        self._roc_by_symbol = {}

        # While short-term rates are low, only target long assets. Otherwise,
        # only target short assets.
        if unlinked_factors[Factors.UST_YIELD_1_MONTH] < 4:
            direction = InsightDirection.UP
            selected = {s: roc for s, roc in roc_by_symbol.items() if roc > 0}
        else:
            direction = InsightDirection.DOWN
            selected = {s: roc for s, roc in roc_by_symbol.items() if roc < 0}
        if not selected:
            return []

        # Weight each insight by the magnitude of the asset's ROC.
        total_roc = sum(abs(roc) for roc in selected.values())
        return [
            Insight.price(symbol, timedelta(1), direction, weight=abs(roc)/total_roc)
            for symbol, roc in selected.items()
        ]

    def on_securities_changed(self, algorithm: QCAlgorithm, changes: SecurityChanges) -> None:
        for security in changes.added_securities:
            security.factors = algorithm.add_data(Factors, security.symbol).symbol
        for security in changes.removed_securities:
            algorithm.remove_security(security.factors)
            self._roc_by_symbol.pop(security.symbol, None)
public class FactorsFrameworkAlgorithm : QCAlgorithm
{
    public override void Initialize()
    {
        SetStartDate(2025, 9, 1);
        SetEndDate(2025, 12, 31);
        SetCash(10000000);

        UniverseSettings.Resolution = Resolution.Daily;
        AddUniverseSelection(new ETFConstituentsUniverseSelectionModel("SPY"));
        AddAlpha(new FactorsAlphaModel(this));
        SetPortfolioConstruction(new InsightWeightingPortfolioConstructionModel());
    }
}

public class FactorsAlphaModel : AlphaModel
{
    private readonly Symbol _unlinkedFactors;
    private Dictionary<Symbol, decimal> _rocBySymbol = new Dictionary<Symbol, decimal>();

    public FactorsAlphaModel(QCAlgorithm algorithm)
    {
        _unlinkedFactors = algorithm.AddData<Factors>(Factors.Unlinked).Symbol;
    }

    public override IEnumerable<Insight> Update(QCAlgorithm algorithm, Slice data)
    {
        // Cache the Equities that moved more than 1%. Their factors arrive with
        // the session's 4PM close, ahead of the unlinked factors row.
        foreach (var factors in data.Get<Factors>().Values)
        {
            if (factors.ContainsKey(Factors.Roc1Day) && Math.Abs(factors[Factors.Roc1Day]) > 0.01m)
            {
                _rocBySymbol[factors.Symbol.Underlying] = factors[Factors.Roc1Day];
            }
        }

        // The unlinked factors arrive at 4:30PM, when the US Treasury publishes
        // the daily yield curve rates, completing the session's signals.
        if (!data.Get<Factors>().TryGetValue(_unlinkedFactors, out var unlinkedFactors) || !unlinkedFactors.ContainsKey(Factors.UstYield1Month))
        {
            return Enumerable.Empty<Insight>();
        }

        // Consume the session's cache so stale values never roll into the
        // next emission.
        var rocBySymbol = _rocBySymbol;
        _rocBySymbol = new Dictionary<Symbol, decimal>();

        // While short-term rates are low, only target long assets. Otherwise,
        // only target short assets.
        InsightDirection direction;
        List<KeyValuePair<Symbol, decimal>> selected;
        if (unlinkedFactors[Factors.UstYield1Month] < 4)
        {
            direction = InsightDirection.Up;
            selected = rocBySymbol.Where(kvp => kvp.Value > 0).ToList();
        }
        else
        {
            direction = InsightDirection.Down;
            selected = rocBySymbol.Where(kvp => kvp.Value < 0).ToList();
        }
        if (selected.Count == 0)
        {
            return Enumerable.Empty<Insight>();
        }

        // Weight each insight by the magnitude of the asset's ROC.
        var totalRoc = selected.Sum(kvp => Math.Abs(kvp.Value));
        return selected.Select(kvp =>
            Insight.Price(kvp.Key, TimeSpan.FromDays(1), direction, weight: (double)(Math.Abs(kvp.Value) / totalRoc)));
    }

    public override void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes)
    {
        foreach (dynamic security in changes.AddedSecurities)
        {
            security.Factors = algorithm.AddData<Factors>(security.Symbol).Symbol;
        }
        foreach (dynamic security in changes.RemovedSecurities)
        {
            algorithm.RemoveSecurity(security.Factors);
            _rocBySymbol.Remove(security.Symbol);
        }
    }
}

Data Point Attributes

The Factors dataset provides Factors and FactorsUniverse objects.

Factors Attributes

Factors objects has the following attributes:

FactorsUniverse Attributes

FactorsUniverse objects has the following attributes:

You can also see our Videos. You can also get in touch with us via Discord.

Did you find this page helpful?

Contribute to the documentation: