Hi guys,
I'm trying to start this algorithm by meeting all restrictions, but I can't seem to meet the leverage req's or the turnover req's
import talib as ta
from quantopian.pipeline.data import morningstar
import numpy as np
import time
import datetime
import pandas as pd
import talib
import quantopian.optimize as opt
from quantopian.pipeline.filters import QTradableStocksUS
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 CustomFactor,SimpleMovingAverage
from quantopian.pipeline.data.psychsignal import stocktwits
#from quantopian.pipeline.data.zacks import EarningsSurprises
def initialize(context):
context.max_leverage = 1.1
context.max_pos_size = 0.05
context.max_turnover = 0.65
def handle_data(context, data):
pass
def make_pipeline(context):
pipe=Pipeline()
universe = QTradableStocksUS()
sentiment_score = SimpleMovingAverage(
inputs=[stocktwits.bull_minus_bear],
window_length=3,
mask=QTradableStocksUS()
)
pipe.add(sentiment_score,'sentiment_score')
Price_Range = PriceRange(window_length=3,mask = universe)
pipe.add(Price_Range,'Price Range')
Volume_Mean5 = VolumeFactor(window_length=5,mask = universe)
pipe.add(Volume_Mean5,'Volume_Mean5')
pipe.set_screen((Volume_Mean5>=1000000)&(Price_Range>300)&(Price_Range<10000) &sentiment_score.notnull())
return pipe
def rebalance(context, data):
# Retrieve alpha from pipeline output
alpha = context.pipeline_data.sentiment_score
if not alpha.empty:
# Create MaximizeAlpha objective
objective = opt.MaximizeAlpha(alpha)
# Create position size constraint
constrain_pos_size = opt.PositionConcentration.with_equal_bounds(
-context.max_pos_size,
context.max_pos_size
)
# Constrain target portfolio's leverage
max_leverage = opt.MaxGrossExposure(context.max_leverage)
# Ensure long and short books
# are roughly the same size
dollar_neutral = opt.DollarNeutral()
beta_neutral = opt.FactorExposure(
pipeline_data[['beta']],
min_exposures={'beta': -0.05},
max_exposures={'beta': 0.05},
)
# Constrain portfolio turnover
max_turnover = opt.MaxTurnover(context.max_turnover)
# Rebalance portfolio using objective
# and list of constraints
algo.order_optimal_portfolio(
objective=objective,
constraints=[
constrain_pos_size,
max_leverage,
beta_neutral,
dollar_neutral,
max_turnover,
]
)