The code throws an error as update_universe has been deprecated. I tried to rewrite it in the new style, but it is not compiling. Wondering if anyone can update the code? Besides , how can I enhance the code so that the weights of each stock is proportional to its sentiment score?
"""
This sample algorithm will give you a brief overview on using the
StockTwits Trader Mood PsychSignal dataset.
This dataset measures the mood of traders posting messages on
StockTwits
Key metrics:
bull_scored_messages - total count of bullish sentiment messages
scored by PsychSignal's algorithm
bear_scored_messages - total count of bearish sentiment messages
scored by PsychSignal's algorithm
bullish_intensity - score for each message's language for the stength
of the bullishness present in the messages on a 0-4
scale. 0 indicates no bullish sentiment measured, 4
indicates strongest bullish sentiment measured. 4 is rare
bearish_intensity - score for each message's language for the stength
of the bearish present in the messages on a 0-4 scale.
0 indicates no bearish sentiment measured, 4 indicates
strongest bearish sentiment measured. 4 is rare
total_scanned_messages - number of messages coming through PsychSignal's
feeds and attributable to a symbol regardless of
whether the PsychSignal sentiment engine can score
them for bullish or bearish intensity
"""
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.factors import CustomFactor, AverageDollarVolume
from quantopian.pipeline.filters import QTradableStocksUS
import pandas as pd
import numpy as np
from quantopian.pipeline.data.psychsignal import stocktwits_free as psychsignal
class PsychSignal(CustomFactor):
"""
Baseline PsychSignal Factor
"""
inputs = [psychsignal.bull_minus_bear]
window_length = 1
def compute(self, today, assets, out, bull_minus_bear):
out[:] = bull_minus_bear
class PsychSignalMessages(CustomFactor):
"""
Created to rank each security by message coverage
"""
inputs = [psychsignal.bull_scored_messages, psychsignal.bear_scored_messages]
window_length = 30
def compute(self, today, assets, out, bull_msgs, bear_msgs):
np.mean(bull_msgs + bear_msgs, axis=0, out=out)
def before_trading_start(context, data):
results = pipeline_output('factors').dropna()
lower, upper = results['psychsignal_sentiment'].quantile([.05, .95])
context.shorts = results[results['psychsignal_sentiment'] <= lower]
context.longs = results[results['psychsignal_sentiment'] >= upper]
#update_universe(context.longs.index | context.shorts.index)
#context.Universo = context.longs.index | context.shorts.index
#context = context[(context.longs.index | context.shorts.index)]
def initialize(context):
# Create our pipeline
# Base universe set to the QTradableStocksUS
universe = QTradableStocksUS()
pipe = Pipeline()
pipe = attach_pipeline(pipe, name='factors')
pipe.add(PsychSignal(), "psychsignal_sentiment")
# Screen out penny stocks and low liquidity securities.
dollar_volume = AverageDollarVolume(window_length = 20)
# Only looks at securities within the top 1000 most liquid
# and the 500 securities within those with the highest message
# coverage
liquidity_rank = dollar_volume.rank(ascending=False) < 1000
message_rank = PsychSignalMessages().rank(ascending=False,
mask=liquidity_rank)
pipe.set_screen(universe & (dollar_volume > 10**7) & (500 > message_rank))
# Set our shorts and longs and define our benchmark
context.spy = sid(8554)
context.shorts = None
context.longs = None
# Create our scheduled functions
schedule_function(rebalance, date_rules.every_day())
schedule_function(cancel_open_orders, date_rules.every_day(),
time_rules.market_close())
set_commission(commission.PerShare(cost=0, min_trade_cost=0))
set_slippage(slippage.FixedSlippage(spread=0))
def handle_data(context, data):
record(lever=context.account.leverage,
exposure=context.account.net_leverage,
num_pos=len(context.portfolio.positions),
oo=len(get_open_orders()))
def cancel_open_orders(context, data):
# Cancel any open orders at the end of each day
for security in get_open_orders():
for order in get_open_orders(security):
cancel_order(order)
def rebalance(context, data):
# Order our shorts
for security in context.shorts.index:
if get_open_orders(security):
continue
if security in data:
order_target_percent(security, -1.0/len(context.shorts.index))
# Order our longs
for security in context.longs.index:
if get_open_orders(security):
continue
if security in data:
order_target_percent(security, 1.0/len(context.longs.index))
# Order securities not in the portfolio
for security in context.portfolio.positions:
if get_open_orders(security):
continue
if security in data:
if security not in (context.longs.index):# | context.shorts.index):
order_target_percent(security, 0)