import pandas from pandas\datareader import data as pdr import yfinance as yfin Override…
- User
import pandas from pandas_datareader import data as pdr import yfinance as yfin
Override pandas_datareader's default method to use yfinance
yf.pdr_override()
Set the start and end dates for the data
start_date = '2008-01-01' end_date = '2023-03-01'
Define the ticker symbols and data sources
ticker_symbols = { '^GSPC': 'yahoo', 'DTB3': 'fred', '^IRX': 'yahoo', 'GC=F': 'yahoo', 'BZ=F': 'yahoo', 'DX-Y.NYB': 'yahoo', 'EURUSD=X': 'yahoo', 'JPY=X': 'yahoo', 'CNY=X': 'yahoo', '^VIX': 'yahoo', }
Define the column names for the master DataFrame
column_names = { '^GSPC': 'S&P500', 'DTB3': '3-Month Treasury', '^IRX': '2-Year Treasury', 'GC=F': 'Gold', 'BZ=F': 'Crude Oil (Brent)', 'DX-Y.NYB': 'Dollar Index', 'EURUSD=X': 'USD/EUR', 'JPY=X': 'USD/JPY', 'CNY=X': 'USD/CNY', '^VIX': 'VIX', }
Create an empty DataFrame to store the data
master_df = pd.DataFrame()
Download data for each ticker symbol and add it to the master DataFrame
for symbol, source in ticker_symbols.items(): try: if source == 'yahoo': data = pdr.get_data_yahoo(symbol, start=start_date, end=end_date, interval='1wk') data = data[['Adj Close']] # Select only the 'Adj Close' column data = data.rename(columns={'Adj Close': symbol}) # Rename the column to the symbol name elif source == 'fred': data = pdr.get_data_fred(symbol, start_date, end_date) data.columns = [symbol] # Rename the column to the symbol name else: raise ValueError(f"Unsupported data source: {source}") print(f"Successfully downloaded {symbol} from {source}")
Calculate the weekly average and ignore NULL values
data = data.resample('W').mean().dropna()
Rename the column to the human-readable name
data = data.rename(columns={symbol: column_names.get(symbol, symbol)}) master_df = pd.concat([master_df, data], axis=1) # Add the data to the master DataFrame except Exception as e: print(f"Failed to download {symbol} from {source}: {e}")
master_df = master_df.fillna(master_df.mean()) master_df
- Assistant
This code downloads financial data for a set of ticker symbols from various sources using the pandas_datareader library and stores it in a master DataFrame. The data is then cleaned by resampling it on a weekly basis, calculating the weekly average, and dropping NULL values. Finally, any remaining NULL values are filled in with the mean of the corresponding column.
The ticker symbols and data sources are defined in the ticker_symbols dictionary, while the column names for the master DataFrame are defined in the column_names dictionary. The code loops through each ticker symbol, downloads the data using the appropriate source, and adds it to the master DataFrame.
It is important to note that the code uses the yfinance library to override pandas_datareader's default method for downloading data from Yahoo Finance. This is because the pandas_datareader library no longer supports Yahoo Finance API access. The yfinance library provides a workaround to this problem.
Overall, this code is useful for downloading and cleaning financial data for a set of ticker symbols from various sources. The resulting master DataFrame can then be used for further analysis and modeling.