我是 Python 初学者,但在此类在线教程和论坛的帮助下,我能够编写以下代码,提取 S&P 500 中所有名称/股票上个月的定价数据,并将其保存到单独的 csv 文件。
我现在想增强此代码,以继续提取 S&P 500 股票代码的定价数据,同时还将我自己的自定义代码列表添加到 S&P 500 代码中,并提取 S&P 500 中所有代码的定价数据,以及我的自定义列表也是如此。此自定义列表是目前不在标准普尔 500 指数中的感兴趣的公司,例如 SHOP、RIVN、DDOG 等,并且可能会随着时间的推移而变化,但不会频繁变化。
import os
import pandas as pd
import yfinance as yf
import datetime
S_AND_P_URL = 'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'
def get_ticker_data(tickers: list):
'''
Obtain the price data for all tickers specified. Creates a csv file of price data for each
ticker in the data folder.
Parameters
----------
tickers : list
A list of the tickers to download the data for
'''
data = yf.download(
tickers = tickers,
period = '1mo',
interval = '1d',
#start = "2023-02-24", #20 days of data
#end = "2023-03-23", #previous close
group_by = 'ticker',
threads = True,
)
for ticker in tickers:
try:
df = data.loc[:, ticker.upper()].dropna()
df.to_csv(f'data/{ticker}.csv', index = True)
except:
print(f'Ticker {ticker} failed to download.')
return
def get_s_and_p_tickers() -> list:
'''
Get a list of all tickers currently in the S&P 500 index.
'''
return pd.read_html(S_AND_P_URL)[0]['Symbol'].tolist()
if __name__ == '__main__':
# Check if a directory exists called 'data', if not, create it
if not os.path.isdir('data'):
os.mkdir('data')
# Download one csv file per ticker and place it in the data directory
get_ticker_data(get_s_and_p_tickers())
我尝试在“def get_s_and_p_tickers()”块下方添加 .append 或 .extend 行,但没有成功。
我想从 wikipidia 中提取 S&P 500 股票代码列表,然后从我的自定义列表中提取,并继续为每个股票代码下载一个 csv 文件,并将它们放在我拥有的数据目录中。因此,保持已经有效的相同流程,但只需添加第二个股票数据源/列表来下载 csv 文件。
任何建议/帮助将不胜感激。谢谢!
您描述的方法应该有效。尝试替换代码的最后一行
get_ticker_data(get_s_and_p_tickers())
与
ticker_list = get_s_and_p_tickers()
ticker_list += [ ... my own list ..]
get_ticker_data(ticker_list)