Back to Community
Announcement: New schedule_function method allows you to specify when a function runs

Today we are releasing a brand new method called schedule_function that allows you to specify on what days and at what times you want a function to run. Instead of manually calculating the day and time in your algorithm, you can pass it in this function automatically! It will execute your code based on the rules you pass - on a daily, weekly or monthly schedule, or at a specific time during the trading day.

This means, you can easily schedule a piece of code to run once a day, at the beginning of a month, or only execute orders 15 minutes before the market closes - to name a few examples.

Take a look at the example below which shows a portfolio rebalance that happens the first trading day of the month, 30 minutes after the market opens or read more about how schedule_function works. Try it out with your algorithm and we'd love to hear your feedback!

Clone Algorithm
121
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 5464feb2662824093264d1e1
There was a runtime error.
Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

11 responses

Great addition to Quantopian. This should save code, make things simpler, and hopefully allow the programmers to optimize the code.

Thanks Karen,

Some questions:

  1. When does the function get called in relation to the call to handle_data?
  2. The help page and your example show the function with context & data as arguments. Are they the only arguments that can be used?
  3. Is the code for this functionality open source (e.g. in zipline)?
  4. If the function contains an order, will it be sent asynchronously (immediately) to the broker (as for a normal order)? Or will there be a delay?
  5. Can the function be called independently (e.g. based on other conditions in the code)? Or if it is scheduled, can it only be run per the schedule automatically?

Grant

Hey Grant, to address your questions:

  1. The functions are called AFTER handle_data in the order they are scheduled.
  2. Just like handle_data, context and data are the only arguments that can be used. You can think of handle_data as a function that has been implicitly scheduled to run every minute (this is the actual implementation too).
  3. This is all in zipline. For implementation details, you can poke at zipline.utils.events
  4. I am going to double check on the timing of orders.
  5. The function is still usable like normal, you can call it just like any other function without affecting the schedule.
Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Here are a few examples that show how you'd convert an algorithm into schedule function.

I took Alex Lokhov's Structural Arbitrage Strategy found here (https://www.quantopian.com/posts/example-implementation-of-the-structural-arbitrage-strategy?c=1) and converted (very easily with schedule function) into minutely mode

Clone Algorithm
107
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 546f81931698c808f1779c6c
There was a runtime error.
Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

I'm using schedule_function in a quantopian script without a problem, but when I try to run it outside quantopian using zipline the function can't be found.
zipline.utils.events doesn't seem to have that function either. Can you post the way to use it in zipline?

If a function is available to you without import on Quantopian, then it normally lives in:

zipline.api

# For example  
from zipline.api import schedule_function, order, history  

The function itself is in zipline.algorithm if you are interested.

Thanks Joe, that worked well. How do I keep compatibility with the log.info commands available in quantopian?

you can construct a Logger object:

from logbook import Logger  
log = Logger('Algorithm)  

and then you should be good to go.

Hey Seong--

I'm finding that the schedule function doesn't appear to be respecting the parameters in the market_open function as well as not respecting two separate schedule_function calls for the same day (ie. market_open/market_close) For the example you pasted, if I change minutes from 15 to 45 (or hours), nothing changes with respect when the order occurs or the returns generated. Similarly, if I try and use two schedule_function calls, one for the beginning of the day and one for the end, it seems to call them both at the same time. Any insight?

Thanks!

Clone Algorithm
4
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 54d0f638b5bb900d2fdbc7db
There was a runtime error.

In daily mode, all scheduled functions are executed at the end of day when handle_data is called.

Is schedule_function available in zipline 0.7.0? If not, is there a plan on updating the zipline package in pip to 0.8.0 anytime soon? I tried importing zipline.api with schedule_function, but I receive

AttributeError: 'MyStrategy' object has no attribute 'schedule_function'

I checked the Git repository and read the schedule_function code, so I'm certain I'm calling it correctly. Here's an example of how my code looks

class MyStrategy(TradingAlgorithm):  
    def trade_indicator(self, data):  
        # Do something cool  
        pass

    def initialize(self):  
        # Initialize broker settings  
        self.set_commission(commission.PerTrade(cost=1.0))  
        self.set_slippage(FixedSlippage(spread=0.0))

        # Initialize scheduled functions  
        self.schedule_function(self.trade_indicator,  
                               date_rule=self.date_rules.every_day(),  
                               time_rule=self.time_rules.market_open(hours=0, minutes=30))

    def handle_data(self, data):  
        pass  

Any ideas of what could be the issue? I guess if this ends up not working, I'll prime the data via history and "schedule" my function's call in handle_data.