Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
batch_transform or history functions on portfolio data?

Suppose I want to have a data panel for the past 10 days of the portfolio value of my portfolio, so that I could compute a moving average. How would I go about doing it?

2 responses

SH,

Here's an approach. If you increase the value of 'window' you can accumulate a longer trailing window. Then, depending on what you need to do, you can select the 'portfolio_value' down to the minute level for the past 10 days or more.

Grant

import pandas as pd

window = 5 # trailing window size, in bars

def initialize(context):  
    context.stocks = [sid(8554),sid(33652)] # SPY & BND  
    context.all_data = pd.DataFrame()  
    context.orders_submitted = False  
def handle_data(context, data):  
    if (not context.orders_submitted):  
        order_target_percent(context.stocks[0],0.5)  
        order_target_percent(context.stocks[1],0.5)  
        context.orders_submitted = True  
    all_data = history(1,'1d','price')  
    # all_data = history(1,'1m','price') # runtime error "IndexError: index out of bounds"

    all_data['portfolio_value'] = context.portfolio.portfolio_value  
    context.all_data = context.all_data.append(all_data)  
    context.all_data = context.all_data.tail(window)  
    if len(context.all_data.index) < window:  
        return  
    print get_datetime()  
    print context.all_data  

thanks!