Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
context.portfolio.portfolio_value (of N days ago)

I would like to know how it is possible to grab the context.portfolio.portfolio_value of the previous N days.

Is this possible? Or is there another more straightforward way of calculating the portfolio's return over the last N days?

Thanks.

6 responses

I dont think this would come out of the box, you would need to track it yourself.

If you are always using the same N period, using something like a deque makes it simple - that is what I am doing with one of my algos.

Mohammad,

Could you maybe show me an example of what you are talking about? I would really appreciate it.

Sure, here is some rough untested code...

Assuming N period of 5, we create a deque with max length of 5, then every day we put the new portfolio_value into it. Old ones automatically drop off and you always have 5 values.

# init  
context.daily_window = deque(maxlen=5)

# run daily  
context.daily_window.append(context.portfolio.portfolio_value)  

then whenever you want to get a value, you can do context.daily_window[-1] or context.daily_window[-4] etc.

Thanks a lot Mohammad!

The code works with a value of -1 but when I try to index further I get "IndexError: deque index out of range"

Is there a fix for this one? I tried a few things but I could not get it to work

so you wont be able to use further indexes until you have them stored - so for the first 4 days you cant use it.

You can check it like this:

if (len(context.daily_window) > 4):  
    # do some trading  

Bear in mind that the above will mean your algo wont trade in the first 4 days of the backtest, because your deque will not be filled yet.

Seems to work perfectly now! Thanks for the help!