股票头寸止盈止损词典

时间:2021-01-16 19:46:37

标签: python dictionary finance stock

假设我有一个字典 (current_price),它不断将值更新为给定股票(键)的最新价格。 在它上面我已经有一本字典,可以保存给定股票的入场价格。 此外,我将止盈和止损设置为特定数字。

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

TP = 15
SL = -10

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

我需要如何遍历 current_price 字典来检查 current_pl 是大于 15 还是小于 -10。如果他们都不是那个数字,那么显然保持持仓。

1 个答案:

答案 0 :(得分:1)

如下

代码

# 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}')

输出

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