Python 如何从雅虎获取历史ESG数据?

Python 如何从雅虎获取历史ESG数据?,python,pandas,web-scraping,yahoo-finance,Python,Pandas,Web Scraping,Yahoo Finance,我正在尝试使用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

我正在尝试使用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)
它返回一个包含27行的数据帧,其中包含Microsoft的ESG相关信息

标准普尔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数据。

您可以使用一个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

yfinance有关于历史时期的文档吗?这太棒了!非常感谢。