I am trying to create a basic algorithm in order to understand how to order based on my parameters but also optimize the portfolio and manage the risk according to quantopians rules and to do this to every stock in the qtradeable universe .
I use the talib ema function to create a ema. If the price is above the ema it buys a certain percentage of the asset if below it will sell the asset. It will then use the ATR function of talib to use 1atr as a stop loss and 2 as a profit target. Then reference the rebalance rules to make sure it adheres to quantopians rules.
This is happening on a minutely time frame repeatedly to every stock in the qtradeableuniverse.
I am having a few issues atm. 1 is making sure it doesn't just keep buying the same asset multiple times if it already has a position in it. And 2 telling it when to sell and stop loss.
Here is the full code. I am still learning python im trying to create a shell that I can add variables to and experiment with that adheres to the parameters of quantopian. Any suggestions would be appreciated.
import quantopian.algorithm as algo
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.filters import QTradableStocksUS
import talib
def initialize(context):
#Called once at the start of the algorithm.
# Constraint parameters
context.max_leverage = 1.0
context.max_pos_size = 0.015
context.max_turnover = 0.95
# Rebalance every day, 1 hour after market open.
algo.schedule_function(
rebalance,
algo.date_rules.every_day(),
algo.time_rules.market_open(hours=1),
)
# Record tracking variables at the end of each day.
algo.schedule_function(
record_vars,
algo.date_rules.every_day(),
algo.time_rules.market_close(),
)
# Create our dynamic stock selector.
algo.attach_pipeline(make_pipeline(), 'pipeline')
def make_pipeline():
# Base universe set to the QTradableStocksUS
base_universe = QTradableStocksUS()
# Factor of yesterday's close price.
yesterday_close = USEquityPricing.close.latest
pipe = Pipeline(
columns={
'close': yesterday_close,
},
screen=base_universe
)
return pipe
def before_trading_start(context, data):
#Called every day before market open.
context.output = algo.pipeline_output('pipeline')
def handle_data(context, data):
ema8 = talib.EMA(context.data,'close','1m')
if 'price' > ema8:
trend = 1
elif 'price' < ema8:
trend = 2
else:
trend = 0
price_history = context.data('close','1m')
H = price_history('high', 14, '1m')
L = price_history('low', 14, '1m')
C = price_history('price', 14, '1m')
ATR = talib.atr(H, L, C, 14)
if Trend == 1:
order_percent(.015)
elif Trend == 2:
order_percent(-.015)
else:
Trend = 0
pass
def rebalance(context, data):
#Execute orders according to our schedule_function() timing.
# Retrieve alpha from pipeline output
alpha = context.pipeline_data.alpha
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()
# Constrain portfolio turnover
max_turnover = opt.MaxTurnover(context.max_turnover)
# Constrain target portfolio's risk exposure
# By default, max sector exposure is set at
# 0.2, and max style exposure is set at 0.4
factor_risk_constraints = opt.experimental.RiskModelExposure(
context.risk_factor_betas,
version=opt.Newest
)
# Rebalance portfolio using objective
# and list of constraints
algo.order_optimal_portfolio(
objective=objective,
constraints=[
constrain_pos_size,
max_leverage,
dollar_neutral,
max_turnover,
factor_risk_constraints,
]
)
pass
def record_vars(context, data):
pass