Back to Community
Schedule Function Problem

Hello Everybody,
I am working on a very simple algorithm and I only want it to live trade once per day right before closing (like a daily backtest works) (I may want to make the trades at the beginning of the day depending on the results). I want to do this because the funds are leveraged ETFs so I lose money if I trade more than once per day. The only problem is that I don't know what I am doing wrong with the schedule_function. I keep getting the error: Line 4: Error: SyntaxError: pass the non-keyword argument before the keyword argument.

Here is the code:

def initialize(context):
context.stocks = [sid(32272), sid(39214), sid(32269), sid(39215), sid(32270), sid(38533), sid(32271), sid(39216), sid(33209), sid(33208), sid(39217), sid(38564)]

schedule_function(func=handle_data, date_rules.every_day(), time_rules.market_close(hours=0, minutes=1), half_days=True)

def handle_data(context, data):
for stock in context.stocks:
if stock in data:

Thanks for all of the help,
Nick V

6 responses

There are two things wrong with your code...

1) The message you get is accurate, you're using the "func" key word before the two trailing non-key word arguments in schedule_function. Remove the func word.

2) You're overloading handle_data. Handle_data gets called every minute. Period. You'll be calling this method 390 times a day. Use a dedicated method name.

def initialize(context):  
    context.stocks = [sid(32272), sid(39214), sid(32269), sid(39215), sid(32270), sid(38533), sid(32271),sid(39216), sid(33209), sid(33208), sid(39217), sid(38564)]

    schedule_function(handle_data2, date_rules.every_day(), time_rules.market_close(hours=0, minutes=1))

def handle_data(context, data):  

def handle_data2(context, data):  
    for stock in context.stocks:  
        if stock in data:  

Keep in mind that Quantopian automatically cancels open orders at day's end, when trading with IB. See Live Trading section of help page:

All open orders are cancelled at end-of-day.

So, if there are any incomplete fills at the market close, your orders won't get completely filled. Maybe this is the behavior you want, but if not, I thought I'd point out this detail.


I have been trying to figure out how to schedule a function right myself.

I want to buy two different ETF's at market price 30 minutes after the open, and have them sell at market price at 3:15pm, I am using this:

def initialize(context):

) # This defines the scheduled function that is supposed to buy 30min after the open.

time_rule=time_rules.market_open(hours=5 minutes=45),
) # This defines the function to sell the remaining position 45min before close.

#myfuncOpen is to buy after the open  

) # Algorithm will call myfuncOpen every day 30 minutes after the market opens

#myfuncClose is to sell before the close  

time_rules.market_close(hours=5, minutes=45)
) # Algorithm will call myfuncClose every day, 45 minutes before the market closes

Any idea whats wrong here?

I cleaned up my code and figured out how to use the schedule function command. but I have a run time error now,

import talib
import datetime
import pytz
from pytz import timezone
import brokers.ib
from brokers.ib import IBExchange

def initialize(context):
context.stock = symbol("SPY")
context.ETFs = sid(42471),sid(42472) # UWTI and DWTI
# Add other 3x ETF's later
set_benchmark(context.stock) # comparing against SPY
context.stop_price = 0
context.stop_pct = 0.99 # sets 1% trailing stop-loss

schedule_function(buy, date_rules.every_day(), time_rules.market_open(minutes=30),  
# I want to schedule to buy ETFs everyday 30min after the open at market price  

schedule_function(sell, date_rules.every_day(), time_rules.market_close(minutes=45),  
# I want to schedule to sell the ETFs everyday, if no stop triggered, 45min before close 

def handle_data(context, data):
set_trailing_stop(context, data)
if data[context.ETFs].price < context.stop_price:
order_target(context.ETFs, 0)
context.stop_price = 0

record(price=data[context.ETFs].price, stop=context.stop_price)  

def buy(context, data):
order_value(sid(42471), sid(42472), 5000, style=MarketOrder(exchange=IBExchange.IEX))

def sell(context, data):
order_value(sid(42471), sid(42472), 5000, style=MarketOrder(exchange=IBExchange.IEX))

def set_trailing_stop(context, data):
if context.portfolio.positions[context.ETFs].amount:
price = data[context.ETFs].price
context.stop_price = max(context.stop_price, context.stop_pct * price)

I cleaned up your code a bit to make it run. Some edits/suggestions:

  • context.ETFs is a tuple in your algo. When you order a stock, record the price etc, you need to specify the exact security - it can't accept multiple securities. Check out the updates in lines 28,29,33, 38-40,43-44,47-48
  • your buy and sell logic is identical, perhaps you're still working on this section?
  • it helps to add logging to your code, identifying when orders trigger to confirm the algo is behaving as expected


Clone Algorithm
Backtest from to with initial capital
Total Returns
Max Drawdown
Benchmark Returns
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: 56415c23d5d14f1106bf6e36
There was a runtime error.

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 see what you did, thanks a ton!

yes my buy and sell logic is the same under def_buy(context, data) and def_sell(context, data) because I thought that the logic in them would only be called when schedule_function calls to buy or sell, or when the trailing stop loss is triggered to sell. Wont the schedule_function and trailing stop initiate the buy and sell logic under Handle_Data?

If this is not how it works then I must be missing something in understanding how Def_Initialize and Def_Handle_data relate to each other