Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can use a loop to iterate through a list of tickers and create a Ticker object for each ticker. Then, you can use the Ticker object's methods to retrieve data for each ticker and store it in a dictionary or pandas dataframe. Here's an example:

import yfinance as yf
import pandas as pd

tickers = ['AAPL', 'TSLA', 'GOOG']

# Create dictionary to store data for each ticker
data = {}

# Iterate through tickers and retrieve data
for ticker in tickers:
    # Create Ticker object
    t = yf.Ticker(ticker)

    # Retrieve data using Ticker object's methods
    info = t.info
    history = t.history(period='1y')

    # Store data in dictionary
    data[ticker] = {'info': info, 'history': history}

# Access data dynamically
print(data['AAPL']['info']['sector'])
print(data['TSLA']['history']['Close'].head())

This code creates a Ticker object for each ticker in the tickers list and retrieves the info and 1-year history for each ticker. The data is then stored in a dictionary with the ticker symbol as the key. You can access the data dynamically by specifying the ticker symbol and the type of data you want to retrieve (e.g. data['AAPL']['info']['sector'] to get the sector for AAPL). The example also demonstrates how to access the historical stock prices for TSLA.