Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
order on a specific day every month

Hey guys,

I´m new in programming with quantopian and I have a problem. I`m trying to place an order on a specific date every month.

My code actually looks like this:

def trading_function(context, data):  
    open_orders = get_open_orders()  
    actual_time = get_datetime()  
    order_time1 = datetime.datetime(2017, 1, 27)  

    if actual_time == order_time1:  
        if context.spy not in open_orders and data.can_trade(context.spy):  
            order_target_percent(context.spy, 1.0, stop_price='price'*0.9)  

it tells me the following:
TypeError: can't compare offset-naive and offset-aware datetimes
The problem is in the line "if actual_time == order_time1".

So the problem seems to be that the two datetypes dont match together. Is there any possibility to order on a specific date?

The next problem is, that with this method, I have to manually save all dates for ordering. Like I did at the variable order_time1.

Is there any possibility to always order on the 27th per month without saving all dates manually?

I hope you can help me. Thank you guys.

2 responses

You are getting that error because 'actual_time' is timezone aware but, by default, the 'datetime.datetime' method returns a timezone un-aware datetime. You could maybe do this (but haven't tried).

order_time1 =  datetime.datetime(2017, 1, 27, tzinfo=<UTC>)

However, consider using the schedule_function (https://www.quantopian.com/help#ide-schedulefunction). Maybe something like this will get you close to the 27th of each month.

schedule_function(  
        func=trading_function,  
        date_rule=date_rules.month_start(days_offset = 18),  
        time_rule=time_rules.market_close(minutes=1),  
        half_days=True  
  )

Ordering on a specific date (eg the 27th of each month) won't typically work because many times that will not be a trading day. I am guessing you don't want that behavior?

A couple of things to note about your approach . When using get_datetime() to check for market times and dates it's best to use the timezone parameter. Otherwise it will be in UTC. Something like this.

    current_date = get_datetime('US/Eastern')

Also, comparing two datetimes as you did

    if actual_time == order_time1: 

will also compare the time portion of the datetime too and NOT just the date portion. The 'get_datetime()' method will include the current algorithm time while setting a datetime as you did will set the time to zeros.

@Din Whitnable

Thank you really much, using a schedule_function is a really good idea, I didn`t think about that.

I will tell you if it works. :)