Search code examples
pythonpositiontrading

Position / lot size based on buy entry and stop gap


I'm trying to code in Python my lot size based on a positive order signal. Below is the expected output which was done in excel. The logic is: Lot_size = IF (Order_Signal=1, then Prior_Period_Portfolio_Value * Risk_pct / Stop_gap, elif(Active=0, 0, prior period lot size)) risk_pct=0.02

I'm having a having a hard time to reproduce this in excel, specifically the last component where it refers to the prior period lot size.

enter image description here


Solution

  • It depends on how you store these data in Python. But for simplicity I'll assume each variable is in its own list.

    order_signal = [0,0,...-1,0]
    stop_gap = [0.44,1.13,...1.94,9.06]
    prior_period_portfolio_value = [10000,10000,...9900,9807.5]
    active = [0,0,...1,0]
    lot_size = [0] * len(order_signal)
    risk_pct = 0.02
    
    for i = 1:len(order_signal):
        if order_signal[i] == 1:
            lot_size[i] = prior_period_portfolio_value[i] * risk_pct / stop_gap[i]
        elif active[i] == 0:
            lot_size[i] = 0
        else:
            # just need to be sure this doesn't happen on the first iteration
            lost_size[i] = lot_size[i-1]