pythondictionaryfor-loopcomputation

Iterating over a dictionary and computing a result from its contents


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!


Solution

  • 2 observations:

    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).