Research API Reference

This page contains reference materials for functions and classes importable from quantopian.research.

Quick Reference

The tables in this section describe functions and classes importable from quantopian.research.

For more detailed information, see Detailed Reference below.

Pipeline

run_pipeline(pipeline, start_date, end_date) Compute values for pipeline from start_date to end_date, in chunks of size chunksize.

Algorithm Results

get_backtest(backtest_id) Get the results of a backtest that was run on Quantopian.
AlgorithmResult(algo_id, start_date, ...) A container of information describing a backtest's performance.

AlgorithmResult Methods

AlgorithmResult.create_simple_tear_sheet([...]) Simpler version of create_full_tear_sheet; generates summary performance statistics and important plots as a single image.
AlgorithmResult.create_full_tear_sheet([...]) Generate a number of tear sheets that are useful for analyzing a strategy's performance.
AlgorithmResult.create_perf_attrib_tear_sheet(self) Generate plots and tables for analyzing a strategy's performance.
AlgorithmResult.create_position_tear_sheet([...]) Generate a number of plots for analyzing a strategy's positions and holdings.
AlgorithmResult.create_returns_tear_sheet([...]) Generate a number of plots for analyzing a strategy's returns.
AlgorithmResult.preview(attr[, length, ...]) Return a preview of the first length bars of the timeseries stored in getattr(self, attr).

AlgorithmResult Attributes

AlgorithmResult.attrs List of names of attributes of this object.
AlgorithmResult.frames List of names of pd.DataFrame attributes on this object.
AlgorithmResult.scalars List of names of non-DataFrame attributes of this object.
AlgorithmResult.algo_id Return the algorithm's ID
AlgorithmResult.benchmark_security Return the security used as a benchmark for this algorithm.
AlgorithmResult.capital_base Return the capital base for this algorithm.
AlgorithmResult.start_date Return the start date for this algorithm.
AlgorithmResult.end_date Return the end date for this algorithm.
AlgorithmResult.launch_date The real-world datetime at which this backtest started running.
AlgorithmResult.attributed_factor_returns Return a daily datetime-indexed DataFrame containing the algorithm's returns broken down by style and sector risk factors.
AlgorithmResult.factor_exposures Return a daily datetime-indexed DataFrame containing the algorithm's exposures to style and sector risk factors.
AlgorithmResult.cumulative_performance Return a DataFrame with a daily DatetimeIndex containing cumulative performance metrics for the algorithm.
AlgorithmResult.daily_performance Return a DataFrame with a daily DatetimeIndex containing cumulative performance metrics for the algorithm
AlgorithmResult.risk Return a DataFrame with a daily DatetimeIndex representing rolling risk metrics for the algorithm.
AlgorithmResult.recorded_vars Return a DataFrame containing the recorded variables for the algorithm.
AlgorithmResult.orders Return a DataFrame representing a record of all orders made by the algorithm.
AlgorithmResult.positions Return a datetime-indexed DataFrame representing a point-in-time record of positions held by the algorithm during the backtest.
AlgorithmResult.transactions Return a DataFrame representing a record of transactions that occurred during the life of the algorithm.
AlgorithmResult.pyfolio_positions Return a DataFrame containing positions formatted for pyfolio.
AlgorithmResult.pyfolio_transactions Return a DataFrame containing transactions formatted for pyfolio.

Price and Volume Data

symbols(symbols[, symbol_reference_date, ...]) Convert a string or a list of strings into Asset objects.
prices(assets, start, end[, frequency, ...]) Get close price data for assets between start and end.
returns(assets, start, end[, periods, ...]) Fetch returns for one or more assets in a date range.
volumes(assets, start, end[, frequency, ...]) Get trading volume for assets between start and end.
log_prices(assets, start, end[, frequency, ...]) Fetch logarithmic-prices for one or more assets in a date range.
log_returns(assets, start, end[, periods, ...]) Fetch logarithmic-returns for one or more assets in a date range.
get_pricing(symbols[, start_date, end_date, ...]) Load a table of historical trade data.

Experimental APIs

The following functions have been recently added to the Research API. They are importable from quantopian.research.experimental.

We expect to eventually stabilize these APIs and move the functions into the core quantopian.research: module.

Price and Volume Data (Experimental)

history(symbols, fields, start, end, frequency) Load a table of historical trade data.

