Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Help Using Total Market Cap for Sector in IDE

Hello,
I have been testing some data in a notebook. I will post the notebook code below. It takes market cap data for stocks, sums them by sector, creates a Moving Average, then compares them with a Bollinger Band. To be clear, the Moving Average and Bollinger Bands use the sum of the market caps of all stocks in a sector. Right now all I have it doing is printing whether the Moving Average is above, in, or below the band. I'm now trying to integrate this into an algorithm in the IDE and I haven't been able to solve it. I believe that my problem is when the backtest runs for a trading day, I don't have the historical data needed to create Moving Averages and Bollinger Bands. The backtest does currently run but the results are not correct.

For 2018-10-19 should be:
101 is in band
102 is in band
103 is in band
104 is in band
205 is in band
206 is in band
207 is in band
308 is in band
309 is below band
310 is in band
311 is in band

Thanks in advance for the help.

# Imports  
import numpy as np  
import pandas as pd  
import matplotlib.pyplot as plt  
from quantopian.pipeline import Pipeline  
from quantopian.research import run_pipeline  
from quantopian.pipeline.data.builtin import USEquityPricing  
from quantopian.pipeline.data import morningstar  
from quantopian.pipeline.filters import QTradableStocksUS  
from quantopian.pipeline.data import Fundamentals

sector_list = [101,102,103,104,205,206,207,308,309,310,311]

def stock_pipeline():

    #Data Columns  
    sectors = morningstar.asset_classification.morningstar_sector_code.latest  
    market_cap = Fundamentals.market_cap.latest  
    # Return Pipeline  
    return Pipeline(columns={  
        'sector':sectors,  
        'market_cap':market_cap  
    })

stocks = run_pipeline(stock_pipeline(),'2018-01-01','2018-10-19')

# Function to see if buy signal exist in sectors  
def sector_signal_checker(sector_list):  
    for sector in sector_list:  
        # Add market cap in sector  
        total_market_cap = stocks[stocks.sector==sector].market_cap.groupby(level=0).sum()  
        # Create bollinger band  
        total_mc_bb_middle = total_market_cap.rolling(window=5).mean().shift(1)  
        total_mc_bb_upper = total_mc_bb_middle + 2.0*total_market_cap.rolling(window=5).std().shift(1)  
        total_mc_bb_lower = total_mc_bb_middle - 2.0*total_market_cap.rolling(window=5).std().shift(1)

        # Set Signal  
        if total_market_cap[-1] > total_mc_bb_upper[-1]:  
            print('{} is above band'.format(sector))  
        elif total_market_cap[-1] < total_mc_bb_lower[-1]:  
            print('{} is below band'.format(sector))  
        else:  
            print('{} is in band'.format(sector))

sector_signal_checker(sector_list)