Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
how do i make it not go above x leverage, (how much leverage for competitions is allowed) and how do i sell shares

""" This is a template algorithm on Quantopian for you to adapt and fill in.
""" from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import AverageDollarVolume
from quantopian.pipeline.filters.morningstar import Q500US
attach_pipeline

def initialize(context):
schedule_function(my_rebalance, date_rules.every_day(), time_rules.market_open(hours=1))
attach_pipeline(make_pipeline(), 'my_pipeline')
pipe= Pipeline()

context.aapl = sid(24)  
context.spy = sid(8554)  
context.googl = sid(46631)  
context.agn = sid(205)  
context.infn = sid(33979)  

def handle_data(context,data):
stocks = symbols('AAPL','SPY','AAPL','GOOG','AGN','INFN',)

for stock in stocks:  
    if get_open_orders(stock): return  
    hist= data.history(stock, 'price', 30, '1d')  
    if  hist[-1] < hist[0:-2].min() and data.can_trade(stock):  
        order_target_percent(stock, 0.5)  
    elif hist[-1] >= hist[0:-2].max()  and data.can_trade(stock):  
        order_target(stock, 5)

record(leverage=context.account.leverage)  

"selling"  
for stock in stocks:  
    if get_open_orders(stock): return  
    hist= data.history(stock, 'price', 30, '1d')  
    if  hist[-1] < hist[0:-2].min() and data.can_trade(stock):  
        order_target_percent(stock, 0.5)  
    elif hist[-1] >= hist[0:-2].max()  and data.can_trade(stock):  
        order_target(stock, 5)  

def make_pipeline():
"""
A function to create our dynamic stock selector (pipeline). Documentation on
pipeline can be found here: https://www.quantopian.com/help#pipeline-title
"""

# Base universe set to the Q500US  
base_universe = Q500US()

# Factor of yesterday's close price.  
yesterday_close = USEquityPricing.close.latest  

pipe = Pipeline(  
    screen = base_universe,  
    columns = {  
        'close': yesterday_close,  
    }  
)  
return pipe  

def before_trading_start(context, data):
results = pipeline_output('my_pipeline')
print results.head(5)
"""
Called every day before market open.
"""
#I MAY NEED THIS context.output = pipeline_output('my_pipeline')

# These are the securities that we are interested in trading each day.  
#COULD NEED THIS context.security_list = context.output.index  

def my_assign_weights(context, data):
"""
Assign weights to securities that we want to order.
"""
pass

def my_rebalance(context,data):
"""
Execute orders according to our schedule_function() timing.
"""
pass

def my_record_vars(context, data):
"""
Plot variables at the end of each day.
"""
pass

"""  
Called once at the start of the algorithm.  
"""  
# Rebalance every day, 1 hour after market open.  
schedule_function(my_rebalance, date_rules.every_day(), time_rules.market_open(hours=1))  

# Record tracking variables at the end of each day.  
schedule_function(my_record_vars, date_rules.every_day(), time_rules.market_close())  

# Create our dynamic stock selector.  

# attach_pipeline(make_pipeline[my_pipeline] )

8 responses

ALSO!!!! WHY IS IT SELLING IF I HAVEN'T PROGRAMMED THAT IN YET! MY LEVERAGE GOES TO ZERO ON BACKTEST AFTER A WHILE

It's easier to read if you attach the backtest to your post

srry there you go, i figured out the selling, but how do i deal with the leverage?

whoops, bad backtest, here's this one

okay, scratch EVERYTHING, how do i keep it below 1 leverage.

It is not easy to really be SURE you're not going over 1x leverage but there is an easy way to make sure it doesn't go too crazy. Just put this at the begining of your rebalancing:

if get_open_orders(): return  

Order execution is not instant, in the timespan between placing an order and having the shares in your account your order_target_percent() does not recognize that you've already placed an order for the shares and it tries to buy more shares. Once it sees that you DO have the shares and then it tries to sell all the extra shares you bought... basically your leverage freaks out and goes to the moon and back... unless you put the above code that abandons your ordering logic if it detects that an order is placed that's unfilled.

okay, thank you, i'm also thinking about incorporating in the buy- if leverage is below x buy

i couldn't implement that quite right, is there anything else i have to do with it?
the get_open_orders thing