Risk Model (Experimental)

get_factor_loadings(assets, start, end[, ...]) Retrieve Quantopian Risk Model loadings for a given period.
get_factor_returns(start, end) Retrieve Quantopian Risk Model factor returns for a given period.

Futures (Experimental)

continuous_future(root_symbol[, offset, ...]) Create a specifier for a continuous contract.

Automatic Pre-Imports

For historical reasons, a small number of API functions are automatically imported when you start a research notebook. These functions are:

symbols(symbols[, symbol_reference_date, ...]) Convert a string or a list of strings into Asset objects.
get_pricing(symbols[, start_date, end_date, ...]) Load a table of historical trade data.
get_backtest(backtest_id) Get the results of a backtest that was run on Quantopian.
local_csv(path[, symbol_column, ...]) Load a CSV from the /data directory.

Detailed Reference

This section contains detailed reference information on each function and class importable from quantopian.research and quantopian.research.experimental.

Pipeline

quantopian.research.run_pipeline(pipeline, start_date, end_date, show_progress=True, chunksize=525)

Compute values for pipeline from start_date to end_date, in chunks of size chunksize.

Parameters:
  • pipeline (Pipeline) -- The pipeline to run.
  • start_date (pd.Timestamp) -- First date on which the pipeline should run. If start_date is not a trading day, the pipeline will start on the first trading day after start_date.
  • end_date (pd.Timestamp) -- Last date on which the pipeline should run. If end_date is not a trading day, the pipeline will end on the first trading day after end_date.
  • chunksize (int, optional) -- The number of days to execute at a time. Using smaller chunks will result in less memory usage, but may also take longer, particularly for pipelines that compute factors with long lookback windows. Default is 525.
  • show_progress (bool, optional) -- If True, display a progress bar during execution. Default is True.
Returns:

result -- A frame of computed results.

The result columns correspond to the entries of pipeline.columns, which should be a dictionary mapping strings to instances of zipline.pipeline.term.Term.

For each date between start_date and end_date, result will contain a row for each asset that passed pipeline.screen. A screen of None indicates that a row should be returned for each asset that existed each day.

Return type:

pd.DataFrame

Algorithm Results

quantopian.research.get_backtest(backtest_id)

Get the results of a backtest that was run on Quantopian.

Parameters:backtest_id (str) -- The id of the backtest for which results should be returned.
Returns:result -- An object containing all the information stored by Quantopian about the performance of a given backtest run, as well as some additional metadata.
Return type:AlgorithmResult

Notes

You can find the ID of a backtest in the URL of its full results page, which will be of the form:

https://www.quantopian.com/algorithms/<algorithm_id>/<backtest_id>

Once you have your AlgorithmResult object, you can call create_full_tear_sheet() on it to get an in-depth analysis of your backtest:

bt = get_backtest('<backtest_id>')
bt.create_full_tear_sheet()

See also

AlgorithmResult

class quantopian.research.AlgorithmResult

A container of information describing a backtest's performance.

Instances of this class are returned by quantopian.research.get_backtest().

create_full_tear_sheet(benchmark_rets=None, slippage=None, live_start_date=None, bayesian=False, round_trips=False, estimate_intraday='infer', hide_positions=False, cone_std=(1.0, 1.5, 2.0), bootstrap=False, header_rows=None)

Generate a number of tear sheets that are useful for analyzing a strategy's performance.

Creates tear sheets for returns, significant events, positions, transactions, and Bayesian analysis.

Parameters:
  • benchmark_rets (pd.Series or pd.DataFrame, optional) -- Daily noncumulative returns of the benchmark. This is in the same style as returns.
  • slippage (int/float, optional) -- Basis points of slippage to apply to returns before generating tearsheet stats and plots. If a value is provided, slippage parameter sweep plots will be generated from the unadjusted returns. See pyfolio.txn.adjust_returns_for_slippage for more details.
  • live_start_date (datetime, optional) -- The point in time when the strategy began live trading, after its backtest period.
  • bayesian (bool, optional) -- If True, causes the generation of a Bayesian tear sheet.
  • round_trips (bool, optional) -- If True, causes the generation of a round trip tear sheet.
  • estimate_intraday (bool or str, optional) -- Instead of using the end-of-day positions, use the point in the day where we have the most $ invested. This will adjust positions to better approximate and represent how an intraday strategy behaves. By default, this is 'infer', and an attempt will be made to detect an intraday strategy. Specifying this value will prevent detection.
  • hide_positions (bool, optional) -- If True, will not output any symbol names.
  • cone_std (float, or tuple, optional) -- If float, the standard deviation to use for the cone plots. If tuple, tuple of stdev values to use for the cone plots. The cone is a normal distribution with this standard deviation centered around a linear regression.
  • bootstrap (bool, optional) -- Whether to perform bootstrap analysis for the performance metrics. Takes a few minutes longer.
  • header_rows (dict or OrderedDict, optional) -- Extra rows to display at the top of the perf stats table.
