Skip to main content

Hướng dẫn lấy dữ liệu cổ phiếu từ Yahoo Finance bằng Python

· 4 min read

Yahoo Finance là một nguồn dữ liệu tài chính phong phú và miễn phí. Với thư viện yfinance của Python, chúng ta có thể dễ dàng truy cập và phân tích dữ liệu thị trường. Bài viết này sẽ hướng dẫn bạn cách sử dụng yfinance để lấy và xử lý dữ liệu cổ phiếu.

1. Cài đặt và thiết lập

Cài đặt thư viện yfinance

pip install yfinance pandas numpy matplotlib seaborn

Import các thư viện cần thiết

import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime, timedelta

2. Lấy dữ liệu cơ bản

Lấy thông tin cổ phiếu

# Tạo đối tượng Ticker
aapl = yf.Ticker("AAPL")

# Lấy thông tin cơ bản
info = aapl.info
print("Thông tin cơ bản:")
print(f"Tên công ty: {info['longName']}")
print(f"Ngành: {info['industry']}")
print(f"Giá hiện tại: ${info['currentPrice']}")
print(f"Vốn hóa thị trường: ${info['marketCap']:,.2f}")

Thông tin cơ bản

Lấy dữ liệu lịch sử

# Lấy dữ liệu 1 năm gần nhất
hist = aapl.history(period="1y")
print("\nDữ liệu lịch sử:")
print(hist.head())

# Vẽ biểu đồ giá đóng cửa
plt.figure(figsize=(12, 6))
plt.plot(hist.index, hist['Close'])
plt.title('Giá đóng cửa AAPL trong 1 năm')
plt.xlabel('Ngày')
plt.ylabel('Giá ($)')
plt.grid(True)
plt.show()

Dữ liệu lịch sử

3. Lấy dữ liệu nâng cao

Lấy dữ liệu nhiều cổ phiếu

# Định nghĩa danh sách cổ phiếu
tickers = ['AAPL', 'MSFT', 'GOOGL', 'AMZN']

# Lấy dữ liệu cho nhiều cổ phiếu
data = pd.DataFrame()
for ticker in tickers:
stock = yf.Ticker(ticker)
hist = stock.history(period='1y')
data[ticker] = hist['Close']

# Tính toán lợi nhuận hàng ngày
returns = data.pct_change()

# Vẽ biểu đồ so sánh
plt.figure(figsize=(12, 6))
for column in data.columns:
plt.plot(data.index, data[column], label=column)
plt.title('So sánh giá đóng cửa')
plt.xlabel('Ngày')
plt.ylabel('Giá ($)')
plt.legend()
plt.grid(True)
plt.show()

So sánh nhiều cổ phiếu

Lấy dữ liệu theo khoảng thời gian tùy chỉnh

# Định nghĩa khoảng thời gian
start_date = '2020-01-01'
end_date = '2023-12-31'

# Lấy dữ liệu theo khoảng thời gian
hist = aapl.history(start=start_date, end=end_date)

# Tính toán các chỉ số
hist['Daily_Return'] = hist['Close'].pct_change()
hist['Cumulative_Return'] = (1 + hist['Daily_Return']).cumprod()

# Vẽ biểu đồ lợi nhuận tích lũy
plt.figure(figsize=(12, 6))
plt.plot(hist.index, hist['Cumulative_Return'])
plt.title('Lợi nhuận tích lũy AAPL')
plt.xlabel('Ngày')
plt.ylabel('Lợi nhuận tích lũy')
plt.grid(True)
plt.show()

Lợi nhuận tích lũy

4. Phân tích dữ liệu

Phân tích biến động

# Tính toán các chỉ số thống kê
stats = pd.DataFrame({
'Giá trung bình': hist['Close'].mean(),
'Độ lệch chuẩn': hist['Close'].std(),
'Giá cao nhất': hist['Close'].max(),
'Giá thấp nhất': hist['Close'].min(),
'Biến động trung bình': hist['Daily_Return'].std() * np.sqrt(252)
})

print("\nThống kê cơ bản:")
print(stats)

# Vẽ biểu đồ phân phối lợi nhuận
plt.figure(figsize=(12, 6))
sns.histplot(hist['Daily_Return'].dropna(), kde=True)
plt.title('Phân phối lợi nhuận hàng ngày')
plt.xlabel('Lợi nhuận')
plt.ylabel('Tần suất')
plt.show()

Phân tích biến động

Phân tích tương quan

# Tính toán ma trận tương quan
correlation = returns.corr()

# Vẽ biểu đồ nhiệt
plt.figure(figsize=(10, 8))
sns.heatmap(correlation, annot=True, cmap='coolwarm', center=0)
plt.title('Ma trận tương quan giữa các cổ phiếu')
plt.show()

Ma trận tương quan

5. Lấy dữ liệu bổ sung

Lấy dữ liệu tài chính

# Lấy báo cáo tài chính
financials = aapl.financials
balance_sheet = aapl.balance_sheet
cash_flow = aapl.cashflow

print("\nBáo cáo tài chính:")
print(financials.head())

# Vẽ biểu đồ doanh thu
plt.figure(figsize=(12, 6))
plt.bar(financials.columns, financials.loc['Total Revenue'])
plt.title('Doanh thu theo quý')
plt.xlabel('Quý')
plt.ylabel('Doanh thu ($)')
plt.xticks(rotation=45)
plt.show()

Báo cáo tài chính

Lấy dữ liệu cổ tức

# Lấy thông tin cổ tức
dividends = aapl.dividends

# Vẽ biểu đồ cổ tức
plt.figure(figsize=(12, 6))
plt.bar(dividends.index, dividends)
plt.title('Lịch sử cổ tức')
plt.xlabel('Ngày')
plt.ylabel('Cổ tức ($)')
plt.grid(True)
plt.show()

Lịch sử cổ tức

6. Xử lý dữ liệu thời gian thực

Lấy dữ liệu realtime

# Lấy dữ liệu realtime
ticker = yf.Ticker("AAPL")
realtime = ticker.history(period="1d", interval="1m")

# Vẽ biểu đồ giá trong ngày
plt.figure(figsize=(12, 6))
plt.plot(realtime.index, realtime['Close'])
plt.title('Giá AAPL trong ngày')
plt.xlabel('Thời gian')
plt.ylabel('Giá ($)')
plt.grid(True)
plt.show()

Dữ liệu realtime

Kết luận

Thư viện yfinance cung cấp một cách đơn giản và hiệu quả để truy cập dữ liệu tài chính từ Yahoo Finance. Với Python, chúng ta có thể:

  • Lấy thông tin cơ bản về cổ phiếu
  • Truy cập dữ liệu lịch sử
  • Phân tích biến động và tương quan
  • Xem báo cáo tài chính
  • Theo dõi dữ liệu thời gian thực

Tài liệu tham khảo