Hi,

I am trying a simple long short algorithm. When I print the number of securities in universe, it shows 300. But when I plot long and short positions the short positions keep rising. Could someone please help.

Best regards,

Pravin

Clone Algorithm

5

Loading...

There was an error loading this backtest.
Retry

Backtest from
to
with
initial capital

Cumulative performance:

Algorithm
Benchmark

Custom data:

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, order_optimal_portfolio from quantopian.pipeline import Pipeline from quantopian.pipeline.factors import CustomFactor, RollingLinearRegressionOfReturns from quantopian.pipeline.data.builtin import USEquityPricing from quantopian.pipeline.data import morningstar from quantopian.pipeline.classifiers.morningstar import Sector from quantopian.pipeline.factors import Latest, Returns import quantopian.experimental.optimize as opt from scipy.stats.mstats import zscore from scipy.stats import rankdata import numpy as np import pandas as pd from quantopian.pipeline.filters import Q1500US from quantopian.pipeline.data.sentdex import sentiment as sentdex from quantopian.pipeline.data.psychsignal import stocktwits as psychsignal from quantopian.pipeline.data.zacks import EarningsSurprises # Constraint Parameters MAX_GROSS_LEVERAGE = 1.0 NUM_LONG_POSITIONS = 150 NUM_SHORT_POSITIONS = 150 MAX_SHORT_POSITION_SIZE = 1.0/(NUM_LONG_POSITIONS + NUM_SHORT_POSITIONS) MAX_LONG_POSITION_SIZE = 1.0/(NUM_LONG_POSITIONS + NUM_SHORT_POSITIONS) # Risk Exposures MAX_SECTOR_EXPOSURE = 0.01 MAX_BETA_EXPOSURE = 0.01 class PsychSignalMessages(CustomFactor): inputs = [psychsignal.bull_scored_messages, psychsignal.bear_scored_messages] window_length = 10 def compute(self, today, assets, out, bull_msgs, bear_msgs): np.mean(bull_msgs + bear_msgs, axis=0, out=out) def make_factors(): class PsychSignal(CustomFactor): inputs = [psychsignal.bull_minus_bear] window_length = 1 def compute(self, today, assets, out, bull_minus_bear): out[:] = preprocess(bull_minus_bear[-1]) class AvgSentiment(CustomFactor): inputs=[sentdex.sentiment_signal] window_length=3 def compute(self, today, assets, out, impact): out[:] = preprocess(np.mean(impact, axis=0)) return { 'AvgSentiment': AvgSentiment, 'PyschSignal': PsychSignal, } def make_pipeline(): # Define universe # =============================================== pricing = USEquityPricing.close.latest base_universe = (Q1500US() & (pricing > 5)) message_rank = PsychSignalMessages().rank(ascending=False, mask=base_universe) market_cap = Latest(inputs=[morningstar.valuation.market_cap], mask=500 > message_rank) universe = market_cap.top(10*(NUM_LONG_POSITIONS + NUM_SHORT_POSITIONS)) sector = Sector(mask=universe) # sector needed to construct portfolio # =============================================== factors = make_factors() combined_alpha = None for name, f in factors.iteritems(): if combined_alpha == None: combined_alpha = f(mask=universe) else: combined_alpha = combined_alpha + f(mask=universe) combined_alpha = combined_alpha.rank(ascending=False) longs = combined_alpha.top(NUM_LONG_POSITIONS) shorts = combined_alpha.bottom(NUM_SHORT_POSITIONS) long_short_screen = (longs | shorts) beta = 0.66*RollingLinearRegressionOfReturns( target=sid(8554), returns_length=5, regression_length=260, mask=long_short_screen ).beta + 0.33*1.0 # Create pipeline pipe = Pipeline(columns = { 'combined_alpha':combined_alpha, 'sector':sector, 'market_beta':beta }, screen = long_short_screen) return pipe def initialize(context): context.spy = sid(8554) attach_pipeline(make_pipeline(), 'long_short_equity_template') # Schedule my rebalance function schedule_function(func=rebalance, date_rule=date_rules.every_day(), time_rule=time_rules.market_open(hours=0,minutes=30), half_days=True) # record my portfolio variables at the end of day schedule_function(func=recording_statements, date_rule=date_rules.every_day(), time_rule=time_rules.market_close(), half_days=True) set_commission(commission.PerShare(cost=0.001, min_trade_cost=0)) def before_trading_start(context, data): context.pipeline_data = pipeline_output('long_short_equity_template') def recording_statements(context, data): longs = shorts = 0 for sid in context.portfolio.positions: if context.portfolio.positions[sid].amount > 0: longs += 1 elif context.portfolio.positions[sid].amount < 1: shorts += 1 record(l=longs, s=shorts) def rebalance(context, data): pipeline_data = context.pipeline_data objective = opt.MaximizeAlpha(pipeline_data.combined_alpha) print pipeline_data.combined_alpha.shape[0] constraints = [] constraints.append(opt.MaxGrossLeverage(MAX_GROSS_LEVERAGE)) constraints.append(opt.DollarNeutral()) constraints.append( opt.NetPartitionExposure.with_equal_bounds( labels=pipeline_data.sector, min=-MAX_SECTOR_EXPOSURE, max=MAX_SECTOR_EXPOSURE, )) constraints.append( opt.PositionConcentration.with_equal_bounds( min=-MAX_SHORT_POSITION_SIZE, max=MAX_LONG_POSITION_SIZE )) order_optimal_portfolio( objective=objective, constraints=constraints) def preprocess(a): a[np.isinf(a)] = 0 a = np.nan_to_num(a) return zscore(rankdata(a))