create_perf_attrib_tear_sheet(self, return_fig=False)

Generate plots and tables for analyzing a strategy's performance.

Parameters:return_fig (bool, optional) -- If True, returns the figure that was plotted on.
create_position_tear_sheet(hide_positions=False, estimate_intraday='infer', return_fig=False)

Generate a number of plots for analyzing a strategy's positions and holdings.

  • Plots: gross leverage, exposures, top positions, and holdings.
  • Will also print the top positions held.
Parameters:
  • hide_positions (bool, optional) -- If True, will not output any symbol names. Overrides show_and_plot_top_pos to 0 to suppress text output.
  • estimate_intraday (bool or str, optional) -- Approximate returns for intraday strategies. See description in create_full_tear_sheet.
  • return_fig (bool, optional) -- If True, returns the figure that was plotted on.
create_returns_tear_sheet(live_start_date=None, cone_std=(1.0, 1.5, 2.0), benchmark_rets=None, bootstrap=False, header_rows=None, return_fig=False)

Generate a number of plots for analyzing a strategy's returns.

  • Fetches benchmarks, then creates the plots on a single figure.
  • Plots: rolling returns (with cone), rolling beta, rolling sharpe, rolling Fama-French risk factors, drawdowns, underwater plot, monthly and annual return plots, daily similarity plots, and return quantile box plot.
  • Will also print the start and end dates of the strategy, performance statistics, drawdown periods, and the return range.
Parameters:
  • live_start_date (datetime, optional) -- The point in time when the strategy began live trading, after its backtest period.
  • cone_std (float, or tuple, optional) -- If float, The standard deviation to use for the cone plots. If tuple, Tuple of stdev values to use for the cone plots The cone is a normal distribution with this standard deviation centered around a linear regression.
  • benchmark_rets (pd.Series, optional) -- Daily noncumulative returns of the benchmark. This is in the same style as returns.
  • bootstrap (bool, optional) -- Whether to perform bootstrap analysis for the performance metrics. Takes a few minutes longer.
  • header_rows (dict or OrderedDict, optional) -- Extra rows to display at the top of the perf stats table.
  • return_fig (bool, optional) -- If True, returns the figure that was plotted on.
create_simple_tear_sheet(benchmark_rets=None, slippage=None, live_start_date=None, estimate_intraday='infer', header_rows=None)

Simpler version of create_full_tear_sheet; generates summary performance statistics and important plots as a single image.

Parameters:
  • benchmark_rets (pd.Series or pd.DataFrame, optional) -- Daily noncumulative returns of the benchmark. This is in the same style as returns.
  • slippage (int/float, optional) -- Basis points of slippage to apply to returns before generating tearsheet stats and plots. If a value is provided, slippage parameter sweep plots will be generated from the unadjusted returns. See pyfolio.txn.adjust_returns_for_slippage for more details.
  • live_start_date (datetime, optional) -- The point in time when the strategy began live trading, after its backtest period.
  • estimate_intraday (bool or str, optional) -- Instead of using the end-of-day positions, use the point in the day where we have the most $ invested. This will adjust positions to better approximate and represent how an intraday strategy behaves. By default, this is 'infer', and an attempt will be made to detect an intraday strategy. Specifying this value will prevent detection.
  • header_rows (dict or OrderedDict, optional) -- Extra rows to display at the top of the perf stats table.
preview(attr, length=3, transpose=True)

Return a preview of the first length bars of the timeseries stored in getattr(self, attr).

If transpose == True (the default), then the result is transposed before being returned.

See also

frames

algo_id

Return the algorithm's ID

attributed_factor_returns

