Back to Community
BB/KC Squeeze

Not much has been really implemented yet but I will improve this scrip

Clone Algorithm
3
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
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import AverageDollarVolume
from quantopian.pipeline.filters import Q1500US 
import talib
import numpy
import math
import pandas


def initialize(context):
    context.stock = sid(48780)
    set_benchmark(context.stock)
    schedule_function(trend_signal, date_rules.every_day(), time_rules.market_close(hours=1))
    
    
def trend_signal(context, data):
    
    #calculate the current price
    price = data.current(context.stock, 'price')
    
    #calculate prices for the last 30 days
    prices = data.history(context.stock, 'price', 30, '1d')
    high = data.history(context.stock, 'high', 30, '1d')
    low = data.history(context.stock, 'low', 30, '1d')
    
    #calculate the BBands with sma for a range of 20 days
    upperBB, middleBB, lowerBB = talib.BBANDS(
        prices, 
        timeperiod=20,
        # number of non-biased standard deviations from the mean
        nbdevup=2,
        nbdevdn=2,
        # Moving average type: simple moving average here
        matype=0)
    
    #calculate the Keltner Channels
    sma = talib.SMA(prices, 20)
    atr = talib.ATR(high, low, prices, timeperiod=20)
    multKC = 1.5
    upperKC = sma + atr * multKC
    lowerKC = sma - atr * multKC
    
    sqzOn = (lowerBB[-1] > lowerKC[-1]) and (upperBB[-1] < upperKC[-1])  
    sqzOff = (lowerBB[-1] < lowerKC[-1]) and (upperBB[-1] > upperKC[-1])   

    #calculate the indicators for a range of 20 days
    DIp = talib.PLUS_DI(high, low, prices, 20)[-1]  
    DIm = talib.MINUS_DI(high, low, prices, 20)[-1]  
    #ADX = talib.ADX(high, low, close, 20)[-1]
    
    
    open_orders = get_open_orders()
        
    if sqzOn and (DIp > DIm):
            if context.stock not in open_orders and data.can_trade(context.stock):
                order_target_percent(context.stock, 1.0)
            
    if sqzOn and (DIp < DIm):
            if context.stock not in open_orders and data.can_trade(context.stock):
                order_target_percent(context.stock, -1.0)
            
    if sqzOff:
        if context.stock not in open_orders and data.can_trade(context.stock):
            order_target_percent(context.stock, 0)
There was a runtime error.