API Reference

Running a Strategy

catalyst.run_algorithm(...)[source]

Run a trading algorithm.

Parameters:
capital_base : float

The starting capital for the backtest.

start : datetime

The start date of the backtest.

end : datetime

The end date of the backtest..

initialize : callable[context -> None]

The initialize function to use for the algorithm. This is called once at the very beginning of the run and should be used to set up any state needed by the algorithm.

handle_data : callable[(context, BarData) -> None], optional

The handle_data function to use for the algorithm. This is called every minute when data_frequency == 'minute' or every day when data_frequency == 'daily'.

before_trading_start : callable[(context, BarData) -> None], optional

The before_trading_start function for the algorithm. This is called once before each trading day (after initialize on the first day).

analyze : callable[(context, pd.DataFrame) -> None], optional

The analyze function to use for the algorithm. This function is called once at the end of the backtest/live run and is passed the context and the performance data.

data_frequency : {‘daily’, ‘minute’}, optional

The data frequency to run the algorithm at. At backtest both modes are supported, at live mode only the minute mode is supported.

data : pd.DataFrame, pd.Panel, or DataPortal, optional

The ohlcv data to run the backtest with. This argument is mutually exclusive with: bundle bundle_timestamp

bundle : str, optional

The name of the data bundle to use to load the data to run the backtest with. This argument is mutually exclusive with data.

bundle_timestamp : datetime, optional

The datetime to lookup the bundle data for. This defaults to the current time. This argument is mutually exclusive with data.

default_extension : bool, optional

Should the default catalyst extension be loaded. This is found at $CATALYST_ROOT/extension.py

extensions : iterable[str], optional

The names of any other extensions to load. Each element may either be a dotted module path like a.b.c or a path to a python file ending in .py like a/b/c.py.

strict_extensions : bool, optional

Should the run fail if any extensions fail to load. If this is false, a warning will be raised instead.

environ : mapping[str -> str], optional

The os environment to use. Many extensions use this to get parameters. This defaults to os.environ.

live : bool, optional

Should the algorithm be executed in live trading mode.

remote : bool, optional

Should the algorithm run on a remote server. currently, available only on backtest mode.

mail : str, optional- if running with remote=True then, mandatory.

to which email address shall the server send the results to.

exchange_name: str

The name of the exchange to be used in the backtest/live run.

quote_currency: str

The base currency to be used in the backtest/live run.

algo_namespace: str

The namespace of the algorithm.

live_graph: bool, optional

Should the live graph clock be used instead of the regular clock.

analyze_live: callable[(context, pd.DataFrame) -> None], optional

The interactive analyze function to be used with the live graph clock in every tick.

simulate_orders: bool, optional

Should paper trading mode be applied.

auth_aliases: str, optional

Rewrite the auth file name. It should contain an even list of comma-delimited values. For example: “binance,auth2,bittrex,auth2”

stats_output: str, optional

The URI of the S3 bucket to which to upload the performance stats.

output: str, optional

The output file path to which the algorithm performance is serialized.

Returns:
perf : pd.DataFrame

The daily performance of the algorithm.

Algorithm API

The following methods are available for use in the initialize, handle_data, and before_trading_start API functions.

In all listed functions, the self argument is implicitly the currently-executing TradingAlgorithm instance.

Data Object

class catalyst.protocol.BarData

Provides methods to access spot value or history windows of price data. Also provides some utility methods to determine if an asset is alive, has recent trade data, etc.

This is what is passed as data to the handle_data function.

Parameters:
data_portal : DataPortal

Provider for bar pricing data.

simulation_dt_func : callable

Function which returns the current simulation time. This is usually bound to a method of TradingSimulation.

data_frequency : {‘minute’, ‘daily’}

The frequency of the bar data; i.e. whether the data is daily or minute bars

restrictions : catalyst.finance.asset_restrictions.Restrictions

Object that combines and returns restricted list information from multiple sources

universe_func : callable, optional

Function which returns the current ‘universe’. This is for backwards compatibility with older API concepts.

can_trade()

For the given asset or iterable of assets, returns true if all of the following are true: 1) the asset is alive for the session of the current simulation time (if current simulation time is not a market minute, we use the next session) 2) there is a known last price for the asset.

Parameters:
assets: Asset or iterable of assets
Returns:
can_trade : bool or pd.Series[bool] indexed by asset.
current()

Returns the current value of the given assets for the given fields at the current simulation time.

Parameters:
assets : Asset or iterable of Assets
fields : str or iterable[str].

Valid values are: “price”, “last_traded”, “open”, “high”, “low”, “close”, “volume”, or column names in files read by fetch_csv.