Return a daily datetime-indexed DataFrame containing the algorithm's returns broken down by style and sector risk factors. Also includes columns for common returns (sum of returns from known factors), specific returns (alpha), and total returns.

Each row of the returned frame contains the following columns:

  • basic_materials
  • consumer_cyclical
  • financial_services
  • real_estate
  • consumer_defensive
  • health_care
  • utilities
  • communication_services
  • energy
  • industrials
  • technology
  • momentum
  • size
  • value
  • short_term_reversal
  • volatility
  • common_returns
  • specific_returns
  • total_returns

Example output:

            basic_materials  ...  volatility  common_returns  specific_returns    total_returns
dt
2017-01-09   0.000000             -0.000091   -0.000127        0.000437           -0.000869
2017-01-10   0.000034              0.000422    0.000076        0.000663            0.000426
2017-01-11   0.000373              0.000192    0.000089        0.000261            0.000689
2017-01-12  -0.000093             -0.000039   -0.000139       -0.000244           -0.000462
2017-01-13  -0.000085              0.000284    0.000095        0.000059            0.000689
attrs

List of names of attributes of this object.

See also

scalars, frames

benchmark_security

Return the security used as a benchmark for this algorithm.

capital_base

Return the capital base for this algorithm.

cumulative_performance

Return a DataFrame with a daily DatetimeIndex containing cumulative performance metrics for the algorithm.

Each row of the returned frame contains the following columns:

  • capital_used
  • starting_cash
  • ending_cash
  • starting_position_value
  • ending_position_value
  • pnl
  • portfolio_value
  • returns
daily_performance

Return a DataFrame with a daily DatetimeIndex containing cumulative performance metrics for the algorithm

Each row of the returned frame contains the following columns:

  • capital_used
  • starting_cash
  • ending_cash
  • starting_position_value
  • ending_position_value
  • pnl
  • portfolio_value
  • returns
end_date

Return the end date for this algorithm.

factor_exposures

Return a daily datetime-indexed DataFrame containing the algorithm's exposures to style and sector risk factors.

Factor exposures are calculated by taking the algorithm's (dates x assets) matrix of portfolio weights each day and multiplying by the (assets x factors) loadings matrix produced by the Quantopian Risk Model. The result is a (dates x factors) matrix representing the factor-weighted sum of the algorithms holdings for each factor on each day.

Each row of the returned frame contains the following columns:

  • basic_materials
  • consumer_cyclical
  • financial_services
  • real_estate
  • consumer_defensive
  • health_care
  • utilities
  • communication_services
  • energy
  • industrials
  • technology
  • momentum
  • size
  • value
  • short_term_reversal
  • volatility

Example output:

             basic_materials  consumer_cyclical  ...  technology  momentum  ...  volatility
dt
2017-01-09   0.0              0.0                     0.788057    0.175617       -0.208708
2017-01-10   0.0              0.0                     1.180821    0.274301       -0.314133
2017-01-11   0.0              0.0                     0.654444    0.190959       -0.173934
2017-01-12   0.0              0.0                     0.768404    0.181316       -0.207495
2017-01-13   0.0              0.0                     1.522823    0.325506       -0.382107
frames

List of names of pd.DataFrame attributes on this object.

See also

preview(), scalars, attrs

launch_date

The real-world datetime at which this backtest started running.

orders

Return a DataFrame representing a record of all orders made by the algorithm.

Each row of the returned frame contains the following columns:

  • amount
  • commission
  • created_date
  • last_updated
  • filled
  • id
  • sid
  • status
  • limit
  • limit_reached
  • stop
  • stop_reached
positions

Return a datetime-indexed DataFrame representing a point-in-time record of positions held by the algorithm during the backtest.

Each row of the returned frame contains the following columns:

  • amount
  • last_sale_price
  • cost_basis
  • sid
pyfolio_positions

Return a DataFrame containing positions formatted for pyfolio.

pyfolio_transactions

Return a DataFrame containing transactions formatted for pyfolio.

recorded_vars

Return a DataFrame containing the recorded variables for the algorithm.

risk

Return a DataFrame with a daily DatetimeIndex representing rolling risk metrics for the algorithm.

Each row of the returned frame contains the following columns:

  • volatility
  • period_return
  • alpha
  • benchmark_period_return
  • benchmark_volatility
  • beta
  • excess_return
  • max_drawdown
  • period_label
  • sharpe
  • sortino
  • trading_days
  • treasury_period_return
