Ask Your Question
2

How can I use yfinance's Tickers to retrieve data for several tickers and access them dynamically?

asked 2023-05-17 23:54:52 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-05-18 00:05:01 +0000

devzero gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-17 23:54:52 +0000

Seen: 14 times

Last updated: May 18 '23