How to iterate through pandas-datareader and create multiple dataframes for each stock ticker?

by francisco , in category: Technical Analysis , a month ago

How to iterate through pandas-datareader and create multiple dataframes for each stock ticker?

Facebook Twitter LinkedIn Whatsapp

1 answer

by sherman.carter , a month ago

@francisco 

To iterate through pandas-datareader and create multiple dataframes for each stock ticker, you can follow these steps:

  1. Import the necessary libraries:
1
2
import pandas as pd
import pandas_datareader.data as web


  1. Create a list of stock tickers:
1
tickers = ['AAPL', 'GOOGL', 'MSFT']  # Update with your desired stock tickers


  1. Create an empty dictionary to store the dataframes:
1
stock_dataframes = {}


  1. Iterate through the tickers and retrieve data using pandas_datareader:
1
2
3
for ticker in tickers:
    data = web.DataReader(ticker, 'yahoo', start_date, end_date)  # Update start_date and end_date with your desired date range
    stock_dataframes[ticker] = data


Note: Replace 'yahoo' in web.DataReader() with the appropriate data source if you intend to use a different one.

  1. Accessing the data frames: You can access the data frames of each stock using the stock ticker as the dictionary key. For example, to access the dataframe for 'AAPL', you can use:
1
apple_dataframe = stock_dataframes['AAPL']


Here's the complete example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import pandas as pd
import pandas_datareader.data as web

tickers = ['AAPL', 'GOOGL', 'MSFT']

stock_dataframes = {}

start_date = '2021-01-01'
end_date = '2021-12-31'

for ticker in tickers:
    data = web.DataReader(ticker, 'yahoo', start_date, end_date)
    stock_dataframes[ticker] = data

# Accessing the data frames
apple_dataframe = stock_dataframes['AAPL']
google_dataframe = stock_dataframes['GOOGL']
microsoft_dataframe = stock_dataframes['MSFT']


In this example, each stock ticker is used as the key in the stock_dataframes dictionary, and the corresponding dataframe is assigned as the value.