Algorithm Recipes

Scheduling Functions

Examples of schedule_function().

Date Rules

This example calls myfunc every morning, 15 minutes after the market opens. (The exact time will depend on the calendar you are using. For the US Equity calendar, for example, the function would run from 9:45-9:46AM Eastern Time.)

Note the use of every_day().

def initialize(context):
    # Algorithm will call myfunc every day 15 minutes after the market opens
    schedule_function(
        myfunc,
        date_rules.every_day(),
        time_rules.market_open(minutes=15)
    )

def myfunc(context,data):
    pass

This example calls myfunc every 30 minutes.

Note the use of multiple schedule_function() calls to execute more complex schedules.

def initialize(context):
    # US market is usually open for 390 minutes.
    total_minutes = 390

    for i in range(1, total_minutes):
        # Every 30 minutes run schedule
        if i % 30 == 0:
        # This will schedule myfunc to run every day at 9:31AM on the US Equity
        # calendar as well as every 30 minutes after that.
        schedule_function(
            myfunc,
            date_rules.every_day(),
            time_rules.market_open(minutes=i),
            True
        )

def myfunc(context,data):
    pass

This example uses schedule_function() to schedule a rebalance function once at the start of each quarter. Note the use of get_datetime() to skip the rebalance logic when we're not at the start of a quarter. This is a workaround to the fact that schedule_function doesn't support quarterly start/end logic.

QUARTER_STARTS = [1,4,7,10]

def initialize(context):
    # Algorithm will call rebalance once at the start of each month.
    schedule_function(
        rebalance,
        date_rules.month_start(),
        time_rules.market_open()
    )

def rebalance(context,data):

    # If the current month number is not in QUARTER_STARTS,
    # don't do anything.
    month_number = get_datetime().date().month
    if month_number not in QUARTER_STARTS:
        return

    # Rest of rebalance logic goes here.

Ordering

Checking Order Status

This example logs all the open orders across all securities.

Note the use of get_open_orders().

def initialize(context):

    schedule_function(
        my_func,
        date_rules.every_day(),
        time_rules.market_open(minutes=15)
    )

def my_func(context, data):

    # Order 100 shares of AAPL.
    order_target(sid(24), 100)

    # Retrieve all open orders.
    open_orders = get_open_orders()

    # If there are any open orders.
    if open_orders:
        # open_orders is a dictionary keyed by sid, with values that are lists of orders. Iterate over the dictionary
        for security, orders in open_orders.iteritems():
            # Iterate over the orders and log the total open amount
            # for each order.
            for oo in orders:
                message = 'Open order for {amount} shares in {stock}'
                message = message.format(amount=oo.amount, stock=security)
                log.info(message)

Recording Variables

This example records the prices of MSFT and AAPL every day at market close.

Note that the argument names (specified with msft= and aapl=) determine the name of the series in the plot.

def initialize(context):
    schedule_function(record_vars, date_rules.every_day(), time_rules.market_close())

def record_vars(context, data):
    # Plot the prices of MSFT and AAPL
    record(msft=data.current(sid(5061), 'price'), aapl=data.current(sid(24), 'price'))