Back to Community
Alternative for 'order_target_percent'

Hello,

In short, I would like to convert the 'order_target_percent' function to a simple 'order' function.

So, instead of: order_target_percent(stock, weight)
I would like to write: order(stock, num_of_shares)

Also, I would like to sell any shares that I own but need to sell.

Is anyone so kind to post the code for how to do the transition, please?

3 responses

This may help.

I came up with this.
It shows the same results (very very close, about 0.2% less returns in a year) than 'order_target_percent'.
However I'm sure it can be improved

# context.assets is a dictionary: stock:weight  
# context.prices is a list


def rebalance(context, data):  
    portfolio_value = context.portfolio.portfolio_value  
    n = 0  
    for stock, weight in context.assets.items():  
        curr_price = data.current(stock, 'price')  
        context.prices.insert(n, curr_price)  
        n = n + 1  
        #log.info(stock)  
    n = 0  
    for stock, weight in context.assets.items():  
        amount = context.portfolio.positions[stock].amount  
        #cost_basis = context.portfolio.positions[stock]['cost_basis']  
        to_hold = int((portfolio_value * (weight*context.target_leverage) ) / context.prices[n])  
        to_fill = to_hold - amount  
        order(stock, to_fill)  
        n = n + 1  
        #log.info(stock)  

Just an update.

def order_target_percent_manual(context, data, stock, weight):  
    portfolio_value = context.portfolio.portfolio_value

    curr_price = data.current(stock, 'price')  
    amount = context.portfolio.positions[stock].amount  
    to_hold = int(round((portfolio_value * (weight)) / curr_price))  
    to_fill = to_hold - amount  
    if to_fill != 0:  
        order(stock, to_fill)  
        #log.info('Stock: {}, To fill: {}'.format(stock, to_fill))  
    log.info('Stock: {}, Amount: {}, To hold: {}, To fill: {}'.format(stock, amount, to_hold, to_fill))