Back to Community
Bollinger Bands

Hello All,

This is what I had in mind but I don't know why it works. (The Upper and Lower labels are reversed.)

Regards,

Peter

Clone Algorithm
1749
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
import pandas

def process_df(df): 
    df = df.rename(columns={'Close': 'price'})  
    df = df.fillna(method='ffill')  
    log.info(df.head())
    df['MA20']=pandas.stats.moments.rolling_mean(df['price'], 20)
    df['ABS']=abs(df['price']-df['MA20'])
    df['STDDEV']=pandas.stats.moments.rolling_std(df['ABS'], 20)
    df['UPPER_BB']=df['MA20']+2*df['STDDEV']
    df['LOWER_BB']=df['MA20']-2*df['STDDEV']
    log.info(df[38:39])
    return df  

def initialize(context):
    fetch_csv('https://raw.github.com/pcawthron/StockData/master/CMG%202011%20Daily%20Close.csv',  
        date_column='Date',  
        symbol='CMG',  
        usecols=['Close'],
        post_func = process_df,
        date_format='%d/%m/%Y'  
        )  
    context.stock = sid(28016)
        
def handle_data(context, data):
    if str(data['CMG'].datetime.year) == "2011":
        record(CMG=data['CMG'].price)
        record(Upper=data['CMG']['LOWER_BB'])
        record(MA20=data['CMG']['MA20'])
        record(Lower=data['CMG']['UPPER_BB'])
    
We have migrated this algorithm to work with a new version of the Quantopian API. The code is different than the original version, but the investment rationale of the algorithm has not changed. We've put everything you need to know here on one page.
This backtest was created using an older version of the backtester. Please re-run this backtest to see results using the latest backtester. Learn more about the recent changes.
There was a runtime error.
1 response

def handle_data(context, data):
if str(data['CMG'].datetime.year) == "2011":
record(CMG=data['CMG'].price)
record(Upper=data['CMG']['LOWER_BB'])
record(MA20=data['CMG']['MA20'])
record(Lower=data['CMG']['UPPER_BB'])

Your setting "Upper" as "LOWER_BB" and "Lower" as "UPPER_BB"