使用yfinance库根据公司名称匹配股票代码时遇到'Ticker'对象不可订阅错误的解决求助
使用yfinance库根据公司名称匹配股票代码时遇到'Ticker'对象不可订阅错误的解决求助
问题描述
我有一个Excel文件,A列是公司名称,想通过Python的yfinance库把匹配的股票代码填充到B列。测试阶段我只保留了一家公司——Adobe, Inc.。
我写了如下代码:
# Import libraries import pandas as pd !pip install yfinance import yfinance as yf import time # Import Existing Excel excel_file_path = 'MyFilePath/Company Ticker Report.xlsx' # Load Excel data excel_df = pd.read_excel(excel_file_path, sheet_name= 'MS LIst') def get_ticker(company_name): for CompanyNamein excel_df: try: ticker_dictionary = yf.Ticker(company_name) print(type(ticker_dictionary)) # confirm type print(ticker_dictionary) # test print dict related_tickers = [] for row in ticker_dictionary['rows']: for news in row['news']: if 'relatedTickers' in news: related_tickers.append(news['relatedTickers']) # This should return the ticker for CompanyName time.sleep(1) # Pause execution of function for one second return related_tickers except Exception as e: print(f"An unexpected error occurred: {e}") # All errors return 'No Info' # Apply the function to the CompanyName column excel_df['Suggested Ticker'] = excel_df['CompanyName'].apply(get_ticker) # Save the updated data back to Excel excel_df.to_excel('Company Ticker Report.xlsx', index=False) display(excel_df) # test print
运行代码时,我发现yf.Ticker(company_name)返回的是<class 'yfinance.ticker.Ticker'>类型的对象,而不是字典,所以执行ticker_dictionary['rows']时触发了错误:An unexpected error occurred: 'Ticker' object is not subscriptable。我尝试用.__dict__把它转成字典,但之后又找不到需要的嵌套数据(比如rows[news[relatedTickers]])。
有没有办法解决这个问题呢?
问题分析与解决方案
核心问题拆解
你踩的坑是对yfinance的Ticker对象用法理解错了:
yf.Ticker()返回的不是普通字典,而是yfinance封装的Ticker类实例,不能直接用下标[]访问属性,得通过类提供的方法或属性来获取数据。- 你想从
rows和news里找relatedTickers的思路不对,因为Ticker对象本身根本不包含这些结构,这可能是混淆了yfinance其他接口的返回格式。
正确实现方式
要实现“公司名称转股票代码”,可以用yfinance自带的搜索功能,这是最直接的方案:
import pandas as pd import yfinance as yf import time # 加载Excel数据 excel_file_path = 'MyFilePath/Company Ticker Report.xlsx' excel_df = pd.read_excel(excel_file_path, sheet_name='MS LIst') def get_ticker(company_name): try: # 调用yfinance的搜索接口,根据公司名查找匹配的股票 search_results = yf.search(company_name) # 提取最匹配的第一个股票代码(搜索结果默认按匹配度排序) if not search_results.empty: matched_ticker = search_results.iloc[0]['symbol'] time.sleep(1) # 加个延迟,避免请求太频繁被限制 return matched_ticker else: return 'No Match' except Exception as e: print(f"处理{company_name}时出错: {e}") return 'No Info' # 把函数应用到公司名列,生成股票代码列 excel_df['Suggested Ticker'] = excel_df['CompanyName'].apply(get_ticker) # 保存更新后的Excel文件 excel_df.to_excel('Company Ticker Report.xlsx', index=False) display(excel_df)
额外说明
- 如果搜索结果有多个匹配项,你可以根据需求加筛选逻辑(比如只保留美股的代码,或者匹配全称)。
- 如果你是已知股票代码,想验证对应的公司名称,可以用Ticker对象的
info属性:ticker = yf.Ticker("ADBE") print(ticker.info['longName']) # 会输出Adobe Inc. - 批量处理大量公司名时,建议保留
time.sleep(),避免触发Yahoo的请求限制。
备注:内容来源于stack exchange,提问作者Nathan Enix




