如何解决股票头寸止盈止损词典
假设我有一个字典 (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。如果他们都不是那个数字,那么显然保持持仓。
解决方法
如下
代码
# 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 {}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。