@jaylin.bartell
To iterate through pandas-datareader and create multiple dataframes for each stock ticker, you can use a loop to fetch data for multiple tickers and store them in individual dataframes. Here's an example code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import pandas as pd
import pandas_datareader.data as web
tickers = ['AAPL', 'GOOGL', 'MSFT'] # list of stock tickers
dfs = {} # empty dictionary to store dataframes
for ticker in tickers:
try:
# Fetch data using pandas-datareader
data = web.DataReader(ticker, 'yahoo', start='2021-01-01', end='2021-12-31')
# Create a dataframe for the ticker
dfs[ticker] = data
except Exception as e:
print(f"Error retrieving data for {ticker}: {str(e)}")
# Access individual dataframes by ticker key
for ticker, df in dfs.items():
print(f"Data for {ticker}:")
print(df.head()) # printing first 5 rows as an example
print('
')
|
In this code, tickers is a list of stock symbols or tickers for which you want to fetch the data. You can modify this list to include your desired tickers.
The loop iterates through each ticker, fetches the financial data using pandas-datareader's DataReader function, and stores it in a dictionary called dfs, with the ticker symbol as the key and the dataframe as the value.
You can then access the individual dataframes by iterating through the dfs dictionary using .items() method. In the example, it will print the first 5 rows of each dataframe.
Note that this code fetches data from Yahoo Finance. Make sure you have the necessary dependencies installed (pandas, pandas-datareader) and an internet connection to access the data source.