杰瑞科技汇

Python如何使用yahoofinance?

Of course! Using Python to interact with Yahoo Finance is a very common task for financial analysis, data retrieval, and algorithmic trading. There are two main libraries you should know about:

Python如何使用yahoofinance?-图1
(图片来源网络,侵删)
  1. yfinance (Recommended): A popular, reliable, and actively maintained library that acts as a reliable wrapper for Yahoo Finance's data.
  2. pandas-datareader: A general-purpose library for reading data from various sources (including Yahoo Finance), but it can be less reliable as the Yahoo Finance website changes.

We will focus on yfinance as it's the modern standard.


Step 1: Installation

First, you need to install the yfinance library. If you don't have it, open your terminal or command prompt and run:

pip install yfinance

It's also highly recommended to have pandas installed, as yfinance returns data in a pandas DataFrame, which is perfect for analysis.

pip install pandas

Step 2: Basic Usage of yfinance

Let's start with the most common tasks: downloading historical price data and getting basic information about a stock.

Python如何使用yahoofinance?-图2
(图片来源网络,侵删)

A. Downloading Historical Market Data

This is the core function of yfinance. You can get daily, weekly, monthly, or even intraday data.

import yfinance as yf
import pandas as pd
# Define the ticker symbol
# For example: 'AAPL' for Apple, 'MSFT' for Microsoft, 'GOOGL' for Google/Alphabet
ticker_symbol = 'AAPL'
# Create a Ticker object
ticker = yf.Ticker(ticker_symbol)
# Get the historical data for the last year
# You can specify the period (e.g., '1y', '5d', '1mo', 'max')
# or a specific start and end date (YYYY-MM-DD)
hist_data = ticker.history(period='1y')
# Display the first 5 rows of the data
print(hist_data.head())
# You can also specify start and end dates
# hist_data = ticker.history(start='2025-01-01', end='2025-01-01')

Output:

                 Open       High        Low      Close    Volume  Dividends  Stock Splits
Date
2025-12-30  129.400002  130.279999  128.880005  129.949997  67674800        0.0           0.0
2025-01-03  130.279999  132.050003  129.880005  131.960007  99245200        0.0           0.0
2025-01-04  132.440002  132.630005  130.449997  131.059998  92472600        0.0           0.0
2025-01-05  130.029999  131.410004  129.410004  130.789993  77055200        0.0           0.0
2025-01-06  131.270004  131.449997  129.699997  130.419998  84796800        0.0           0.0

B. Getting Stock Information and Details

The Ticker object also provides a wealth of information available on the Yahoo Finance page.

import yfinance as yf
ticker = yf.Ticker('MSFT')
# Get information about the stock (like sector, industry, etc.)
info = ticker.info
print("--- Stock Info ---")
print(f"Sector: {info.get('sector')}")
print(f"Industry: {info.get('industry')}")
print(f"Market Cap: ${info.get('marketCap'):,}")
print(f"Forward P/E: {info.get('forwardPE')}")
print(f"Dividend Yield: {info.get('dividendYield')}")
print("\n" + "="*30 + "\n")
# Get major holders
major_holders = ticker.major_holders
print("--- Major Holders ---")
print(major_holders.head())
# Get institutional holders
institutional_holders = ticker.institutional_holders
print("\n--- Institutional Holders ---")
print(institutional_holders.head())
# Get analyst recommendations
analyst_recommendations = ticker.recommendations
print("\n--- Analyst Recommendations ---")
print(analyst_recommendations.tail())

C. Downloading Data for Multiple Tickers

You can easily get data for a list of stocks at once.

Python如何使用yahoofinance?-图3
(图片来源网络,侵删)
import yfinance as yf
# Define a list of ticker symbols
tickers_list = ['AAPL', 'GOOGL', 'MSFT', 'AMZN']
# Download data for all tickers
data = yf.download(tickers_list, period='1y')
# The result is a MultiIndex DataFrame
print(data.head())
# You can access data for a specific ticker like this
print("\n--- Apple (AAPL) Closing Prices ---")
print(data['Close']['AAPL'].head())

Step 3: Advanced Features

A. Options Data

yfinance can also fetch options chain data (calls and puts).

import yfinance as yf
ticker = yf.Ticker('TSLA')
# Get options expirations
options_expiration_dates = ticker.options
print(f"Available Options Expirations: {options_expiration_dates}")
# Get options chain for a specific expiration date
# The date must be in the format 'YYYY-MM-DD'
opt_chain = ticker.option_chain('2025-12-20')
# The result is an object with two DataFrames: calls and puts
calls = opt_chain.calls
puts = opt_chain.puts
print("\n--- TSLA Call Options (Dec 20, 2025) ---")
print(calls.head())

B. Actions (Splits, Dividends)

The history() method includes actions by default, but you can also get them separately.

import yfinance as yf
ticker = yf.Ticker('VZ') # Verizon has a history of dividends and splits
# Get historical actions (dividends and stock splits)
actions = ticker.actions
print("--- Actions (Dividends/Splits) ---")
print(actions.head())
# You can also get dividends and splits separately
dividends = ticker.dividends
splits = ticker.splits

Important Considerations and Troubleshooting

  1. Data Reliability: Yahoo Finance is a free service. The data is not always 100% perfect or guaranteed. For high-frequency trading or critical financial analysis, you should consider a paid data provider.

  2. Rate Limiting: Be mindful of making too many requests in a short period. Yahoo Finance may temporarily block your IP if you make an excessive number of requests. If you encounter errors, add a small delay between your requests.

  3. Ticker Symbols: Make sure you are using the correct ticker symbol. For example, use '^GSPC' for the S&P 500 index, '^DJI' for the Dow Jones, and '^IXIC' for the NASDAQ.

  4. pandas-datareader Alternative: If yfinance doesn't work for some reason, you can try pandas_datareader. The syntax is slightly different.

    # Using pandas_datareader
    from pandas_datareader import data as pdr
    import yfinance as yf # You still need yfinance as the backend
    import datetime
    # Monkey patch to use yfinance as the source
    yf.pdr_override()
    start = datetime.datetime(2025, 1, 1)
    end = datetime.datetime(2025, 1, 1)
    data = pdr.get_data_yahoo('AAPL', start=start, end=end)
    print(data.head())

Complete Example: Analyzing a Stock

Here is a full script that downloads data, calculates simple moving averages (SMAs), and plots the results.

import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
# 1. Download Data
ticker_symbol = 'SPY' # S&P 500 ETF
ticker = yf.Ticker(ticker_symbol)
hist_data = ticker.history(period='2y')
# 2. Calculate Technical Indicators
# Simple Moving Averages (SMAs)
hist_data['SMA_50'] = hist_data['Close'].rolling(window=50).mean()
hist_data['SMA_200'] = hist_data['Close'].rolling(window=200).mean()
# 3. Plot the Data
plt.figure(figsize=(12, 6))
plt.plot(hist_data['Close'], label='Close Price', color='blue', alpha=0.6)
plt.plot(hist_data['SMA_50'], label='50-day SMA', color='orange')
plt.plot(hist_data['SMA_200'], label='200-day SMA', color='red')
# Add titles and labelsf'{ticker_symbol} Price with 50-day and 200-day SMAs')
plt.xlabel('Date')
plt.ylabel('Price (USD)')
plt.legend()
plt.grid(True)
plt.show()
# 4. Print recent info
print(f"\n--- Recent Data for {ticker_symbol} ---")
print(hist_data.tail())
分享:
扫描分享到社交APP
上一篇
下一篇