从Yahoo Finance下载股票信息的小程序

来源: 2024-01-08 11:36:29 [博客] [旧帖] [给我悄悄话] 本文已被阅读:

这几天工作不忙闲着玩ChatGPT,请教怎么下载股票信息。

 

 

Stock Return from 12/29/2023 to 1/5/2024
Ticker Start Price End Price Price Return Dividend Return Gross Return
AAPL 192.53 181.91 -5.52%   -5.52%
NVDA 495.22 479.98 -3.08%   -3.08%
PFE 28.79 29.09 1.04%   1.04%
"""Python program to download stock price from Yahoo Finance and calculate return"""

import yfinance as yf
import pandas as pd
import datetime

def get_period_return(tickers: list[str], start_date: datetime.date, end_date: datetime.date) -> pd.DataFrame:
    hist = yf.download(tickers=tickers, start=f'{start_date:%Y-%m-%d}', end=f'{end_date:%Y-%m-%d}', actions=True)
    hist.fillna(method='backfill', inplace=True)
    d0 = hist.index[0]
    d1 = hist.index[-1]
    p0 = hist.loc[d0, 'Close']
    p1 = hist.loc[d1, 'Close']
    p_rt = p1/p0 - 1
    dvd = hist.loc[:, ('Dividends', slice(None))].sum()
    dvd.index = dvd.index.get_level_values(level=1)
    dvd_rt = dvd/p0
    g_rt = p_rt + dvd_rt
    p0.name = f'Start Price'
    p1.name = f'End Price'
    p_rt.name = f'Price Return'
    dvd_rt.name = f'Dividend Return'
    g_rt.name = f'Gross Return'
    
    res = pd.concat([p0, p1, p_rt, dvd_rt, g_rt], axis=1)
    res = res.rename_axis('Ticker').reset_index()
    
    res.loc[res['Dividend Return']==0, 'Dividend Return'] = pd.NA
    return res

# Usage
start_date = datetime.date(2023, 12, 29)
end_date = datetime.date(2024, 1, 5)
tickers = ['AAPL', 'PFE', 'NVDA']

period_return = get_period_return(tickers, start_date, end_date)

# do whatever you want with period_return dataframe.  e.g.
period_return.to_clipboard()
# and then paste to spreadsheet