从雅虎财经获取 ESG 数据时 df 中的语法无效 [重复]

问题描述 投票:0回答:1

我的 Python 代码有问题。我正在尝试使用 .csv 文件中的 yfinance 和 NASDAQ 代码从 Yahoo Finance 下载历史 ESG 数据。要下载 ESG 数据,我使用以下代码:

import pandas as pd
import yfinance as yf
import time
from random import randint
import yesg
import requests

# Read in your symbols
nasdaq = pd.read_csv('/path/to/file.csv')

# Endpoint(As far as I am concerned endpoint allows to download historical data from Yahoo)
url = "https://query2.finance.yahoo.com/v1/finance/esgChart"

# List of dataframes
dataframes = []

for symbol in nasdaq["ticker_code"]:
    response = requests.get(url, params={"symbol": symbol})
    if response.ok:
        df = pd.DataFrame(response.json()["esgChart"]["result"][0]["symbolSeries"]
        df["symbol"] = symbol
        dataframes.append(df)

df = pd.concat(dataframes)
df["timestamp"] = pd.to_datetime(df["timestamp"], unit="s")

但是 df["symbol"] = symbol 中存在无效的语法错误。我找不到,错误的原因可能是什么。 顺便说一句,连续一个文件路径就没问题了,我只是在这里写了一个路径示例。

python pandas yahoo-finance yfinance
1个回答
-1
投票

您忘记关闭

)
pd.DataFram(...)
但请注意您必须使用
headers
作为
requests
的参数,否则您的请求将被禁止(HTTP 403)。

url = 'https://query2.finance.yahoo.com/v1/finance/esgChart'
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0'}

# List of dataframes
dfs = {}

for symbol in nasdaq['ticker_code']:
    response = requests.get(url, headers=headers, params={'symbol': symbol})
    data = response.json()
    if response.ok:
        df = pd.DataFrame(data['esgChart']['result'][0]['symbolSeries'])
        dfs[symbol] = df

df = pd.concat(dfs, names=['symbol']).reset_index(level='symbol')
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='s')

输出:

>>> df
   symbol  timestamp  esgScore  governanceScore  environmentScore  socialScore
0    AAPL 2014-09-01     61.00            62.00             74.00        45.00
1    AAPL 2014-10-01     60.00            62.00             74.00        45.00
2    AAPL 2014-11-01     61.00            62.00             74.00        45.00
3    AAPL 2014-12-01     61.00            62.00             74.00        45.00
4    AAPL 2015-01-01     61.00            62.00             74.00        45.00
..    ...        ...       ...              ...               ...          ...
91  GOOGL 2022-04-01       NaN              NaN               NaN          NaN
92  GOOGL 2022-05-01     24.32            11.54              1.66        11.12
93  GOOGL 2022-06-01       NaN              NaN               NaN          NaN
94  GOOGL 2022-07-01       NaN              NaN               NaN          NaN
95  GOOGL 2022-08-01     24.14            11.39              1.66        11.10

[384 rows x 6 columns]
© www.soinside.com 2019 - 2024. All rights reserved.