-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhistorical_sp500_data.py
More file actions
executable file
·35 lines (27 loc) · 998 Bytes
/
Copy pathhistorical_sp500_data.py
File metadata and controls
executable file
·35 lines (27 loc) · 998 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Import dependencies
import pandas_datareader.data as pdr
import yfinance as yf
import datetime as dt
import pandas as pd
import yahoo_fin.stock_info as si
# Set up Yahoo Finance API
yf.pdr_override()
# Get S&P500 tickers from Yahoo Finance
tickers = si.tickers_sp500()
# Replace any periods in ticker names with hyphens
tickers = [item.replace('.', '-') for item in tickers]
# Set number of years of historical data to retrieve
num_of_years = 10
# Calculate start date for retrieving historical data
start = dt.date.today() - dt.timedelta(days=int(365.25*num_of_years))
# Loop through tickers and retrieve historical data using Yahoo Finance API
for ticker in tickers:
try:
df = pdr.get_data_yahoo(ticker, start)
# Save historical data to a CSV file
output_path = f'{ticker}.csv'
df.to_csv(output_path)
print(f'{ticker} historical data saved to {output_path}')
except:
# If an error occurs, skip to the next ticker
continue