scalars

List of names of non-DataFrame attributes of this object.

See also

attrs, frames

start_date

Return the start date for this algorithm.

transactions

Return a DataFrame representing a record of transactions that occurred during the life of the algorithm. The returned frame is indexed by the date at which the transaction occurred.

Each row of the returned frame contains the following columns:

  • amount
  • commission
  • date
  • order_id
  • price
  • sid

Price and Volume Data

quantopian.research.symbols(symbols, symbol_reference_date=None, handle_missing='log')

Convert a string or a list of strings into Asset objects.

Parameters:
  • symbols (String or iterable of strings.) -- Passed strings are interpreted as ticker symbols and resolved relative to the date specified by symbol_reference_date.
  • symbol_reference_date (str or pd.Timestamp, optional) -- String or Timestamp representing a date used to resolve symbols that have been held by multiple companies. Defaults to the current time.
  • handle_missing ({'raise', 'log', 'ignore'}, optional) -- String specifying how to handle unmatched securities. Defaults to 'log'.
Returns:

The symbols that were requested.

Return type:

list of Asset objects

quantopian.research.prices(assets, start, end, frequency='daily', price_field='price', symbol_reference_date=None, start_offset=0)

Get close price data for assets between start and end.

Parameters:
  • assets (int/str/Asset or iterable of same) -- Identifiers for assets to load. Integers are interpreted as sids. Strings are interpreted as symbols.
  • start (str or pd.Timestamp) -- Start date of data to load.
  • end (str or pd.Timestamp) -- End date of data to load.
  • frequency ({'minute', 'daily'}, optional) -- Frequency at which to load data. Default is 'daily'.
  • price_field ({'open', 'high', 'low', 'close', 'price'}, optional) -- Price field to load. 'price' produces the same data as 'close', but forward-fills over missing data. Default is 'price'.
  • symbol_reference_date (pd.Timestamp, optional) -- Date as of which to resolve strings as tickers. Default is the current day.
  • start_offset (int, optional) -- Number of periods before start to fetch. Default is 0. This is most often useful for calculating returns.
Returns:

prices -- Pandas object containing prices for the requested asset(s) and dates.

Data is returned as a pd.Series if a single asset is passed.

Data is returned as a pd.DataFrame if multiple assets are passed.

Return type:

pd.Series or pd.DataFrame

quantopian.research.returns(assets, start, end, periods=1, frequency='daily', price_field='price', symbol_reference_date=None)

Fetch returns for one or more assets in a date range.

Parameters:
  • assets (int/str/Asset or iterable of same) -- Identifiers for assets to load. Integers are interpreted as sids. Strings are interpreted as symbols.
  • start (str or pd.Timestamp) -- Start date of data to load.
  • end (str or pd.Timestamp) -- End date of data to load.
  • periods (int, optional) -- Number of periods over which to calculate returns. Default is 1.
  • frequency ({'minute', 'daily'}, optional) -- Frequency at which to load data. Default is 'daily'.
  • price_field ({'open', 'high', 'low', 'close', 'price'}, optional) -- Price field to load. 'price' produces the same data as 'close', but forward-fills over missing data. Default is 'price'.
  • symbol_reference_date (pd.Timestamp, optional) -- Date as of which to resolve strings as tickers. Default is the current day.
Returns:

returns -- Pandas object containing returns for the requested asset(s) and dates.

Data is returned as a pd.Series if a single asset is passed.

Data is returned as a pd.DataFrame if multiple assets are passed.

Return type:

pd.Series or pd.DataFrame

quantopian.research.volumes(assets, start, end, frequency='daily', symbol_reference_date=None, start_offset=0)

Get trading volume for assets between start and end.

Parameters:
  • assets (int/str/Asset or iterable of same) -- Identifiers for assets to load. Integers are interpreted as sids. Strings are interpreted as symbols.
  • start (str or pd.Timestamp) -- Start date of data to load.
  • end (str or pd.Timestamp) -- End date of data to load.
  • frequency ({'minute', 'daily'}, optional) -- Frequency at which to load data. Default is 'daily'.
  • symbol_reference_date (pd.Timestamp, optional) -- Date as of which to resolve strings as tickers. Default is the current day.
  • start_offset (int, optional) -- Number of periods before start to fetch. Default is 0. This is most often useful for calculating returns.
