Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
portfolio optimizations

Can someone help me with portfolio optimizations,
I know it is a requirement for allocation so how do I implement it into

def Market_Order(context,data,parameter6,parameter7):
#Market_Order(context,data,stock.symbol,round(expected_capital))
stock=parameter6
price_start=data.history(stock, 'open',1,'1m')
price_current=data.current(stock,'price')
varI=bool(price_start[0]<=price_current)
var_v=True#
if varI:

    price_history = data.history(stock, "price", 15, frequency="1m")  
    mean_15=price_history[-10]  
    current_price= data.current(stock, 'price')

    Stop_loss=(current_price - (current_price * 0.11))  

    sym=parameter6  

    #stock_TX= sym not in context.container  
    order_check=len(get_open_orders(stock.symbol))  
    StockTK= sym not in context.portfolio.positions

    #Stk_Traded= ((StockTK) &  (stock_TX) &(order_check == 0))  
    Stk_Traded= ((StockTK) &(order_check == 0))

    Allotment= parameter7  
    #Allotment= (50000/len(context.results.index))  
    B4_Order_check=bool((data.can_trade(stock)) & (order_check == 0) & (context.account.leverage==0))    

    if (B4_Order_check):  
        #context.container.append(stock.symbol)  
        if (current_price > mean_15): #and (current_position > 0):        

            ALot_Bal=context.balance - Allotment  
            Volume= round(Allotment/current_price)  
            context.balance =ALot_Bal

            order_value(stock,Volume,style=StopLimitOrder(limit_price=current_price, stop_price=Stop_loss))  
            context.orders_placed=context.orders_placed+1  
            Current_time= pd.Timestamp(get_datetime()).tz_convert('US/Eastern')  
            Current_hour= Current_time.hour  
            Current_minute= Current_time.minute  
            Current_TV= ((60)*Current_hour)+Current_minute

            context.spend.append(context.balance)  
            context.funds.append(context.account.settled_cash)

            security= stock  
            context.timex[sym]= Current_TV 

Thank you in advance

1 response

Take a look here https://www.quantopian.com/posts/optimize-api-generally-available and especially this notebook https://www.quantopian.com/research/notebooks/Tutorials%20and%20Documentation/4.%20Tutorial%20-%20Optimize%20API.ipynb

Those, along with the links within the post, should give you a good start on using the optimize methods.

However, a couple of things to note especially regarding the above posted code. The 'order_optimal_portfolio' method only places market orders. The above code places a StopLimitOrder. Can't replicate that exactly. Also, the above code determines the order volume and places orders for those volumes. The 'order_optimal_portfolio' method really thinks in terms of 'weights' or dollar-volume percentage of the current portfolio. One would need to convert volume to a portfolio weight. (FYI, the above code should be using the 'order' method and not the 'order_value' method. 'order' will order a specific number of shares. 'order_value' will order a specific dollar amount. )

Within the optimize framework one can use a lot or just a little of the actual 'optimization'. Specifically, one could simply use the 'TargetWeights' objective without any constraints. This will place appropriate market orders so the portfolio has the desired securities with the desired weights. There's a lot of power with adding constraints but one isn't required to use them. Some practical benefits of using optimize is that it checks for outstanding orders before placing new orders, it checks if a security can trade, and it closes out any unwanted held positions. No need to explicitly code for those. Also, it places all orders at once so no need to loop through desired trades. In most cases optimize should simplify the ordering process.

So, I haven't captured all the logic in the above snippet of code, but here is a stab at implementing something using optimize. Note that there wasn't a mechanism to close a position in the above code so this simply closes all positions that it's not trying to open. Also, the above logic relies on the StopLimitOrder to do some 'logic' in the background. This would need to be explicitly coded since optimize only places market orders.

def before_trading_start(context, data):  
    # Get the data and create a list of the stocks  
    context.output = pipeline_output('my_pipeline')  
    context.securities_to_hold = context.output.index.tolist()  


    # Next create a column with a weight for each stock  
    # Here we assume equal weighting  
    # Note that if equal weights are desired then there is  
    # the PositionConcentration constraint that could be used  
    # The following is the most general. Each weight could be set individually.  
    context.output['weight'] = 1.0 / len(context.securities_to_hold)  


def rebalance(context, data):  
    # Set the weight of any stock we don't want to hold to 0.  
    # Get prices and set columns to desired values  
    prices = data.history(context.securities_to_hold, "price", 15, frequency="1m")  
    context.output['current_price'] = prices.iloc[-1]  
    context.output['previous_price'] = prices.iloc[-10]  


    # Now easily select which stocks we want to close  
    close_these = context.output.query('current_price <= previous_price')  
    #Set the weights of the stocks we want to close to 0  
    context.output.loc[close_these.index, 'weight'] = 0.0  


    # Next create a TargetWeights object using our weights  
    # This will become our ordering objective  
    context.equal_weight_objective = opt.TargetWeights(context.output.weight)  


    # Finally, execute the order_optimal_portfolio method  
    # No need to loop through the stocks.  
    # The order_optimal_portfolio does all the ordering at one time  
    # Also closes any positions not in 'securities_to_hold'  
    order_optimal_portfolio(objective = context.equal_weight_objective,  
                            constraints = [])