pandas 将yfinance历史价格数据添加到没有硬编码日期的框架中(使用框架中已有的日期)

tez616oj  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(154)

下面的代码使用yfinance提取资产负债表数据。我想在最后一行的数据框中获得相应日期的收盘价,而不需要硬编码日期。

import yfinance as yf

ticker_object = yf.Ticker('AAPL')
balancesheet = ticker_object.balancesheet

# Select specific rows and columns
selected_data = balancesheet.loc[['Share Issued', 'Tangible Book Value']]

selected_data

字符串
电流输出:


的数据
所需输出:



下面是获取价格数据的示例代码:

import yfinance as yf

data = yf.download("AAPL", start="2017-01-01", end="2017-04-30")
data.head(3)


输出量:

uwopmtnx

uwopmtnx1#

由于交易在周末关闭,因此将最小日期从3天开始,然后选择Close列并通过DataFrame.locSeries.reindexmethod='ffill'添加新行,因为周五的收盘价将保持到周一开盘。

import yfinance as yf

ticker_object = yf.Ticker('AAPL')
balancesheet = ticker_object.balancesheet

start = balancesheet.columns.min() - pd.Timedelta(3, 'days')
end = balancesheet.columns.max()

data = yf.download("AAPL", period="5y")['Close']

#test data - missing 2023-09-30 because Saturday, so used Friday values
print (data.loc['2023-09-27':'2023-10-03'])
Date
2023-09-27    170.429993
2023-09-28    170.690002
2023-09-29    171.210007
2023-10-02    173.750000
2023-10-03    172.399994
Name: Close, dtype: float64

# Select specific rows and columns
selected_data = balancesheet.loc[['Share Issued', 'Tangible Book Value']]
selected_data.loc['Price'] = data.reindex(index=selected_data.columns, method='ffill')
print (selected_data)
                        2023-09-30     2022-09-30     2021-09-30  \
Share Issued         15550061000.0  15943425000.0  16426786000.0   
Tangible Book Value  62146000000.0  50672000000.0  63090000000.0   
Price                   171.210007     138.199997          141.5   

                        2020-09-30  
Share Issued         16976763000.0  
Tangible Book Value  65339000000.0  
Price                   115.809998

字符串

相关问题