Returns:

volumes -- Pandas object containing volumes for the requested asset(s) and dates.

Data is returned as a pd.Series if a single asset is passed.

Data is returned as a pd.DataFrame if multiple assets are passed.

Return type:

pd.Series or pd.DataFrame

quantopian.research.log_prices(assets, start, end, frequency='daily', price_field='price', symbol_reference_date=None, start_offset=0)

Fetch logarithmic-prices for one or more assets in a date range.

Parameters:
  • assets (int/str/Asset or iterable of same) -- Identifiers for assets to load. Integers are interpreted as sids. Strings are interpreted as symbols.
  • start (str or pd.Timestamp) -- Start date of data to load.
  • end (str or pd.Timestamp) -- End date of data to load.
  • frequency ({'minute', 'daily'}, optional) -- Frequency at which to load data. Default is 'daily'.
  • price_field ({'open', 'high', 'low', 'close', 'price'}, optional) -- Price field to load. 'price' produces the same data as 'close', but forward-fills over missing data. Default is 'price'.
  • symbol_reference_date (pd.Timestamp, optional) -- Date as of which to resolve strings as tickers. Default is the current day.
  • start_offset (int, optional) -- Number of periods before start to fetch. Default is 0. This is most often useful for calculating returns.
Returns:

prices -- Pandas object containing log-prices for the requested asset(s) and dates.

Data is returned as a pd.Series if a single asset is passed.

Data is returned as a pd.DataFrame if multiple assets are passed.

Return type:

pd.Series or pd.DataFrame

quantopian.research.log_returns(assets, start, end, periods=1, frequency='daily', price_field='price', symbol_reference_date=None)

Fetch logarithmic-returns for one or more assets in a date range.

Parameters:
  • assets (int/str/Asset or iterable of same) -- Identifiers for assets to load. Integers are interpreted as sids. Strings are interpreted as symbols.
  • start (str or pd.Timestamp) -- Start date of data to load.
  • end (str or pd.Timestamp) -- End date of data to load.
  • periods (int, optional) -- Number of periods over which to calculate returns. Default is 1.
  • frequency ({'minute', 'daily'}, optional) -- Frequency at which to load data. Default is 'daily'.
  • price_field ({'open', 'high', 'low', 'close', 'price'}, optional) -- Price field to load. 'price' produces the same data as 'close', but forward-fills over missing data. Default is 'price'.
  • symbol_reference_date (pd.Timestamp, optional) -- Date as of which to resolve strings as tickers. Default is the current day.
Returns:

returns -- Pandas object containing logarithmic-returns for the requested asset(s) and dates.

Data is returned as a pd.Series if a single asset is passed.

Data is returned as a pd.DataFrame if multiple assets are passed.

Return type:

pd.Series or pd.DataFrame

quantopian.research.get_pricing(symbols, start_date='2013-01-03', end_date='2014-01-03', symbol_reference_date=None, frequency='daily', fields=None, handle_missing='raise', start_offset=0)

Load a table of historical trade data.

Parameters:
  • symbols (Object (or iterable of objects) convertible to Asset) -- Valid input types are Asset, Integral, or basestring. In the case that the passed objects are strings, they are interpreted as ticker symbols and resolved relative to the date specified by symbol_reference_date.
  • start_date (str or pd.Timestamp, optional) -- String or Timestamp representing a start date or start intraday minute for the returned data. Defaults to '2013-01-03'.
  • end_date (str or pd.Timestamp, optional) -- String or Timestamp representing an end date or end intraday minute for the returned data. Defaults to '2014-01-03'.
  • symbol_reference_date (str or pd.Timestamp, optional) -- String or Timestamp representing a date used to resolve symbols that have been held by multiple companies. Defaults to the current time.
  • frequency ({'daily', 'minute'}, optional) -- Resolution of the data to be returned.
  • fields (str or list, optional) -- String or list drawn from {'price', 'open_price', 'high', 'low', 'close_price', 'volume'}. Default behavior is to return all fields.
  • handle_missing ({'raise', 'log', 'ignore'}, optional) -- String specifying how to handle unmatched securities. Defaults to 'raise'.
  • start_offset (int, optional) -- Number of periods before start to fetch. Default is 0.
Returns:

