[PYTHON] Quantopian API Reference

About this article

About Quantopian's API reference, I will translate the part you care about into Japanese instead of a memo. The author is not good at English, so please understand the text.

Required method

The algorithm must implement two methods, ʻinitialize and handle_data. The third method is before_trading_start`, which is optional.

Initialization

initialize(context)

Called only once at the beginning of the backtest. The context object can be passed to all other methods in the algorithm.

context: An empty dictionary at the time of initialization. You can access the property in either dot or bracket notation.

Return value None

Response to market events

handle_data(context, data) Called every time a market event (bar update) occurs.

data: A dictionary keyed by securities ID (SID), including universe stocks. Represents a snapshot of the stock universe at the time this method was called.

Same as the one that appeared in context: initialize. Stores user-defined status and portfolio objects.

Return value None

Pre-processing for trading

before_trading_start(context, data) Called only once a day before the market opens. Its primary use is to query Quantopian's underlying database to investigate the financial data of individual companies. Using your company's basic data, you can set the stock universe to use in your algorithm based on over 600 measurable criteria.

Same as the one that appeared in context: initialize. Stores user-defined status and portfolio objects.

Return value None

Other methods

There are several ordering methods available in the algorithm. When constructing a target position using a function such as order_target, completed orders are considered, but open orders are not considered.

Order method

The ordering methods that can be used in the algorithm are shown in the table. Regular orders are created with the number of shares, amount, and percentage specified by amount or percentage. For the target order, take into account the existing positions and create an order so that the position after ordering will be the number of shares, amount, and percentage specified by amount or percentage. When building a target position with a target order, closed orders are considered, but open orders are not.

Order type Regular order Target order
Specify the number of shares order() order_target()
Amount specification order_value() order_target_value()
Weight specification order_percent() order_target_percent()

You can specify the order type style = OrderType for all order types. The default is MarketOrder, which allows you to use StopOrder, LimitOrder, and StopLimitOrder (Limit + Stop).

Specify the number of shares

order(security, amount, style=OrderType) order_target(security, amount, style=OrderType)

order creates an order for the specified brand and quantity. order_target creates an order so that the number of shares after the order is the target number of shares. If there are no existing positions, an order for the full quantity specified by amount will be created. If you have an existing position, the difference between the target number of shares and the number of shares you currently own will be the order quantity. For example, if you have 5 shares of AAPL in your current portfolio, executing order_target (symbol ('AAPL'), 20) will create an order for the difference of 15 shares.

security: securities object amount: Specify the number of shares as an integer. Positive numbers are buys and negative numbers are sells. style: Specify the order type.

Return value Order ID

Amount specification

order_value(security, amount, style=OrderType) order_target_value(security, amount, style=OrderType)

order_value creates an order with the specified amount. For example, if you want to buy AAPL \ $ 1000, specify order_value (symbol ('AAPL'), 1000) and if the price of AAPL is \ $ 105, 9 shares will be bought. Fractions are truncated. order_target_value creates an order so that the amount after the order is the target amount. If there are no existing positions, a full order specified by amount will be created. If you have an existing position, the difference between the target amount and the current holding amount will be the order amount. For example, if you have \ $ 500 in AAPL in your current portfolio, running order_target_value (symbol ('AAPL'), 2000) will create an order with a difference of \ $ 1500.

security: securities object specify the amount with amount: float. Positive numbers are buys and negative numbers are sells. style: Specify the order type.

Return value Order ID

Weight specification

order_percent(security, amount, style=OrderType) order_target_percent(security, percent, style=OrderType)

order_percent creates an order with a specified weight for the value of the portfolio. The value of the portfolio is the value of the position and the total amount of cash. The percentage must be specified as a decimal. For example, running order_percent (symbol ('AAPL'), .5) will create a buy order for AAPL with 50% of the value of the current portfolio. order_target_percent creates an order so that the weight after ordering is the target. If there are no existing positions, a full order specified by percent will be created. If you have an existing position, the difference between the target weight and the currently held weight will be the order quantity. For example, if your current portfolio has an AAPL weight of 5%, running order_target_percent (symbol ('AAPL'), 0.1) will create an order with a difference of 5%.

security: securities object amount: Specify the weight. Positive numbers are buys and negative numbers are sells. percent: Specify the weight. Positive numbers are buys and negative numbers are sells. style: Specify the order type.

Return value Order ID

Order cancellation

cancel_order(order) Cancels the specified order.

order: order ID

Return value None

Get order information

get_open_orders(sid=sid) If no security ID is specified or None, a dictionary with the security ID as the key is returned. The dictionary stores a list of order information for each securities ID, starting from oldest. If a security ID is specified, returns a list of ordered orders for the security ID, sorted by oldest.

sid: (optional) Securities ID

Return value Dictionary or list

Get order information

get_order(order) Returns the specified order information.

order: order ID

Return value Returns a readable and writable order object, but is destroyed at the end of handle_data.

Order execution with Interactive Brokers Securities

Relative Order order(security, amount, style=RelativeOrder(offset, pct_offset, limit_price, exchange)) RelativeOrder is an order form that allows you to execute at a more aggressive price than NBBO (National Best Bid & Offer) [^ 1]. By presenting a more aggressive Bid and Offer than NBBO, you can increase the chances of your order being filled. There are fixed offsets (for example, 2 cents above and below Bid / Offer) and percentage offsets, which can also be used in combination. Quarts are automatically adjusted according to the movement of the market.

[^ 1]: ... Of the prices offered by all domestic exchanges and market makers, the bid and offer that are most favorable to investors.

To use this order form, subscribe to IB's market data for Relative Orders. Otherwise, the IB will deliver quotes that are 15 minutes late.

In the case of a buy order, if the NBB (National Best Bid) rises, the order price will be automatically adjusted upward. If the NBB falls, the order price will not be adjusted. This is because the fall in NBB is believed to have made existing orders more aggressive.

In the case of sell orders, if the NBO (National Best Offer) drops, the order price will be automatically adjusted downward. The order price will not be adjusted if the NBO rises. This is because the rise in NBO is believed to have made existing orders more aggressive.

If you specify both a fixed offset and a percentage offset, the IB will choose the more aggressive and possible of the two prices. (Higher for buying, lower for selling)

In this order form, you can also specify a limit so that the price is not executed above the specified price in the case of buying and below the specified price in the case of selling.

If backtested with this order form, the order will be a simple market order. It really works as a Relative Order only when run with an IB real money account.

In the future, when backtesters support this order form, they will set up a custom slippage model.

To use this order form, you need to import RelativeOrder from the brokers.ib library.

security: securities object amount: Number of shares ordered. offset: Fixed offset value from the current NBB or NBO. In dollar units. pct_offset: Percentage offset value from the current NBB or NBO. Specify between 0 and 100. limit_price: Specifies the highest price for buying or the lowest price for selling. exchange: Not used. For this order form, IB Live Trading will place an order with SMART [^ 2]. Ignored if not Live Trading. Routing to the IEX exchange is not allowed.

[^ 2]: An order that automatically selects the market with the best price from multiple markets such as SMART ... Smart order routing (SOR), domestic exchanges and private exchanges (PTS), and executes trading.

VWAPBestEffort

python


order(security, amount, style=VWAPBestEffort(limit_price=price1, start_date=date1,
                                             end_date=date2, max_pct_vol=percent,
                                             avoid_liquidity=False, exchange=Exchange))

VWAPBestEffort seeks to approach the Volume Weighted Average Price (VWAP) by subdividing orders into smaller pieces and executing them over a specified period of time. This order form is only available for IB live trading. IB supports best effort VWAP for market and limit orders. Stop order and limit + stop order are not supported. This order form is compatible with order forms that include order, order_target, order_value, order_target_percent. Once a market or limit order is placed with the IB, the broker will use a best effort algorithm to fill the order.

With this method, the order is partially filled within the time period and fully filled by the end date. It is highly recommended that the algorithm check for open orders in order for the order logic to work.

You need to import the VWAPBestEffort class from brokers.ib in order to place a VWAP order.

security: securities object amount: Number of shares ordered. limit_price: (optional) Specifies the limit price for the order as a fractional number. If None is specified, it will be a market order. start_date: (optional) Specifies the VWAP start period. The default is 1 minute after the algorithm time. BestEffort orders will be executed from the next minute of the IB. end_date: (optional) Specifies the VWAP end period. The default is the closing time of the transaction. max_pct_volume: (optional) Specifies the percentage of the daily volume that is allowed to be traded. The possible range is 0.01 – 0.5. The default is 0.25. avoid_liquidity: (optional) Prevents orders from hitting bid / offer. This will help you avoid the liquidity acquisition fee [^ 3] and you will get a liquidity rebate. However, the gap with the benchmark may be large. This parameter is a boolean value and defaults to False. exchange: (optional) Specifies the routing of the order. The default for IB Live Trading is SMART. Ignored if not Live Trading. Routing to the IEX exchange is not allowed.

Return value Order ID

pipeline

// Will be summarized separately

Other methods

Historical data acquisition

history(bar_count, frequency, field, ffill=True) Get variable historical data for each day.

bar_count: Specifies the number of bars as an integer. The number includes the current bar. frequency: Specifies the frequency with which data is retrieved. '1d' and '1m' are available. field: Specify the value to get from the historical data. You can specify one of'open_price',' close_price',' price',' high',' low', and'volume'. ffill: If there is a gap in the historical data, specify whether to use the previous data to fill the gap. The default is True. If set to False, np.nan will be returned for price data and 0 for volume.

Return value In pandas.DataFrame format, the number of rows is bar_count, the value is the value specified by field, and column is the Security ID of the current universe.

Record on the chart

record(series1_name=value1, series2_name=value2, ...) record('series1_name', value1, 'series2_name', value2, ...) Records the value given as an argument. Outputs a chart for all recorded content. values: You can set up to 5 keywords and values.

Return value None

Periodic execution processing

schedule_function(func=myfunc, date_rule=date_rule, time_rule=time_rule, half_days=True) The function is automatically executed according to a predefined schedule. It can only be called from within initialize.

func: Defines the function name. The function must have context and data as parameters. date_rule: Specifies the date part of the schedule. Dates can be offset daily, weekly, or from the beginning or end of each month. The default is daily and the offset is 0. In other words, if you don't specify a date rule, the function runs daily. The applicable rules are as follows.

time_rule: Specifies the time part of the schedule. The time can be specified as an offset from the beginning or end of the transaction start or end, respectively. The default is at the start of the transaction and 1 minute before the end of the transaction. The applicable rules are as follows.

half_days: A Boolean value that specifies the behavior of the half-Hitachi day. If set to False, the function will not be called on the day of Semi-Hitachikai. The default is True.

Return value None

Get ticker symbol

set_symbol_lookup_date('YYYY-MM-DD') Specify a date to make the ticker symbol valid at that time the universe. Must be executed in initialize before calling the symbol or symbols function.

date: YYYY-MM-DD format string

Return value None

Acquisition of securities object

sid(int) Get the security object by specifying the security ID.

int: Securities ID

Return value Securities object

symbol('symbol1') Gets the security object by specifying the ticker symbol.

'symbol1': ticker symbol

Return value Securities object

symbols('symbol1', 'symbol2', ...) Gets a list of securities objects by specifying ticker symbols separated by commas.

'symbol1','symbol2', ...: ticker symbol

Return value List of securities objects

Universe update

update_universe(sids) Update the stock universe. Called in before_trading_start.

sids: List of securities IDs

Return value None

Recommended Posts

Quantopian API Reference
xlwings API reference list