Returns:
current_value : Scalar, pandas Series, or pandas DataFrame.

See notes below.

Notes

If a single asset and a single field are passed in, a scalar float value is returned.

If a single asset and a list of fields are passed in, a pandas Series is returned whose indices are the fields, and whose values are scalar values for this asset for each field.

If a list of assets and a single field are passed in, a pandas Series is returned whose indices are the assets, and whose values are scalar values for each asset for the given field.

If a list of assets and a list of fields are passed in, a pandas DataFrame is returned, indexed by asset. The columns are the requested fields, filled with the scalar values for each asset for each field.

If the current simulation time is not a valid market time, we use the last market close instead.

“price” returns the last known close price of the asset. If there is no last known value (either because the asset has never traded, or because it has delisted) NaN is returned.

“last_traded” returns the date of the last trade event of the asset, even if the asset has stopped trading. If there is no last known value, pd.NaT is returned.

In backtest mode, “volume” returns the trade volume for the current simulation time. If there is no trade this minute, 0 is returned.

“open”, “high”, “low”, and “close” return the relevant information for the current trade bar. If there is no current trade bar, NaN is returned.

In live mode, “volume”, “close” and “price” are the only available fields.

In live mode, “volume” returns the last 24 hour trading volume.

history()

Returns a window of data for the given assets and fields.

The label of each candle is left-bound. This means that for example, in case of 5 minute candles, the candle of 00:00:00 will hold the data between 00:00:00 and 00:04:59.

In minute mode, both in live and backtest, the last candle will almost always be a partial one. For example, if the current time is 00:02:00 then the last 5 minute candle with 00:00:00 timestamp will hold data between 00:00:00 and 00:01:59.

The semantics of missing data are identical to the ones described in the notes for get_spot_value.

Parameters:
assets: Asset or iterable of Asset
fields: string or iterable of string. Valid values are “open”, “high”,

“low”, “close”, “volume”, “price”, and “last_traded”.

bar_count: integer number of bars of trade data
frequency: string. “T” for minutely data, “D” for daily date,

“H” for hourly data

Returns:
history : Series or DataFrame or Panel

Return type depends on the dimensionality of the ‘assets’ and ‘fields’ parameters.

If single asset and field are passed in, the returned Series is indexed by dt.

If multiple assets and single field are passed in, the returned DataFrame is indexed by dt, and has assets as columns.

If a single asset and multiple fields are passed in, the returned DataFrame is indexed by dt, and has fields as columns.

If multiple assets and multiple fields are passed in, the returned Panel is indexed by field, has dt as the major axis, and assets as the minor axis.

is_stale()

For the given asset or iterable of assets, returns true if the asset is alive and there is no trade data for the current simulation time.

If the asset has never traded, returns False.

If the current simulation time is not a valid market time, we use the current time to check if the asset is alive, but we use the last market minute/day for the trade data check.

Parameters:
assets: Asset or iterable of assets
Returns:
boolean or Series of booleans, indexed by asset.

Scheduling Functions

catalyst.api.schedule_function(self, func, date_rule=None, time_rule=None, half_days=True, calendar=None)

Schedules a function to be called according to some timed rules.

Parameters:
func : callable[(context, data) -> None]

The function to execute when the rule is triggered.

date_rule : EventRule, optional

The rule for the dates to execute this function.

time_rule : EventRule, optional

The rule for the times to execute this function.

half_days : bool, optional

Should this rule fire on half days?

calendar : Sentinel, optional

Calendar used to reconcile date and time rules.

class catalyst.api.date_rules[source]
every_day

alias of Always

static month_end(days_offset=0)[source]
static month_start(days_offset=0)[source]
static week_end(days_offset=0)[source]
static week_start(days_offset=0)[source]
class catalyst.api.time_rules[source]
every_minute

alias of Always

market_close

alias of BeforeClose

market_open

alias of AfterOpen

Orders

catalyst.api.order(self, asset, amount, limit_price=None, stop_price=None, style=None)

Place an order.

Parameters:
asset : Asset

The asset/TradingPair that this order is for.

amount : int

The amount of currency to order. If amount is positive, this is the number of base_currency (the first asset in the pair) to buy. If amount is negative, this is the number of base_currency to sell (buy quote_currency).

limit_price : float, optional

The limit price for the order.

stop_price : float, optional

Not supported.

style : ExecutionStyle, optional

The execution style for the order.

Returns:
order_id : str or None

The unique identifier for this order, or None if no order was placed.

Notes

The limit_price argument provide shorthands for passing common execution styles. Passing limit_price=N is equivalent to style=LimitOrder(N). It is an error to pass both a style and limit_price.

