米国株(AAPL/NVDA/TSLA)をPythonで分析する完全ガイド

Python実装・コード

米国株はGAFAMや半導体銘柄など世界的に注目度が高く、個人投資家にも人気です。この記事ではyfinanceを使ってApple・NVIDIA・Teslaなどの米国株を分析する完全なコードを紹介します。

米国株の基本的なデータ取得

import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# 主要米国株の一括取得
tickers = ["AAPL", "NVDA", "TSLA", "MSFT", "GOOGL", "AMZN", "META"]
data = yf.download(tickers, period="2y", progress=False)
close = data["Close"]

print("=== 直近5日間の終値 ===")
print(close.tail().round(2))

# 銘柄の詳細情報
ticker = yf.Ticker("NVDA")
info = ticker.info
print("銘柄名:", info.get("longName"))
print("時価総額:", info.get("marketCap"))
print("PER:", info.get("trailingPE"))

個別銘柄の詳細分析

def analyze_stock(ticker_symbol):
    """銘柄の総合分析レポートを生成"""
    ticker = yf.Ticker(ticker_symbol)
    info = ticker.info
    df = ticker.history(period="1y")
    
    market_cap_b = (info.get("marketCap", 0) or 0) / 1e9
    div_yield = (info.get("dividendYield", 0) or 0) * 100
    roe = (info.get("returnOnEquity", 0) or 0) * 100
    
    print(f"銘柄: {info.get('longName', ticker_symbol)}")
    print(f"セクター: {info.get('sector', 'N/A')}")
    print(f"現在値(USD): {info.get('currentPrice', 'N/A')}")
    print(f"時価総額(B): {market_cap_b:.1f}")
    print(f"PER: {info.get('trailingPE', 'N/A')}")
    print(f"PBR: {info.get('priceToBook', 'N/A')}")
    print(f"配当利回り: {div_yield:.2f}%")
    print(f"ROE: {roe:.1f}%")
    print(f"52週高値: {info.get('fiftyTwoWeekHigh', 'N/A')}")
    print(f"52週安値: {info.get('fiftyTwoWeekLow', 'N/A')}")
    
    returns = df["Close"].pct_change().dropna()
    annual_return = returns.mean() * 252
    volatility = returns.std() * np.sqrt(252)
    sharpe = annual_return / volatility
    
    print(f"年率リターン: {annual_return:.1%}")
    print(f"ボラティリティ: {volatility:.1%}")
    print(f"シャープレシオ: {sharpe:.2f}")
    return df

# 主要銘柄を一括分析
for t in ["AAPL", "NVDA", "TSLA", "MSFT"]:
    analyze_stock(t)

テクニカル指標の計算

def add_technical_indicators(df):
    """主要テクニカル指標を追加"""
    df["MA20"] = df["Close"].rolling(20).mean()
    df["MA50"] = df["Close"].rolling(50).mean()
    df["MA200"] = df["Close"].rolling(200).mean()
    
    df["BB_Mid"] = df["Close"].rolling(20).mean()
    df["BB_Std"] = df["Close"].rolling(20).std()
    df["BB_Upper"] = df["BB_Mid"] + 2 * df["BB_Std"]
    df["BB_Lower"] = df["BB_Mid"] - 2 * df["BB_Std"]
    
    delta = df["Close"].diff()
    gain = delta.clip(lower=0).rolling(14).mean()
    loss = (-delta.clip(upper=0)).rolling(14).mean()
    rs = gain / loss
    df["RSI"] = 100 - (100 / (1 + rs))
    
    df["EMA12"] = df["Close"].ewm(span=12).mean()
    df["EMA26"] = df["Close"].ewm(span=26).mean()
    df["MACD"] = df["EMA12"] - df["EMA26"]
    df["Signal"] = df["MACD"].ewm(span=9).mean()
    return df

df_aapl = yf.download("AAPL", period="1y", progress=False)
df_aapl = add_technical_indicators(df_aapl)
print(df_aapl[["Close", "MA20", "RSI", "MACD"]].tail())

複数銘柄の相関分析

import seaborn as sns

tickers = ["AAPL", "NVDA", "TSLA", "MSFT", "GOOGL", "AMD", "AMZN"]
data = yf.download(tickers, period="2y", progress=False)["Close"]
returns = data.pct_change().dropna()

corr_matrix = returns.corr()

plt.figure(figsize=(10, 8))
sns.heatmap(corr_matrix, annot=True, fmt=".2f", cmap="RdYlGn",
            center=0, square=True, linewidths=0.5)
plt.title("米国主要テック株の相関行列(2年間)")
plt.tight_layout()
plt.show()

corr_pairs = corr_matrix.unstack().sort_values(ascending=False)
corr_pairs = corr_pairs[corr_pairs < 1]
print("相関が高いペアTop5:")
print(corr_pairs.head())

バリュエーション比較

def get_valuation_metrics(tickers):
    """主要バリュエーション指標を一覧表示"""
    metrics = []
    for t in tickers:
        info = yf.Ticker(t).info
        metrics.append({
            "Ticker": t,
            "Price(USD)": info.get("currentPrice", "N/A"),
            "MarketCap(B)": round((info.get("marketCap", 0) or 0) / 1e9, 1),
            "PER": round(info.get("trailingPE", 0) or 0, 1),
            "PBR": round(info.get("priceToBook", 0) or 0, 1),
            "ROE(%)": round((info.get("returnOnEquity", 0) or 0) * 100, 1),
            "DivYield(%)": round((info.get("dividendYield", 0) or 0) * 100, 2),
        })
    return pd.DataFrame(metrics).set_index("Ticker")

df_val = get_valuation_metrics(["AAPL", "NVDA", "TSLA", "MSFT", "GOOGL"])
print(df_val.to_string())

累積リターン比較グラフ

def plot_portfolio_performance(tickers, period="2y"):
    data = yf.download(tickers, period=period, progress=False)["Close"]
    normalized = data / data.iloc[0]
    
    plt.figure(figsize=(14, 6))
    for ticker in tickers:
        plt.plot(normalized[ticker], label=ticker, linewidth=2)
    plt.title("累積リターン比較(初期値=1)")
    plt.ylabel("累積リターン")
    plt.legend()
    plt.grid(True, alpha=0.3)
    plt.tight_layout()
    plt.show()

plot_portfolio_performance(["AAPL", "NVDA", "TSLA", "MSFT", "^GSPC"])

まとめ

yfinanceを使うことで米国株の価格・財務・テクニカル指標を無料で取得・分析できます。NVDA・AAPLなどの個別銘柄分析、相関分析、バリュエーション比較まで、Pythonだけで本格的な株式分析ができます。

タイトルとURLをコピーしました