Home > Mobile >  Iterating over a dictionary and computing a result from its contents
Iterating over a dictionary and computing a result from its contents

Time:10-19

while iterating over the following code, im getting the a wrong result. The result is supposed to be -174.5, yet I am getting -9170.27.

My code is the following:

portfolio = {
  "AAPL": {
    "volume": 10,
    "strike": 154.12
  },
  "GOOG": {
    "volume": 2,
    "strike": 812.56
  },
  "TSLA": {
    "volume": 12,
    "strike": 342.12
  },
  "FB": {
    "volume": 18,
    "strike": 209.0
  }
}

# print(portfolio["TSLA"]["volume"])
# print(portfolio["GOOG"]["strike"])

market = {
  "AAPL":  198.84,
  "GOOG": 1217.93,
  "TSLA":  267.66,
  "FB":    179.06
}

total_pl = 0

for key, value in portfolio.items():
    pl = market[key] - (portfolio[key]["strike"]) * portfolio[key]["volume"]
    total_pl  = pl

print(total_pl)

Any help would be greatly appreciated!

CodePudding user response:

The price difference should be calculated first before being multiplied by volume:

pl = (market[key] - portfolio[key]["strike"]) * portfolio[key]["volume"]

CodePudding user response:

just use value to replace portfolio[key]

for key, value in portfolio.items():
    pl = (market[key] - value["strike"]) * value["volume"]
    total_pl  = pl

CodePudding user response:

2 observations:

  • the formula you are using to calculate PnL per stock pl is wrong - you are essentially subtracting an overall position value (price * size) from a price.
  • There is no need to lookup the dictionary portfolio within the loop (I am referring to portfolio[key]["volume"] and portfolio[key]["strike"])), given that you have already unpacked that using the loop for key, value in portfolio.items(). You could simply call value["volume"] and value["strike"]

In code:

total_pl = 0

for key, value in portfolio.items():
    pl = (market[key] - value["strike"]) * value["volume"]
    total_pl  = pl

You could make it more compact using a list comprehension:

total_pl = sum([v["volume"] * (market[k] - v["strike"]) for k, v in portfolio.items()])

Personally, I would add some sanity checks that you have market feeds for all the stocks in your portfolio, and manage missing feeds in some ways (right now, it would simply return a KeyError).

  • Related