You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何使用Python解析Yahoo Finance嵌套JSON以获取指定股票数据字段

如何使用Python解析Yahoo Finance嵌套JSON以获取指定股票数据字段

嗨,我明白你现在遇到的问题了——Yahoo Finance返回的JSON结构确实有点嵌套复杂,你之前的代码报错主要是没搞清楚它的层级结构,我来帮你拆解一下并修正代码。

首先,我们先理清Yahoo Finance返回的JSON核心层级:

  • 顶层的data是一个字典,核心数据在chart键下
  • chart里的result列表类型(即使只返回一天的数据,它也是列表),所以需要先取列表的第一个元素result[0]
  • 你要的几个字段分布在两个子结构里:metaindicators

修正后的完整代码

import requests
import json

def fetch_yahoo_finance_data(ticker):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'
    }
    # 把ticker作为参数传入,方便复用函数
    url = f"https://query1.finance.yahoo.com/v8/finance/chart/{ticker}?interval=1d&range=1d"
    response = requests.get(url, headers=headers)
    
    if response.status_code == 200:
        return response.json()
    else:
        print(f"Failed to fetch data. Status Code: {response.status_code}")
        return None

# 测试用的股票代码,比如GGUS.AX、ETPMPM.AX
data = fetch_yahoo_finance_data("GGUS.AX")

if data:
    # 先检查result是否存在且不为空
    if 'chart' in data and 'result' in data['chart'] and len(data['chart']['result']) > 0:
        result_data = data['chart']['result'][0]
        
        # 获取regularMarketPrice
        regular_market_price = result_data['meta'].get('regularMarketPrice', 'N/A')
        print(f"Regular Market Price: {regular_market_price}")
        
        # 获取open、close、volume
        if 'indicators' in result_data and 'quotes' in result_data['indicators'] and len(result_data['indicators']['quotes']) > 0:
            quotes = result_data['indicators']['quotes'][0]
            open_price = quotes.get('open', 'N/A')
            close_price = quotes.get('close', 'N/A')
            volume = quotes.get('volume', 'N/A')
            
            print(f"Open Price: {open_price}")
            print(f"Close Price: {close_price}")
            print(f"Volume: {volume}")
        else:
            print("No quotes data found")
    else:
        print("No valid result data found")
else:
    print("Failed to retrieve data")

关键说明

  1. 层级修正:你之前的错误写法data['chart'][0]['result']是搞反了层级,正确的是data['chart']['result'][0]——因为chart是字典,result是它的键,对应的值是列表。
  2. 安全取值:我用了.get()方法来获取字段,而不是直接用键索引,这样如果某个字段不存在(比如API返回结构变化),程序不会直接崩溃,而是返回你指定的默认值(比如'N/A')。
  3. 函数复用:把股票代码改成函数参数,这样你可以轻松切换不同的ASX股票(比如NDQ.AX、PME.AX、WOW.AX)。

为什么你之前的循环没效果?

因为顶层的data只有charterror两个键,直接遍历data.items()只会打印这两个顶层键,看不到深层的嵌套数据。如果要遍历所有嵌套字段,需要写递归函数,但对于你的需求来说,直接按指定路径提取字段更高效。

备注:内容来源于stack exchange,提问作者Craig

火山引擎 最新活动