Search code examples
pythondictionaryfinancestock

Dictionary for Take Profit and Stop Loss on Stock Positions


Let's say I have a dictionary (current_price) that constantly updates the values as the latest price of a given stock (keys). Above it I already have a dictionary that saves the entry price for the given stock. Additionally, I have a Take Profit and Stop Loss set at a certain number.

entry_price = {'SPY': 350, 'QQQ': 250}
current_price = {'SPY': 367, 'QQQ': 220}

TP = 15
SL = -10

current_pl = {'SPY': ???, 'QQQ': ???}

How would I need to loop through the current_price dictionary to check if the current_pl is more than 15 or less than -10. If none of them are that number, then obviously keep the position open.


Solution

  • As follows

    Code

    # Setup
    entry_price = {'SPY': 350, 'QQQ': 250}
    current_price = {'SPY': 367, 'QQQ': 220}
    
    TP = 15
    SL = -10
    
    # Use dictionary comprehension to update current_pl dictionary
    current_pl = {k:(v-entry_price[k]) for k, v in current_price.items()}
    
    # Simple loop to check thresholds
    for k, v in current_pl.items():
    if v >= TP:
        print(f'Profit    - Symbol {k} Profit {v}')
    elif v <= SL:
        print(f'Stop Loss - Symbol {k} Loss {v}')
    
    # Open positions after applying thresholds
    open_positions = {k:current_price[k] for k, v in current_pl.items() if v < TP and v > SL}
    print(f'Open Positions {open_positions}')
    

    Output

    Profit    - Symbol SPY Profit 17
    Stop Loss - Symbol QQQ Loss -30
    Open Positions {}