Hey guys,
I have to program a code with the squeeze momentum indicator for a seminar at university. And now our task is to normalize the returns. For that I need to calculate the beta between my investment and the market (S&P 500 in this case) regularly. With the help of the Talib-library it is possible to calculate the beta. But as far as I can see you can just compute the beta between two given instruments and not your own code. I have no clue how I can implement this task in my code and solve this problem. For any help I am very thankful. I attached my code. Thanks in advance.
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(4707)
set_benchmark(context.stock) #set the stock as benchmark
schedule_function(trend_signal, date_rules.every_day(), time_rules.market_close(hours=1))
def trend_signal(context, data):
#calculate the current price and position
current_position = context.portfolio.positions[context.stock].amount
current_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 with sma for a range of 20 days
sma = talib.SMA(prices, 20)
atr = talib.ATR(high, low, prices, timeperiod=20)
multKC = 1.5
upperKC = sma + atr * multKC
lowerKC = sma - atr * multKC
#calculate the signals
sqzOn = (lowerBB[-1] > lowerKC[-1]) and (upperBB[-1] < upperKC[-1])
sqzOff = (lowerBB[-1] < lowerKC[-1]) and (upperBB[-1] > upperKC[-1])
#calculate the trading-direction 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)