簡體   English   中英

如何從雅虎獲取歷史 ESG 數據?

[英]How to fetch historical ESG data from Yahoo?

我正在嘗試使用 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 行 dataframe。

標准普爾 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 數據 dataframe,我們可以將其用於分析。 背后的想法是創建“好”和“壞” 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

我無法使用 requests.get 因為連接被禁止。 錯誤 403。所以我嘗試使用下面 StackOverflow 板上的 urllib.request.urlopen。 訪問Python; urllib 錯誤:AttributeError: 'bytes' object 沒有屬性 '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())

代碼的rest改編自putty

雅虎財經是否提供英國/美國金融公司的歷史 ESG 分數? 我希望它們用於我的研究。 如果他們願意,可以購買月度計划。 似乎是每月 35 美元,免費使用 14 天

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM