You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

遍历嵌套列表与字典:批量提取持仓股票新闻标题

批量提取持仓股票新闻标题方案

1. 先明确常见的yfinance新闻数据结构

yfinance返回的单只股票新闻是字典列表,每只股票对应一组这样的列表。常见的两种存储形式:

  • 字典格式:键为股票代码,值是该股票的新闻字典列表
  • 嵌套列表格式:每个元素是包含股票代码和对应新闻列表的字典

模拟示例:

# 字典格式示例
holdings_news_dict = {
    "AAPL": [
        {"title": "苹果发布新MacBook Pro", "publisher": "CNBC"},
        {"title": "Q3营收超市场预期", "publisher": "路透"}
    ],
    "MSFT": [
        {"title": "微软AI业务季度增长30%", "publisher": "华尔街日报"}
    ]
}

# 嵌套列表格式示例
holdings_news_list = [
    {"symbol": "AAPL", "news": [{"title": "iOS 17正式推送"}, {"title": "供应链成本下降"}]},
    {"symbol": "MSFT", "news": [{"title": "Copilot企业版用户破5万"}]}
]

2. 两种结构的批量提取代码

针对字典格式的实现

import yfinance as yf

# 你的持仓股票代码列表
holdings = ["AAPL", "MSFT", "GOOG"]

# 第一步:批量获取所有持仓股票的新闻
holdings_news = {}
for symbol in holdings:
    stock = yf.Ticker(symbol)
    holdings_news[symbol] = stock.news  # stock.news返回该股票的新闻字典列表

# 第二步:批量提取每只股票的新闻标题
for symbol, news_list in holdings_news.items():
    print(f"=== {symbol} 当日新闻 ===")
    # 遍历单只股票的所有新闻
    for news in news_list:
        # 先检查title字段存在,避免报错
        if "title" in news:
            print(f"- {news['title']}")
    print("\n")

针对嵌套列表格式的实现

如果你的数据是嵌套列表结构,用下面的代码:

# 假设这是你已获取的嵌套列表数据
holdings_news_list = [
    {"symbol": "AAPL", "news": [{"title": "苹果新品发布会定档"}, {"title": "海外销量增长"}]},
    {"symbol": "MSFT", "news": [{"title": "微软云服务营收创新高"}]}
]

# 批量提取标题
for item in holdings_news_list:
    symbol = item["symbol"]
    news_list = item["news"]
    print(f"=== {symbol} 当日新闻 ===")
    for news in news_list:
        if "title" in news:
            print(f"- {news['title']}")
    print("\n")

3. 实用优化:把标题存入字典备用

如果需要后续使用这些标题,可以把它们整理成字典存储:

all_news_titles = {}
# 以字典格式的数据源为例
for symbol, news_list in holdings_news.items():
    # 用列表推导式提取所有有效标题
    all_news_titles[symbol] = [news["title"] for news in news_list if "title" in news]

# 打印整理后的结果
print(all_news_titles)

内容的提问来源于stack exchange,提问作者ctcodes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 08:53:23