The pricing data that was requested. See note below.

Return type:

pandas Panel/DataFrame/Series

Notes

If a list of symbols is provided, data is returned in the form of a pandas Panel object with the following indices:

items = fields
major_axis = TimeSeries (start_date -> end_date)
minor_axis = symbols

If a string is passed for the value of symbols and fields is None or a list of strings, data is returned as a DataFrame with a DatetimeIndex and columns given by the passed fields.

If a list of symbols is provided, and fields is a string, data is returned as a DataFrame with a DatetimeIndex and a columns given by the passed symbols.

If both parameters are passed as strings, data is returned as a Series.

Experimental APIs

Price and Volume Data (Experimental)

quantopian.research.experimental.history(symbols, fields, start, end, frequency, symbol_reference_date=None, handle_missing='raise', start_offset=0)

Load a table of historical trade data.

Parameters:
  • symbols (Asset-convertible object, ContinuousFuture, or iterable of same.) -- Valid input types are Asset, Integral, basestring, or ContinuousFuture. In the case that the passed objects are strings, they are interpreted as ticker symbols and resolved relative to the date specified by symbol_reference_date.
  • fields (str or list) -- String or list drawn from {'price', 'open_price', 'high', 'low', 'close_price', 'volume', 'contract'}.
  • start (str or pd.Timestamp) -- String or Timestamp representing a start date or start intraday minute for the returned data.
  • end (str or pd.Timestamp) -- String or Timestamp representing an end date or end intraday minute for the returned data.
  • frequency ({'daily', 'minute'}) -- Resolution of the data to be returned.
  • symbol_reference_date (str or pd.Timestamp, optional) -- String or Timestamp representing a date used to resolve symbols that have been held by multiple companies. Defaults to the current time.
  • handle_missing ({'raise', 'log', 'ignore'}, optional) -- String specifying how to handle unmatched securities. Defaults to 'raise'.
  • start_offset (int, optional) -- Number of periods before start to fetch. Default is 0. This is most often useful when computing returns.
Returns:

The pricing data that was requested. See note below.

Return type:

pandas Panel/DataFrame/Series

Notes

If a list of symbols is provided, data is returned in the form of a pandas Panel object with the following indices:

items = fields
major_axis = TimeSeries (start_date -> end_date)
minor_axis = symbols

If a string is passed for the value of symbols and fields is None or a list of strings, data is returned as a DataFrame with a DatetimeIndex and columns given by the passed fields.

If a list of symbols is provided, and fields is a string, data is returned as a DataFrame with a DatetimeIndex and a columns given by the passed symbols.

If both parameters are passed as strings, data is returned as a Series.

Risk Model (Experimental)

quantopian.research.experimental.get_factor_loadings(assets, start, end, handle_missing='log')

Retrieve Quantopian Risk Model loadings for a given period.

Parameters:
  • assets (int/str/Asset or iterable of same) -- Identifiers for assets to load. Integers are interpreted as sids. Strings are interpreted as symbols.
  • start (str or pd.Timestamp) -- Start date of data to load.
  • end (str or pd.Timestamp) -- End date of data to load.
  • handle_missing ({'raise', 'log', 'ignore'}, optional) -- String specifying how to handle unmatched securities. Defaults to 'log'.
quantopian.research.experimental.get_factor_returns(start, end)

Retrieve Quantopian Risk Model factor returns for a given period.

Parameters:
  • start (str or pd.Timestamp) -- Start date of data to load.
  • end (str or pd.Timestamp) -- End date of data to load.
Returns:

factor_returns -- A DataFrame containing returns for each factor calculated by the Quantopian Risk Model.

Return type:

pandas.DataFrame

Futures (Experimental)

quantopian.research.experimental.continuous_future(root_symbol, offset=0, roll='volume', adjustment='mul')

Create a specifier for a continuous contract.

Parameters:
  • root_symbol (str) -- The root symbol for the continuous future.
  • offset (int, optional) -- The distance from the primary contract. Default is 0.
  • roll (str, optional) -- How rolls are determined. Options are 'volume' and 'calendar'. Default is 'volume'.
  • adjustment (str) -- Method for adjusting lookback prices between rolls. Options are 'mul', 'add', and None. Default is 'mul'.
Returns:

continuous_future -- The continuous future specifier.

Return type:

ContinuousFuture