Home > Enterprise >  How do I correct my output so that it returns the specified categories with the corresponding ticker
How do I correct my output so that it returns the specified categories with the corresponding ticker

Time:03-26

How do I correct my code so it categorizes my specified dictionaries ('Trash' and 'Tech').

Then add the sum of each ticker's prices of each category?

For example it would output: The string of the category following the sum of dictionary.

Trash: (sum of prices of AMC DOGE-USD, GME)

Tech: (sum of prices of TSLA NIO NVDA)

import requests
import yfinance as yf

portfolios = {'Trash': ['AMC', 'DOGE-USD', 'GME'], 'Tech':['TSLA','NIO','NVDA']}

for tickers in portfolios:
    for tickers in portfolios[tickers]:
        info = yf.Ticker(tickers).info
        marketprice = str(info.get('regularMarketPrice'))
        message= tickers  ","  marketprice
        print(message)
        #print (portfolios)

CodePudding user response:

You need to fix your loop like this:

for category in portfolios:
    sum = 0
    for ticker in portfolios[category]:
        info = yf.Ticker(ticker).info
        marketprice = info.get('regularMarketPrice')
        sum  = marketprice
        message= ticker  ","  str(marketprice)
        print(message)
    print(category   ": "   sum)
  • Related