newby

Hi!
I am new to coding and algo.
I just want to start with a simple momentum strategy 12m and go Long 20 stocks equal weight from total us market available at quantopian.
How would I do that?
Thanks,
Paul

4 responses

rebalanced monthly

6 months lookback, 3 months Holding period. Rebalancing first trading day of 02/05/08/22

2
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
'''
Simple algorithm with quarterly rebalance.
'''

# import pipeline methods
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline

# import built in factors and filters
import quantopian.pipeline.factors as Factors
import quantopian.pipeline.filters as Filters

# import optimize
import quantopian.optimize as opt

# import any datasets we need
from quantopian.pipeline.data.builtin import USEquityPricing

# import numpy and pandas just in case
import numpy as np
import pandas as pd

# define any constants.
TOTAL_STOCKS = 26

def initialize(context):
"""
Called once at the start of the algorithm.
"""

# Create and attach pipeline to get data
attach_pipeline(my_pipeline(), name='my_pipeline')

schedule_function(
rebalance,
date_rules.month_start(),
time_rules.market_open())

schedule_function(
record_and_log,
date_rules.every_day(),
time_rules.market_close())

def my_pipeline():

returns_6_mo = Factors.Returns(window_length = 126)
top_returns = returns_6_mo.top(TOTAL_STOCKS, mask = Filters.Q1500US())

return Pipeline(screen = top_returns)

context.output = pipeline_output('my_pipeline')
# These are the securities that we are interested in trading.
context.security_list = context.output.index

total_stocks = len(context.security_list)

# Create weights (equal weighted)
context.output = context.output.assign(weights = 1.0/total_stocks)

def rebalance(context, data):
current_month = get_datetime().month

if current_month not in [2,5,8,11]:
return
else:

# Create a target weight objective
weight_objective = opt.TargetWeights(context.output.weights)

# Execute the order_optimal_portfolio method with above objective and constraint
order_optimal_portfolio(objective = weight_objective, constraints = [])

def record_and_log(context, data):

record(positions=len(context.portfolio.positions))
There was a runtime error.

Would be nice to exclude the most recent month from lookback period. Also a trend filter could be added in order to avoid the big drawdown of 62% in 2008

I did not design the algo. Found it in a post and adapted it accordingly