Skip to content

Factors

QuantConnect.DataSource.Factors

Factors()

Bases: DynamicData

Precomputed factors. One class serves both kinds of factor data: linked factors for a single US Equity (subscribe with the Equity's Symbol) and unlinked factors that aren't tied to a tradable security, such as US Treasury yield curve rates (subscribe with UNLINKED). Each data point behaves like a dictionary of factor name to value.

Creates an empty instance, required by LEAN to construct the type

UNLINKED

UNLINKED: str = '$UNLINKED'

Ticker for the unlinked factors subscription

ROC_1_DAY

ROC_1_DAY: str = 'technical_roc_1d'

1-day rate of change of the closing price: close / close - 1

VOLATILITY_21_DAY

VOLATILITY_21_DAY: str = 'technical_volatility_21d'

21-day realized volatility of daily returns: the standard deviation of 1-day closing-price returns over the trailing 21 days

VOLUME_Z_21_DAY

VOLUME_Z_21_DAY: str = 'technical_volume_z_21d'

21-day volume z-score: the number of standard deviations the current trading volume sits above or below its trailing 21-day mean

FINRA_SHORT_SALE_VOLUME_SHORT_VOLUME_RATIO_SMA_21_DAY

FINRA_SHORT_SALE_VOLUME_SHORT_VOLUME_RATIO_SMA_21_DAY: (
    str
) = "alternative_finra_short_sale_volume_short_volume_ratio_sma_21d"

21-day simple moving average of the FINRA Reg SHO daily short volume ratio: the share (0-1) of a security's off-exchange reported volume executed as short sales during regular trading hours, aggregated from trades broker-dealers file with FINRA

SPECTRAL_TICK_FLOW_SIGNAL_EXECUTION_SCORE

SPECTRAL_TICK_FLOW_SIGNAL_EXECUTION_SCORE: str = (
    "alternative_spectral_tick_flow_signal_execution_score"
)

Algorithmic execution-flow intensity: the normalized strength of the strongest recurring intraday execution rhythm in the security's tick data, derived by QuantConnect's Fourier transform-like decomposition of daily US Equity trades (SpectralTickFlowSignal.ExecutionScore); a non-negative normalized score, higher meaning trade flow more strongly backed by an active, repeating execution signature.

UST_YIELD_1_MONTH

UST_YIELD_1_MONTH: str = 'market_ust_yield_1m'

1-month US Treasury yield curve rate

EARNING_YIELD

EARNING_YIELD: str = 'fundamental_earning_yield'

Trailing earnings yield: Morningstar's ValuationRatios.EarningYield, diluted EPS divided by price (the inverse trailing P/E), so higher values indicate cheaper stocks relative to trailing earnings.

MFI_21_DAY

MFI_21_DAY: str = 'technical_mfi_21d'

21-day Money Flow Index: volume-weighted buying vs. selling pressure, from daily typical price changes signed and weighted by volume, accumulated over 21 sessions and bounded 0-100.

MOM_12_MONTH

MOM_12_MONTH: str = 'technical_mom_12m'

Twelve-month momentum skipping the most recent month: the stock's return over months t-11 through t-1, computed each session from LEAN's adjusted daily closes, from Jegadeesh and Titman (1993, JF), where higher values predicted higher returns

INT_MOM

INT_MOM: str = 'technical_int_mom'

Intermediate momentum: the stock's return over months t-12 through t-7, computed each session from LEAN's adjusted daily closes, from Novy-Marx (2012, JFE), where higher values predicted higher returns

MOM_12_MONTH_OFF_SEASON

MOM_12_MONTH_OFF_SEASON: str = (
    "technical_mom_12m_off_season"
)

Momentum without the seasonal month: the mean of the monthly returns of months t-1 through t-10, which leaves out the current month and month t-11, the month one year before the coming month, computed each session from LEAN's adjusted daily closes, from Heston and Sadka (2008, JFE), where higher values predicted higher returns

VIX

VIX: str = 'market_vix'

CBOE Volatility Index (VIX) daily close: the market's expectation of 30-day S&P 500 volatility implied by index option prices, in annualized percentage points

WTI_CRUDE_OIL

WTI_CRUDE_OIL: str = 'market_wti_crude_oil'

WTI crude oil price: the daily mid close of Oanda's West Texas Oil CFD, in US dollars per barrel, a continuous quote that tracks the front NYMEX contract without roll jumps

MONETARY_CYCLE

MONETARY_CYCLE: str = 'market_monetary_cycle'

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 (expansive) and -1 while it was an increase (restrictive), read from LEAN's risk-free interest rate model for every calendar day at midnight New York; the state flips on the day the model's rate changes

VOLUME_TREND

VOLUME_TREND: str = 'technical_volume_trend'

Volume trend: the slope of a regression of monthly volume on a linear time trend over the trailing 60 months, divided by the mean monthly volume over those months, computed each session from LEAN's split- and dividend-adjusted daily volume with 21 sessions to a month and at least 30 months required, from Haugen and Baker (1996, JFE), where higher values predicted lower returns

MOM_SEASON_SHORT

MOM_SEASON_SHORT: str = 'technical_mom_season_short'

Return seasonality last year: the stock's return over the 21 sessions from 252 to 231 sessions ago, the month one year before the coming month, computed each session from LEAN's adjusted daily closes, from Heston and Sadka (2008, JFE), where higher values predicted higher returns

ILLIQUIDITY

ILLIQUIDITY: str = 'technical_illiquidity'

Amihud illiquidity: the mean over the past 12 months of the daily ratio of the absolute return to the dollar volume traded, computed each session from LEAN's adjusted daily bars, from Amihud (2002, JFM), where higher values predicted higher returns

M_2_GROWTH_1_MONTH

M_2_GROWTH_1_MONTH: str = 'market_m2_growth_1m'

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; each month's value is stamped at 13:00 New York on the fourth Tuesday of the following month, when the Federal Reserve's H.6 release publishes it

EQUITY_FACTOR_NAMES

EQUITY_FACTOR_NAMES: List[str] = ...

Column order of the per-Equity factor files, fixed by the dataset specification so rows parse without header state

UNLINKED_FACTOR_NAMES

UNLINKED_FACTOR_NAMES: List[str] = ...

Column order of the unlinked factor file, fixed by the dataset specification so rows parse without header state

keys

keys: Iterable[str]

Names of the factors this data point carries a value for

is_unlinked

is_unlinked: bool

True when this data point carries the unlinked factors rather than a tradable security's factors

end_time

end_time: datetime

Time the factor values became available. Linked values are stamped at the Equity session close in New York time; unlinked values keep their source series' native end time.

symbol

symbol: Symbol

Symbol representation for underlying Security

data_type

data_type: MarketDataType

Market Data Type of this data - does it come in individual price packets or is it grouped into OHLC.

time

time: datetime

Current time marker of this data packet.

value

value: float

Value representation of this data packet. All data requires a representative value for this moment in time. For streams of data this is the price now, for OHLC packets this is the closing price.

price

price: float

As this is a backtesting platform we'll provide an alias of value as price.

ALL_RESOLUTIONS

ALL_RESOLUTIONS: List[Resolution] = ...

A list of all Resolution

This Field is protected.

DAILY_RESOLUTION

DAILY_RESOLUTION: List[Resolution] = ...

A list of Resolution.DAILY

This Field is protected.

MINUTE_RESOLUTION

MINUTE_RESOLUTION: List[Resolution] = ...

A list of Resolution.MINUTE

This Field is protected.

HIGH_RESOLUTION

HIGH_RESOLUTION: List[Resolution] = ...

A list of high Resolution, including minute, second, and tick.

This Field is protected.

OPTION_RESOLUTIONS

OPTION_RESOLUTIONS: List[Resolution] = ...

A list of resolutions support by Options

This Field is protected.

is_fill_forward

is_fill_forward: bool

True if this is a fill forward piece of data

__getitem__

__getitem__(factor_name: str) -> float

Gets the value of the given factor, e.g. factors

Parameters:

Name Type Description Default
factor_name str

Name of the factor

required

contains_key

contains_key(factor_name: str) -> bool

Checks whether this data point carries a value for the given factor

Parameters:

Name Type Description Default
factor_name str

Name of the factor

required

data_time_zone

data_time_zone() -> Any

Specifies the data time zone for this data type. All factor timestamps are New York time.

Returns:

Type Description
Any

The NodaTime.DateTimeZone of this data type.

default_resolution

default_resolution() -> Resolution

Gets the default resolution for this data and security type

get_source

get_source(
    config: SubscriptionDataConfig,
    date: datetime,
    is_live_mode: bool,
) -> SubscriptionDataSource

Return the URL string source of the file. This will be converted to a stream

Parameters:

Name Type Description Default
config SubscriptionDataConfig

Configuration object

required
date datetime

Date of this source file

required
is_live_mode bool

true if we're in live mode, false for backtesting mode

required

Returns:

Type Description
SubscriptionDataSource

String URL of source file.

is_sparse_data

is_sparse_data() -> bool

Indicates whether the data is sparse. If true, we disable logging for missing files

Returns:

Type Description
bool

true.

reader

reader(
    config: SubscriptionDataConfig,
    line: str,
    date: datetime,
    is_live_mode: bool,
) -> BaseData

Parses the data from the line provided and loads it into LEAN. CSV format: "yyyyMMdd HH:mm" time column, then one column per factor in EQUITY_FACTOR_NAMES or UNLINKED_FACTOR_NAMES order.

Parameters:

Name Type Description Default
config SubscriptionDataConfig

Subscription configuration

required
line str

Line of data

required
date datetime

Date

required
is_live_mode bool

Is live mode

required

Returns:

Type Description
BaseData

New instance, or null for the header line.

requires_mapping

requires_mapping() -> bool

Indicates whether the data source is tied to an underlying symbol and requires that corporate events be applied to it as well, such as renames and delistings

Returns:

Type Description
bool

true for the per-Equity subscription, false for the unlinked one.

supported_resolutions

supported_resolutions() -> List[Resolution]

Gets the supported resolution for this data and security type

to_string

to_string() -> str

Converts the instance to string

try_get_value

try_get_value(
    factor_name: str, value: Optional[float]
) -> Tuple[bool, float]

Gets the value of the given factor if this data point carries one

Parameters:

Name Type Description Default
factor_name str

Name of the factor

required
value Optional[float]

The factor value

required

clone

clone() -> BaseData

Return a new instance clone of this object, used in fill forward

Returns:

Type Description
BaseData

A clone of the current object.

deserialize_message

deserialize_message(serialized: str) -> Sequence[BaseData]

Deserialize the message from the data server

Parameters:

Name Type Description Default
serialized str

The data server's message

required

Returns:

Type Description
Sequence[BaseData]

An enumerable of base data, if unsuccessful, returns an empty enumerable.

should_cache_to_security

should_cache_to_security() -> bool

Indicates whether this contains data that should be stored in the security cache

Returns:

Type Description
bool

Whether this contains data that should be stored in the security cache.

update

update(
    last_trade: float,
    bid_price: float,
    ask_price: float,
    volume: float,
    bid_size: float,
    ask_size: float,
) -> None

Update routine to build a bar/tick from a data update.

Parameters:

Name Type Description Default
last_trade float

The last trade price

required
bid_price float

Current bid price

required
ask_price float

Current asking price

required
volume float

Volume of this trade

required
bid_size float

The size of the current bid, if available

required
ask_size float

The size of the current ask, if available

required

update_ask

update_ask(ask_price: float, ask_size: float) -> None

Updates this base data with the new quote ask information

Parameters:

Name Type Description Default
ask_price float

The current ask price

required
ask_size float

The current ask size

required

update_bid

update_bid(bid_price: float, bid_size: float) -> None

Updates this base data with the new quote bid information

Parameters:

Name Type Description Default
bid_price float

The current bid price

required
bid_size float

The current bid size

required

update_quote

update_quote(
    bid_price: float,
    bid_size: float,
    ask_price: float,
    ask_size: float,
) -> None

Updates this base data with new quote information

Parameters:

Name Type Description Default
bid_price float

The current bid price

required
bid_size float

The current bid size

required
ask_price float

The current ask price

required
ask_size float

The current ask size

required

update_trade

update_trade(last_trade: float, trade_size: float) -> None

Updates this base data with a new trade

Parameters:

Name Type Description Default
last_trade float

The price of the last trade

required
trade_size float

The quantity traded

required

get_meta_object

get_meta_object(parameter: Any) -> Any

Get the metaObject required for Dynamism.

get_property

get_property(name: str) -> Object

Gets the property's value with the specified name. This is a case-insensitve search.

Parameters:

Name Type Description Default
name str

The property name to access

required

Returns:

Type Description
Object

object value of BaseData.

get_storage_dictionary

get_storage_dictionary() -> IDictionary[str, Object]

Gets the storage dictionary Python algorithms need this information since DynamicMetaObject does not work

Returns:

Type Description
IDictionary[str, Object]

Dictionary that stores the paramenters names and values.

has_property

has_property(name: str) -> bool

Gets whether or not this dynamic data instance has a property with the specified name. This is a case-insensitve search.

Parameters:

Name Type Description Default
name str

The property name to check for

required

Returns:

Type Description
bool

True if the property exists, false otherwise.

set_property

set_property(name: str, value: Any) -> Object

Sets the property with the specified name to the value. This is a case-insensitve search.

Parameters:

Name Type Description Default
name str

The property name to set

required
value Any

The new property value

required

Returns:

Type Description
Object

Returns the input value back to the caller.