我正在尝试使用Python从Yahoo Finance上的可持续分析中获取ESG历史数据。具体地说,假设我想要给定的选民列表中最近10年的ESG分数。
以下代码行提供了最新的ESG分数。但我想刮刮过去-ESG的表现。我基本上是寻找每年(每月,如果可能的话) ESG从2010年1月到2020年12月。我想自动抓取并将数据保存在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它返回标准普尔500指数成分股的ESG数据帧,我们可以使用该数据帧进行分析。其背后的想法是创建“好的”和“坏的”ESG公司的投资组合,并比较业绩,以了解股价在不同历史时期的表现。
到目前为止,这些代码无法获取过去日期的ESG数据。
发布于 2021-05-04 23:49:51
有一个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发布于 2021-10-20 10:57:09
我无法使用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
https://stackoverflow.com/questions/67378377
复制相似问题