Currently, orders must be done only with one quote_currency throughout all the algorithm.

catalyst.api.order_value(self, asset, value, limit_price=None, stop_price=None, style=None)

Place an order by quote_currency value rather than desired number of base_currency wanted.

Parameters:
asset : TradingPair

The TradingPair that this order is for.

value : float

If the requested tradingPair exists, the requested value is divided by its price to imply the number of currency to transact.

value > 0 :: Buy/Cover value < 0 :: Sell

limit_price : float, optional

The limit price for the order.

stop_price : float, optional

Not supported.

style : ExecutionStyle

The execution style for the order.

Returns:
order_id : str

The unique identifier for this order.

Notes

See catalyst.api.order() for more information about limit_price, and style

catalyst.api.order_percent(self, asset, percent, limit_price=None, stop_price=None, style=None)

Place an order in the specified tradingPair corresponding to the given percent of the current portfolio value.

Parameters:
asset : TradingPair

The tradingPair that this order is for.

percent : float

The percentage of the portfolio value to allocate to asset. This is specified as a decimal, for example: 0.50 means 50%.

limit_price : float, optional

The limit price for the order.

stop_price : float, optional

Not supported.

style : ExecutionStyle

The execution style for the order.

Returns:
order_id : str

The unique identifier for this order.

Notes

See catalyst.api.order() for more information about limit_price, and style

catalyst.api.order_target(self, asset, target, limit_price=None, stop_price=None, style=None)

Place an order to adjust a position to a target number of currency. If the position doesn’t already exist, this is equivalent to placing a new order. If the position does exist, this is equivalent to placing an order for the difference between the target number of shares and the current number of shares.

Parameters:
asset : TradingPair

The TradingPair that this order is for.

target : int

The desired number of TradingPair.

limit_price : float, optional

The limit price for the order.

stop_price : float, optional

Not supported.

style : ExecutionStyle

The execution style for the order.

Returns:
order_id : str

The unique identifier for this order.

Notes

order_target takes into account open orders as well.

See catalyst.api.order() for more information about limit_price, and style

catalyst.api.order_target_value(self, asset, target, limit_price=None, stop_price=None, style=None)

Place an order to adjust a position to a target value. If the position doesn’t already exist, this is equivalent to placing a new order. If the position does exist, this is equivalent to placing an order for the difference between the target value and the current value.

Parameters:
asset : TradingPair

The TradingPair that this order is for.

target : float

The desired total value of TradingPair.

limit_price : float, optional

The limit price for the order.

stop_price : float, optional

Not supported.

style : ExecutionStyle

The execution style for the order.

Returns:
order_id : str

The unique identifier for this order.

Notes

See catalyst.api.order() for more information about limit_price and style

catalyst.api.order_target_percent(self, asset, target, limit_price=None, stop_price=None, style=None)

Place an order to adjust a position to a target percent of the current portfolio value. If the position doesn’t already exist, this is equivalent to placing a new order. If the position does exist, this is equivalent to placing an order for the difference between the target percent and the current percent.

Parameters:
asset : TradingPair

The TradingPair that this order is for.

target : float

The desired percentage of the portfolio value to allocate to TradingPair. This is specified as a decimal, for example: 0.50 means 50%.

limit_price : float, optional

The limit price for the order.

stop_price : float, optional

Not supported

style : ExecutionStyle

The execution style for the order.

Returns:
order_id : str

The unique identifier for this order.

Notes

See catalyst.api.order() for more information about limit_price and style

class catalyst.finance.execution.ExecutionStyle[source]

Abstract base class representing a modification to a standard order.

class catalyst.finance.execution.MarketOrder(exchange=None)[source]

Class encapsulating an order to be placed at the current market price.

class catalyst.finance.execution.LimitOrder(limit_price, exchange=None)[source]

Execution style representing an order to be executed at a price equal to or better than a specified limit price.

catalyst.api.get_order(self, order_id, asset_or_symbol=None, return_price=False, params={})

Lookup an order based on the order id returned from one of the order functions.

Parameters:
order_id : str

The unique identifier for the order.

asset_or_symbol: Asset or str

The asset or the tradingPair symbol of the order.

return_price: bool

get the trading price in addition to the order

params: dict, optional

Extra parameters to pass to the exchange

Returns:
order : Order

The order object.

execution_price: float

The execution price per unit of the order if return_price is True

catalyst.api.get_open_orders(self, asset=None)

Retrieve all of the current open orders.

Parameters:
asset : Asset

If passed and not None, return only the open orders for the given asset instead of all open orders.

Returns:
open_orders : dict[list[Order]] or list[Order]

