【问题标题】:How to fetch historical ESG data from Yahoo?如何从雅虎获取历史 ESG 数据?
【发布时间】:2021-05-04 03:23:52
【问题描述】:

我正在尝试使用 Python 从 Yahoo Finance 上的 Sustainalytics 抓取历史 ESG 数据。具体来说,假设我想要给定成分表最近 10 年的 ESG 分数。

以下代码行提供了最新的 ESG 分数。但我想了解过去的 ESG 表现。我基本上是在寻找从 2010 年 1 月到 2020 年 12 月的年度(如果可能的话,每月)ESG。我想自动抓取并将数据保存在 txt 或 csv 文件中。

# import yfinance, pandas and os
import yfinance as yf
import pandas as pd
import os

单个代码的代码:

msft = "MSFT"
msft_y = yf.Ticker(msft)
esg_data = pd.DataFrame.transpose(msft_y.sustainability)
esg_data['company_ticker'] = str(msft_y ticker)

它返回一个包含 Microsoft 的 ESG 相关信息的 27 行数据框。

标准普尔 500 指数代码:

# Import list of tickers from file
os.chdir("C:\...")
sp_500 = pd.read_csv('SP_500_tickers.csv')
# Retrieve Yahoo! Finance Sustainability Scores for each ticker
for i in sp_500['ticker_code']:
    # print(i)
    i_y = yf.Ticker(i)
    try:
        if i_y.sustainability is not None:
            temp = pd.DataFrame.transpose(i_y.sustainability)
            temp['company_ticker'] = str(i_y.ticker)
            # print(temp)
            esg_data = esg_data.append(temp)
    except IndexError:
        pass

它返回 S&P500 成分股的 ESG 数据数据框,我们可以将其用于分析。背后的想法是创建“好”和“坏” ESG 公司的投资组合,并比较业绩,以了解股价在不同历史时期的表现。

到目前为止,这些代码无法获取过去日期的 ESG 数据。

【问题讨论】:

  • yfinance 是否附带有关历史时期的文档?

标签: python pandas web-scraping yahoo-finance


【解决方案1】:

您可以使用 Yahoo Finance 端点,该端点应该会为您提供每月 ESG 分数、治理分数、环境分数和社会分数。但不要认为它可以追溯到那么远:

import pandas as pd
import requests

# Read in your symbols
sp_500 = pd.read_csv("SP_500_tickers.csv")

# Endpoint
url = "https://query2.finance.yahoo.com/v1/finance/esgChart"

# List of dataframes
dataframes = []

for symbol in sp_500["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.head()
   timestamp  esgScore  governanceScore  environmentScore  socialScore symbol
0 2014-09-01      61.0             62.0              74.0         45.0   AAPL
1 2014-10-01      60.0             62.0              74.0         45.0   AAPL
2 2014-11-01      61.0             62.0              74.0         45.0   AAPL
3 2014-12-01      61.0             62.0              74.0         45.0   AAPL
4 2015-01-01      61.0             62.0              74.0         45.0   AAPL

【讨论】:

  • 这太棒了!谢谢
【解决方案2】:

由于连接被禁止,我无法使用 requests.get。错误 403。所以我尝试使用下面 StackOverflow 板上的 urllib.request.urlopen。 访问Python; urllib error: AttributeError: 'bytes' object has no attribute 'read'

import pandas as pd
from datetime import datetime as dt
import urllib.request
import json
dataframes = []
url = "https://query2.finance.yahoo.com/v1/finance/esgChart?symbol=A"

connection = urllib.request.urlopen(url)

data = connection.read()
data_2 = json.loads(data)
Formatdata = data_2["esgChart"]["result"][0]["symbolSeries"]
Formatdata_2 = pd.DataFrame(Formatdata)
Formatdata_2["timestamp"] = pd.to_datetime(Formatdata_2["timestamp"], unit="s")

预览打印数据如putty所示

print(Formatdata_2.head())

其余代码改编自putty

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    • 2021-06-03
    • 2018-04-21
    • 2015-05-07
    • 1970-01-01
    相关资源
    最近更新 更多