Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Seems to be too much memory

I am trying to run my code, and I seem to get a memory error. I can not understand it clear.

The errors shows:
IndexError: Too many levels: Index has only 1 level, not 2
There was a runtime error on line 64.

import quantopian.algorithm as algo  
from quantopian.pipeline import CustomFactor  
from quantopian.pipeline import Pipeline  
from quantopian.pipeline.data import USEquityPricing  
from quantopian.pipeline.experimental import QTradableStocksUS

import pandas as pd  
import numpy as np

from quantopian.pipeline.factors import PercentChange  
from zipline.api import attach_pipeline, pipeline_output

import random

class previousFactor(CustomFactor):  
    def compute(self, today, assets, out, inputs):  
        out[:] = inputs[0]

def initialize(context):

    # Schedule rebalance function  
    schedule_function(  
        rebalance,  
        date_rule=algo.date_rules.week_start(),  
        time_rule=algo.time_rules.market_open()  
    )  
    algo.attach_pipeline(make_pipeline_before(), 'pipelinebefore')  
    algo.attach_pipeline(make_pipeline_today(), 'pipelinetoday')  
def make_pipeline_today():  
    pipe=Pipeline()  
    mom_t=range(2,121)  
    for t in mom_t:  
        mom=PercentChange(inputs=[USEquityPricing.close],window_length=t)+1  
        pipe.add(mom,'mom'+'-'+str(t))  
    return pipe 

def make_pipeline_before():  
    week_return=PercentChange(inputs=[USEquityPricing.close],window_length=5)  
    days=range(1,120,5)  
    mom_t=range(2,121)  
    pipe=Pipeline()  
    for day in days:  
        return_previous = previousFactor(inputs = [week_return],window_length = day)  
        pipe.add(return_previous,'week_return'+str(day))  
        for t in mom_t:  
            mom=PercentChange(inputs=[USEquityPricing.close],window_length=t)+1  
            mom_previous = previousFactor(inputs = [mom],window_length = day)  
            pipe.add(mom_previous,'mom'+'-'+str(t)+'-'+str(day))  
    return pipe


def rebalance(context, data):  
    optimal_momentum_t = local_search()  
    pipeline_output = algo.pipeline_output('pipelinetoday')  
    mom='mom'+'-'+str(optimal_momentum_t)  
    output=pipeline_output.sort_values(by=mom).dropna().tail(5)  
    chosen_asset = output.index.get_level_values(level=1).unique()  
    for asset in chosen_asset:  
        order_percent(asset, 0.2)

def simulated(mom_t):  
    # This function generate new pipeline every week with momentum period mom_per  
    # and choose 5 stocks with highest momentums  
    # then calc the weekly return at next week  
    # It returns the total return of 17 times that's about 120 days  
    total_return=0  
    days=range(116,6,-5)

    for day in days:  
        # every week new pipeline  
        mom='mom'+'-'+str(mom_t)+'-'+str(day)  
        pipeline_output=algo.pipeline_output('pipelinebefore')  
        output=pipeline_output.sort_values(by=mom).dropna().tail(5)  
        # next week  
        newday=day-5  
        week_return = output['week_return'+str(newday)]  
        total_return+=sum(week_return)  
    return total_return

def init_t():  
    mom_peris = []  
    for x in range(0,4):  
        t=random.randint(2, 120)  
        mom_peris.append(t)  
    return mom_peris

def reproduce(mom_peris,returns,p):  
    # reproduce in a population  
    return_sum=0  
    posib=[]  
    for i in range(len(mom_peris)):  
        if returns[i]>0:  
            return_sum+=returns[i]  
    for i in range(len(mom_peris)):  
        if returns[i]>0:  
            posib.append(returns[i]/return_sum)  
        else:  
            posib.append(0)  
    a=np.random.choice(mom_peris,p=posib)  
    b=np.random.choice(mom_peris,p=posib)  
    # crossover  
    new_per=(a+b)//2  
    # mutation  
    number=random.random()  
    if number<p:  
        new_per=random.randint(1, 120)  
    return new_per

def local_search():  
    # get the best momentum period t at period_start  
    p=0.1  # mutation prob  
    #create population  
    mom_peris=init_t()  
    returns=[]  
    for i in range(len(mom_peris)):  
        r = simulated(mom_peris[i])  
        returns.append(r)  
    # reproduce 5 times  
    end=5  
    times=0  
    while(times<end):  
        new_per = reproduce(mom_peris,returns,p)  
        mom_peris.append(new_per)  
        returns.append(simulated(new_per))  
        times+=1  
    # get t  
    best=max(returns)  
    i=returns.index(best)  
    t = mom_peris[i]  
    return t

1 response

The error IndexError: Too many levels: Index has only 1 level, not 2 comes from the following line of code

    chosen_asset = output.index.get_level_values(level=1).unique()  

The dataframe returned by a pipeline in an algo has a single index. It doesn't have a multi index as in a notebook. It just returns data for the single simulation date. So, change 'level=1' to 'level-0' and it should work.

    chosen_asset = output.index.get_level_values(level=0).unique()  

I believe you may still get a timeout error. Maybe try speeding up your code by replacing the for and while loops with numpy or pandas vector methods if possible. Additionally, move the time intensive code to the before_tradingstart` function. That get's allocated more time (scheduled functions must complete in under 60 seconds).

Disclaimer

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.