Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Can I close out all positions in an algorithm a few minutes before end of backtest period?

In my algorithm I close out positions in mid-month however I would like to additionally close out all positions shortly and be 100% cash before the end of a backtest interval. Is there any date or time rule combination to do this?

5 responses

Mark,

You should be able to hardcode the backtest end date and compare it to the current date-time. You would just need to remember to change the hardcoded end date if you change the backtest dates.

Maybe something like this (though I didn't actually test it)?

import datetime

current_date = get_datetime()         # fetches the current backtest date and time  
end_date = datetime.date(2010, 1, 3)  # whatever the backtest end date is

if current_date >= end_date:  
    # code to close all positions here

Dan

Thanks I was confusing myself searching for date and time rules in a scheduled function inside of the one-time Initialize function. Your solution is simple to implement inside of another function (that was scheduled from Initialize) that actually does buying and selling. It turns out I don't need to worry about scheduled date and time rules at all to do this.

Why do you want to liquidate at the end anyway? They are all mark to market in the portfolio, and trading out costs are small?

The short answer is, when measuring the performance of a strategy, at the end of a test, it is unsuitable to be carrying large short positions. They represent a large (impossible to quantify exactly) risk exposure as well as having implied margin interest costs. Therefore, if a strategy concludes with a large short position, that should be liquidated and then the overall strategy ROI can be stated with certainty.

Yes, but that short position will be marked to market with the same value (more or less) as if you sold it. So why bother selling it?