Back to Community
Psychsignal Algorithm Using New QTradableStocksUS Universe

Note: This is an updated version of an old algo, simulated over more recent market data.

PsychSignal's StockTwits Trader Mood analyzes trader's messages posted on StockTwits, and provides a measure of bull/bear intensity for securities based on aggregated message sentiment. This dataset includes factors such as number of bullish and bearish messages, bull-to-bear intensity and bull-to-bear message ratio.

Both versions of this algo were inspired by Seong Lee's Social Media Trader Mood Series. Enjoy!

Clone Algorithm
71
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
"""
Psychsignal's StockTwits Trader Mood analyzes trader's messages posted on StockTwits,
and provides a measure of bull/bear intensity for securities based on aggregated message
sentiment.

Psychsignal's factors used in this algorithm:

bull_minus_bear - subtracts the bearish intesity from the
                  bullish intensity [BULL - BEAR] to provide
                  an immediate net score.
"""
import quantopian.algorithm as algo
from quantopian.pipeline import Pipeline
from quantopian.pipeline.factors import SimpleMovingAverage
from quantopian.pipeline.experimental import QTradableStocksUS
from quantopian.pipeline.classifiers.fundamentals import Sector

# Optimize API
# https://www.quantopian.com/help#optimize-api
import quantopian.optimize as opt

# Psychsignal's StockTwits Trader Mood
# https://www.quantopian.com/data/psychsignal/stocktwits
from quantopian.pipeline.data.psychsignal import stocktwits


def initialize(context):
    """
    Use this following function to create and attach your pipeline.
    Scheduling logic and variable initialization also go in here.
    """
    # Constraint Parameters
    context.max_leverage = 1.0
    context.max_pos_size = 0.015
    context.max_sector_exp = 1.0
    context.max_turnover = 0.95

    # Pipeline Definition
    algo.attach_pipeline(make_pipeline(), 'PsychSignal')

    # Schedule rebalance function to run at market open on the first trading
    # day of the week.
    schedule_function(
        rebalance,
        date_rules.week_start(),
        time_rules.market_open(),
    )


def make_pipeline():
    """
    Our pipeline scores securities based on their bull_minus_bear net score.
    Additionally, it includes beta-to-spy and Morningstar's Sector for use
    with the Optimize API.
    """
    # This factor calculates the average [BULL - BEAR] intensity over the past
    # 3 days.
    bull_bear_intensity = SimpleMovingAverage(
        inputs=[stocktwits.bull_minus_bear],
        window_length=3,
    )

    sentiment = bull_bear_intensity.zscore()

    # Define a trading universe:
    universe = QTradableStocksUS() & sentiment.notnull()

    # We will use Morningstar's Sector classifier to enforce sector neutrality
    sector = Sector()

    return Pipeline(
        columns={
            'sentiment': sentiment,
            'sector_map': sector
        },
        screen=universe
    )


def before_trading_start(context, data):
    # Pipeline output
    results = algo.pipeline_output('PsychSignal')

    # Sentiment values for today's trading universe
    context.sentiment = results['sentiment']

    # Sector mapping
    context.sector_map = results['sector_map']


def rebalance(context, data):

    # Our objective is to try to maximize alpha based on
    # sentiment values
    objective = opt.MaximizeAlpha(context.sentiment)

    # This constraint ensures that our portfolio is not overly
    # concentrated in a single security, or a small subset of securities.
    constrain_pos_size = opt.PositionConcentration.with_equal_bounds(
        -context.max_pos_size,
        context.max_pos_size
    )
    
    # Constraint allocations to be equally distributed
    # between long and short positions 
    dollar_neutral = opt.DollarNeutral(tolerance = 0.05)

    # We will cap leverage at 1x
    max_leverage = opt.MaxGrossExposure(context.max_leverage)
    
    # Constraint turnover to be no more than 80%
    max_turnover = opt.MaxTurnover(context.max_turnover)

    # Sector neutrality constraint. Our portfolio should not be over-
    # exposed to any particular sector.
    sector_neutral = opt.NetGroupExposure.with_equal_bounds(
        labels=context.sector_map,
        min=-context.max_sector_exp,
        max=context.max_sector_exp,
    )

    # Rebalance portfolio
    algo.order_optimal_portfolio(
        objective=objective,
        constraints=[
            max_leverage,
            dollar_neutral,
            sector_neutral,
            constrain_pos_size,
            max_turnover
        ]
    )
There was a runtime error.
Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

2 responses

@Ernesto Perez
Hi Ernesto. I cloned it & tried running it but got a message stating: "execution timeout". Please advise...

@Tony,

I just cloned the algorithm to test it on my end, and it didn't raise any errors during simulation. Would you mind opening a support request so we can take a closer look on your end?