If no asset is passed this will return a dict mapping Assets to a list containing all the open orders for the asset. If an asset is passed then this will return a list of the open orders for this asset.

catalyst.api.cancel_order(self, order_param, symbol=None, params={})

Cancel an open order.

Parameters:
order_param : str or Order

The order_id or order object to cancel.

symbol: str

The tradingPair symbol

params: dict, optional

Extra parameters to pass to the exchange

catalyst.api.get_orderbook(self, asset, order_type='all', limit=None)

Retrieve the orderbook for the given trading pair. This function is supported only in live and paper trading modes.

Parameters:
asset: TradingPair
order_type: str

The type of the orders: ‘bids’ or ‘asks’ or ‘all’

limit: int
Returns:
list[dict[str, float]

Order Cancellation Policies

catalyst.api.set_cancel_policy(self, cancel_policy)

Sets the order cancellation policy for the simulation.

Parameters:
cancel_policy : CancelPolicy

The cancellation policy to use.

class catalyst.finance.cancel_policy.CancelPolicy[source]

Abstract cancellation policy interface.

should_cancel(event)[source]

Should all open orders be cancelled?

Parameters:
event : enum-value
An event type, one of:
  • catalyst.gens.sim_engine.BAR
  • catalyst.gens.sim_engine.DAY_START
  • catalyst.gens.sim_engine.DAY_END
  • catalyst.gens.sim_engine.MINUTE_END
Returns:
should_cancel : bool

Should all open orders be cancelled?

catalyst.api.EODCancel(warn_on_cancel=True)[source]

This policy cancels open orders at the end of the day. For now, Catalyst will only apply this policy to minutely simulations.

Parameters:
warn_on_cancel : bool, optional

Should a warning be raised if this causes an order to be cancelled?

catalyst.api.NeverCancel()[source]

Orders are never automatically canceled.

Assets

catalyst.api.symbol(self, symbol_str, exchange_name=None)

Lookup a Trading pair by its ticker symbol. Catalyst defines its own set of “universal” symbols to reference trading pairs across exchanges. This is required because exchanges are not adhering to a universal symbolism. For example, Bitfinex uses the BTC symbol for Bitcon while Kraken uses XBT. In addition, pairs are sometimes presented differently. For example, Bitfinex puts the market currency before the base currency without a separator, Bittrex puts the quote currency first and uses a dash seperator.

Here is the Catalyst convention: [Base Currency]_[Quote Currency] For example: btc_usd, eth_btc, neo_eth, ltc_eur.

The symbol for each currency (e.g. btc, eth, ltc) is generally aligned with the Bittrex exchange.

Parameters:
symbol_str : str

The ticker symbol for the TradingPair to lookup.

exchange_name: str

The name of the exchange containing the symbol

Returns:
tradingPair : TradingPair

The TradingPair that held the ticker symbol on the current symbol lookup date.

Raises:
SymbolNotFound

Raised when the symbols was not held on the current lookup date.

catalyst.api.symbols(self, *args)

Lookup multiple TradingPairs as a list. for example: symbols(‘eth_usd’,’btc_usd’)

Parameters:
*args : iterable[str]

The ticker symbols to lookup.

Returns:
tradingPairs : list[TradingPair]

The tradingPairs that held the given ticker symbols on the current symbol lookup date.

Raises:
SymbolNotFound

Raised when one of the symbols was not held on the current lookup date.

See also

catalyst.api.set_symbol_lookup_date()

catalyst.api.sid(self, sid)

Lookup a Trading Pair by its unique identifier.

Parameters:
sid : int

The unique integer that identifies an Trading Pair. for example: The unique sid for the ‘btc_usdt’ Trading Pair on poloniex is 374465. Therefore, running sid(374465) will give you the symbol of the Trading Pair

Returns:
TradingPair : TradingPair

The TradingPair with the given sid.

Raises:
SidsNotFound

When a requested sid does not map to any TradingPair.

Simulation Parameters

catalyst.api.set_benchmark(self, benchmark)

Set the benchmark asset.

Parameters:
benchmark : Asset

The asset to set as the new benchmark.

Notes

Any dividends payed out for that new benchmark asset will be automatically reinvested.

Commission Models

catalyst.api.set_commission(self, maker=None, taker=None)

Sets the maker and taker fees of the commission model for the simulation.

Parameters:
maker : float

The taker fee - taking from the order book.

taker : float

The maker fee - adding to the order book.

class catalyst.finance.commission.CommissionModel[source]

Abstract commission model interface.

Commission models are responsible for accepting order/transaction pairs and calculating how much commission should be charged to an algorithm’s account on each transaction.

calculate(order, transaction)[source]

Calculate the amount of commission to charge on order as a result of transaction.

Parameters:
order : catalyst.finance.order.Order

The order being processed.

The commission field of order is a float indicating the amount of commission already charged on this order.

transaction : catalyst.finance.transaction.Transaction

The transaction being processed. A single order may generate multiple transactions if there isn’t enough volume in a given bar to fill the full amount requested in the order.

Returns:
amount_charged : float

The additional commission, in dollars, that we should attribute to this order.

Slippage Models

catalyst.api.set_slippage(self, slippage=None)

Set the slippage of the fixed slippage model used by the simulation.

Parameters:
slippage : float

The slippage to be set.

class catalyst.finance.slippage.SlippageModel[source]

Abstract interface for defining a slippage model.

process_order(data, order)[source]

Process how orders get filled.

Parameters:
data : BarData

The data for the given bar.

order : Order

The order to simulate.

Returns:
execution_price : float

The price to execute the trade at.

execution_volume : int

The number of shares that could be filled. This may not be all the shares ordered in which case the order will be filled over multiple bars.

class catalyst.exchange.exchange_blotter.TradingPairFixedSlippage(slippage=0.0001)[source]

Model slippage as a fixed value.

Parameters:
slippage : float, optional

fixed slippage will be added to buys and subtracted from sells.

Pipeline

Not supported yet.

Miscellaneous

catalyst.api.record(self, *args, **kwargs)

Track and record values each day.

Parameters:
**kwargs

The names and values to record.

Notes

These values will appear in the performance packets and the performance dataframe passed to analyze and returned from run_algorithm().

catalyst.api.get_environment(self, field='platform')

Query the execution environment.

Parameters:
field : {‘platform’, ‘arena’, ‘data_frequency’,

‘start’, ‘end’, ‘capital_base’, ‘platform’, ‘*’}

The field to query. The options have the following meanings:
arena : str {‘backtest’, ‘live’}

The algorithm’s arena.

data_frequency : {‘daily’, ‘minute’}

data_frequency tells the algorithm if it is running with daily or minute mode.

start : datetime

The start date for the simulation.

end : datetime

The end date for the simulation.

capital_base : float

The starting capital for the simulation.

platform : str

The platform that the code is running on. By default this will be the string ‘catalyst’. This can allow algorithms to know if they are running on the Quantopian platform instead.

\* : dict[str -> any]

Returns all of the fields in a dictionary.

Returns:
val : any

The value for the field queried. See above for more information.

Raises:
ValueError

Raised when field is not a valid option.

Trading Calendar API

catalyst.utils.calendars.get_calendar(name)

Retrieves an instance of a TradingCalendar whose name is given.

Parameters:
name : str

The name of the TradingCalendar to be retrieved.

Returns:
calendar : catalyst.utils.calendars.TradingCalendar

The desired calendar.

class catalyst.utils.calendars.TradingCalendar(start=Timestamp('1990-01-01 00:00:00+0000', tz='UTC'), end=Timestamp('2019-11-11 16:51:46.749042+0000', tz='UTC'))[source]

A TradingCalendar represents the timing information of a single market exchange.

The timing information is made up of two parts: sessions, and opens/closes.

A session represents a contiguous set of minutes, and has a label that is midnight UTC. It is important to note that a session label should not be considered a specific point in time, and that midnight UTC is just being used for convenience.

For each session, we store the open and close time in UTC time.

catalyst.utils.calendars.register_calendar(name, calendar, force=False)

Registers a calendar for retrieval by the get_calendar method.

Parameters:
name: str

The key with which to register this calendar.

calendar: TradingCalendar

The calendar to be registered for retrieval.

force : bool, optional

If True, old calendars will be overwritten on a name collision. If False, name collisions will raise an exception. Default is False.

Raises:
CalendarNameCollision

If a calendar is already registered with the given calendar’s name.

catalyst.utils.calendars.register_calendar_type(name, calendar_type, force=False)

Registers a calendar by type.

This is useful for registering a new calendar to be lazily instantiated at some future point in time.

Parameters:
name: str

The key with which to register this calendar.

calendar_type: type

The type of the calendar to register.

force : bool, optional

If True, old calendars will be overwritten on a name collision. If False, name collisions will raise an exception. Default is False.

Raises:
CalendarNameCollision

If a calendar is already registered with the given calendar’s name.

catalyst.utils.calendars.deregister_calendar(name)

If a calendar is registered with the given name, it is de-registered.

Parameters:
cal_name : str

The name of the calendar to be deregistered.

catalyst.utils.calendars.clear_calendars()

Deregisters all current registered calendars