简体   繁体   中英

How do I change string indices to integers in this program?

I am trying to call on yfinance to get the top 50 holdings of QQQ to run some back testing. However, everytime I run this portion of the code i get the same error saying: "TypeError: string indices must be integers"

import yfinance as yf
import pandas as pd

# QQQ ETF symbol
etf_symbol = "QQQ"

# Retrieve the top 50 holdings of the ETF
qqq = yf.Ticker(etf_symbol)
top_50_holdings = qqq.info.get("holdings")[:50]
top_50_symbols = [holding.get("symbol") for holding in top_50_holdings]

Can someone please help with as I do not understand how to fix it.

thankyou

I expected to get the top weighted stocks according to yahoo finance but I think because the ticker symbols are strings its causing a massive halt.

Probably you didn't install Yfinance correctly : I install and use your code it worked.

import yfinance as yf
import pandas as pd

# QQQ ETF symbol
etf_symbol = "QQQ"

# Retrieve the top 50 holdings of the ETF
qqq = yf.Ticker(etf_symbol)
top_50_holdings = qqq.info.get("holdings")[:50]
top_50_symbols = [holding.get("symbol") for holding in top_50_holdings]

print("TOP 50 HOLDING :" ,top_50_holdings)
print("TOP 50 SymBols :", top_50_symbols)

and this is an answer:

TOP 50 HOLDING: [{'symbol': 'AAPL', 'holdingName': 'Apple Inc', 'holdingPercent': 0.11270001}, {'symbol': 'MSFT', 'holdingName': 'Microsoft Corp', 'holdingPercent': 0.1011}, {'symbol': 'AMZN', 'holdingName': 'Amazon.com Inc', 'holdingPercent': 0.0779}, {'symbol': 'GOOG', 'holdingName': 'Alphabet Inc Class C', 'holdingPercent': 0.0419}, {'symbol': 'FB', 'holdingName': 'Facebook Inc Class A', 'holdingPercent': 0.0404}, {'symbol': 'TSLA', 'holdingName': 'Tesla Inc', 'holdingPercent': 0.039}, {'symbol': 'GOOGL', 'holdingName': 'Alphabet Inc Class A', 'holdingPercent': 0.0387}, {'symbol': 'NVDA', 'holdingName': 'NVIDIA Corp', 'holdingPercent': 0.0378}, {'symbol': 'PYPL', 'holdingName': 'PayPal Holdings Inc', 'holdingPercent': 0.023}, {'symbol': 'ADBE', 'holdingName': 'Adobe Inc', 'holdingPercent': 0.0215}] TOP 50 SymBols: ['AAPL', 'MSFT', 'AMZN', 'GOOG', 'FB', 'TSLA', 'GOOGL', 'NVDA', 'PYPL', 'ADBE']

To check if your libraries work or install correctly, Please once again try to install from the terminal with this:

pip3 install yfinance

or

pip install yfinance

the docs are here: https://pypi.org/project/yfinance/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM