中級者向け No.09

株価トラッカー

Yahoo Finance APIで株価データを取得してチャート表示するアプリ。yfinanceとmatplotlibの活用を学びます。

🎯 難易度: ★★★ 📦 ライブラリ: tkinter(標準ライブラリ), yfinance, matplotlib ⏱️ 制作時間: 30〜90分

1. アプリ概要

Yahoo Finance APIで株価データを取得してチャート表示するアプリ。yfinanceとmatplotlibの活用を学びます。

このアプリは中級カテゴリに分類される実践的なGUIアプリです。使用ライブラリは tkinter(標準ライブラリ)・yfinance・matplotlib で、難易度は ★★★ です。

Pythonでは tkinter を使うことで、クロスプラットフォームなGUIアプリを簡単に作成できます。このアプリを通じて、ウィジェットの配置・イベント処理・データ管理など、GUI開発の実践的なスキルを習得できます。

ソースコードは完全な動作状態で提供しており、コピーしてそのまま実行できます。まずは実行して動作を確認し、その後コードを読んで仕組みを理解していきましょう。カスタマイズセクションでは機能拡張のアイデアも紹介しています。

GUIアプリ開発は、プログラミングの楽しさを実感できる最も効果的な学習方法のひとつです。アプリを作ることで、変数・関数・クラス・イベント処理など、プログラミングの重要な概念が自然と身についていきます。このアプリをきっかけに、オリジナルアプリの開発にも挑戦してみてください。

2. 機能一覧

  • 株価トラッカーのメイン機能
  • 直感的なGUIインターフェース
  • 入力値のバリデーション
  • エラーハンドリング
  • 結果の見やすい表示
  • キーボードショートカット対応

3. 事前準備・環境

ℹ️
動作確認環境

Python 3.10 以上 / Windows・Mac・Linux すべて対応

以下の環境で動作確認しています。

  • Python 3.10 以上
  • OS: Windows 10/11・macOS 12+・Ubuntu 20.04+

インストールが必要なライブラリ

pip install matplotlib

4. 完全なソースコード

💡
コードのコピー方法

右上の「コピー」ボタンをクリックするとコードをクリップボードにコピーできます。

app09.py
import tkinter as tk
from tkinter import ttk, messagebox
import threading
import json
import urllib.request
import urllib.parse
from datetime import datetime, timedelta

try:
    import yfinance as yf
    import matplotlib
    matplotlib.use("TkAgg")
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    import matplotlib.dates as mdates
    LIBS_AVAILABLE = True
except ImportError:
    LIBS_AVAILABLE = False


class App09:
    """株価トラッカー"""

    DEMO_SYMBOLS = ["AAPL", "GOOGL", "MSFT", "AMZN", "META",
                    "TSLA", "NVDA", "7203.T", "6758.T", "9984.T"]
    PERIODS = ["1d", "5d", "1mo", "3mo", "6mo", "1y", "2y", "5y"]
    PERIOD_LABELS = ["1日", "5日", "1ヶ月", "3ヶ月", "6ヶ月", "1年", "2年", "5年"]

    def __init__(self, root):
        self.root = root
        self.root.title("株価トラッカー")
        self.root.geometry("900x620")
        self.root.configure(bg="#1a1a2e")
        self._build_ui()

        if not LIBS_AVAILABLE:
            self.status_var.set(
                "⚠ yfinance・matplotlib が必要です: "
                "pip install yfinance matplotlib")

    def _build_ui(self):
        # ヘッダー
        header = tk.Frame(self.root, bg="#16213e", pady=8)
        header.pack(fill=tk.X)
        tk.Label(header, text="📈 株価トラッカー",
                 font=("Noto Sans JP", 14, "bold"),
                 bg="#16213e", fg="#e2b96f").pack(side=tk.LEFT, padx=12)

        # 検索バー
        search_frame = tk.Frame(self.root, bg="#1a1a2e", pady=8)
        search_frame.pack(fill=tk.X, padx=12)
        tk.Label(search_frame, text="ティッカー:",
                 bg="#1a1a2e", fg="#ccc",
                 font=("Noto Sans JP", 11)).pack(side=tk.LEFT)
        self.symbol_var = tk.StringVar(value="AAPL")
        sym_entry = ttk.Entry(search_frame, textvariable=self.symbol_var,
                              font=("Arial", 12), width=12)
        sym_entry.pack(side=tk.LEFT, padx=8)
        sym_entry.bind("<Return>", lambda e: self._fetch())
        ttk.Button(search_frame, text="取得",
                   command=self._fetch).pack(side=tk.LEFT)

        # プリセット
        for sym in self.DEMO_SYMBOLS:
            tk.Button(search_frame, text=sym, bg="#0f3460",
                      fg="#e2b96f", relief=tk.FLAT, font=("Arial", 9),
                      padx=5, command=lambda s=sym: (
                          self.symbol_var.set(s), self._fetch())
                      ).pack(side=tk.LEFT, padx=2)

        # 期間選択
        period_frame = tk.Frame(self.root, bg="#1a1a2e")
        period_frame.pack(fill=tk.X, padx=12)
        tk.Label(period_frame, text="期間:",
                 bg="#1a1a2e", fg="#ccc").pack(side=tk.LEFT)
        self.period_var = tk.StringVar(value="1mo")
        for p, lbl in zip(self.PERIODS, self.PERIOD_LABELS):
            rb = tk.Radiobutton(period_frame, text=lbl, variable=self.period_var,
                                value=p, bg="#1a1a2e", fg="#ccc",
                                selectcolor="#0f3460", activebackground="#1a1a2e",
                                command=self._fetch)
            rb.pack(side=tk.LEFT, padx=4)

        # 株価情報パネル
        info_frame = tk.Frame(self.root, bg="#16213e", pady=6)
        info_frame.pack(fill=tk.X, padx=12, pady=4)
        self.info_labels = {}
        for key in ["銘柄", "現在値", "前日比", "始値", "高値", "安値", "出来高"]:
            f = tk.Frame(info_frame, bg="#16213e")
            f.pack(side=tk.LEFT, padx=12)
            tk.Label(f, text=key, bg="#16213e", fg="#888",
                     font=("Arial", 9)).pack()
            lbl = tk.Label(f, text="--", bg="#16213e", fg="#e2b96f",
                           font=("Arial", 12, "bold"))
            lbl.pack()
            self.info_labels[key] = lbl

        # チャートエリア
        chart_frame = tk.Frame(self.root, bg="#1a1a2e")
        chart_frame.pack(fill=tk.BOTH, expand=True, padx=12, pady=4)

        if LIBS_AVAILABLE:
            self.fig = Figure(figsize=(9, 4), dpi=90,
                              facecolor="#1a1a2e")
            self.ax = self.fig.add_subplot(111)
            self.ax.set_facecolor("#0f3460")
            self.fig.subplots_adjust(left=0.07, right=0.97,
                                     top=0.9, bottom=0.15)
            self.chart_canvas = FigureCanvasTkAgg(self.fig, master=chart_frame)
            self.chart_canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
        else:
            self.placeholder = tk.Label(
                chart_frame,
                text="yfinance と matplotlib をインストールしてください\n"
                     "pip install yfinance matplotlib",
                bg="#0f3460", fg="#e2b96f",
                font=("Noto Sans JP", 12))
            self.placeholder.pack(fill=tk.BOTH, expand=True)

        self.status_var = tk.StringVar(value="ティッカーシンボルを入力して取得してください")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#16213e", fg="#888", font=("Arial", 9),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    def _fetch(self):
        if not LIBS_AVAILABLE:
            return
        symbol = self.symbol_var.get().strip().upper()
        if not symbol:
            return
        self.status_var.set(f"取得中: {symbol} ...")
        threading.Thread(target=self._load_data, args=(symbol,),
                         daemon=True).start()

    def _load_data(self, symbol):
        try:
            ticker = yf.Ticker(symbol)
            period = self.period_var.get()
            hist = ticker.history(period=period)
            info = ticker.fast_info
            self.root.after(0, self._update_chart, symbol, hist, info)
        except Exception as e:
            self.root.after(0, lambda: self.status_var.set(f"エラー: {e}"))

    def _update_chart(self, symbol, hist, info):
        if hist.empty:
            self.status_var.set(f"データが見つかりません: {symbol}")
            return

        # 情報更新
        try:
            price = info.last_price
            prev = info.previous_close
            diff = price - prev
            pct = diff / prev * 100
            color = "#00e676" if diff >= 0 else "#ff5252"
            sign = "+" if diff >= 0 else ""
            self.info_labels["銘柄"].config(text=symbol)
            self.info_labels["現在値"].config(text=f"{price:.2f}", fg=color)
            self.info_labels["前日比"].config(
                text=f"{sign}{diff:.2f} ({sign}{pct:.2f}%)", fg=color)
            self.info_labels["始値"].config(text=f"{info.open:.2f}", fg="#e2b96f")
            self.info_labels["高値"].config(text=f"{hist['High'].max():.2f}", fg="#e2b96f")
            self.info_labels["安値"].config(text=f"{hist['Low'].min():.2f}", fg="#e2b96f")
            vol = info.three_month_average_volume
            self.info_labels["出来高"].config(text=f"{vol:,.0f}" if vol else "--",
                                             fg="#e2b96f")
        except Exception:
            pass

        # チャート描画
        self.ax.clear()
        self.ax.set_facecolor("#0f3460")
        dates = hist.index
        closes = hist["Close"]

        # 折れ線
        color = "#00e676" if closes.iloc[-1] >= closes.iloc[0] else "#ff5252"
        self.ax.plot(dates, closes, color=color, linewidth=1.5)
        self.ax.fill_between(dates, closes, closes.min(),
                             alpha=0.2, color=color)

        # 移動平均
        if len(closes) >= 20:
            ma20 = closes.rolling(20).mean()
            self.ax.plot(dates, ma20, color="#ffd700",
                         linewidth=1, alpha=0.7, label="MA20")
            self.ax.legend(facecolor="#16213e", labelcolor="#ccc",
                           fontsize=8)

        self.ax.set_title(f"{symbol}  株価チャート",
                          color="#e2b96f", fontsize=11)
        self.ax.tick_params(colors="#888")
        self.ax.spines["bottom"].set_color("#444")
        self.ax.spines["left"].set_color("#444")
        self.ax.spines["top"].set_visible(False)
        self.ax.spines["right"].set_visible(False)
        self.ax.xaxis.set_major_formatter(mdates.DateFormatter("%m/%d"))
        self.ax.xaxis.set_major_locator(mdates.AutoDateLocator())
        self.fig.autofmt_xdate()
        self.chart_canvas.draw()
        self.status_var.set(
            f"{symbol}  |  {len(hist)} 日分  |  "
            f"更新: {datetime.now().strftime('%H:%M:%S')}")


if __name__ == "__main__":
    root = tk.Tk()
    app = App09(root)
    root.mainloop()

5. コード解説

株価トラッカーのコードを詳しく解説します。クラスベースの設計で各機能を整理して実装しています。

クラス設計とコンストラクタ

App09クラスにアプリの全機能をまとめています。__init__メソッドでウィンドウの基本設定を行い、_build_ui()でUI構築、process()でメイン処理を担当します。この分離により、各メソッドの責任が明確になりコードが読みやすくなります。

import tkinter as tk
from tkinter import ttk, messagebox
import threading
import json
import urllib.request
import urllib.parse
from datetime import datetime, timedelta

try:
    import yfinance as yf
    import matplotlib
    matplotlib.use("TkAgg")
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    import matplotlib.dates as mdates
    LIBS_AVAILABLE = True
except ImportError:
    LIBS_AVAILABLE = False


class App09:
    """株価トラッカー"""

    DEMO_SYMBOLS = ["AAPL", "GOOGL", "MSFT", "AMZN", "META",
                    "TSLA", "NVDA", "7203.T", "6758.T", "9984.T"]
    PERIODS = ["1d", "5d", "1mo", "3mo", "6mo", "1y", "2y", "5y"]
    PERIOD_LABELS = ["1日", "5日", "1ヶ月", "3ヶ月", "6ヶ月", "1年", "2年", "5年"]

    def __init__(self, root):
        self.root = root
        self.root.title("株価トラッカー")
        self.root.geometry("900x620")
        self.root.configure(bg="#1a1a2e")
        self._build_ui()

        if not LIBS_AVAILABLE:
            self.status_var.set(
                "⚠ yfinance・matplotlib が必要です: "
                "pip install yfinance matplotlib")

    def _build_ui(self):
        # ヘッダー
        header = tk.Frame(self.root, bg="#16213e", pady=8)
        header.pack(fill=tk.X)
        tk.Label(header, text="📈 株価トラッカー",
                 font=("Noto Sans JP", 14, "bold"),
                 bg="#16213e", fg="#e2b96f").pack(side=tk.LEFT, padx=12)

        # 検索バー
        search_frame = tk.Frame(self.root, bg="#1a1a2e", pady=8)
        search_frame.pack(fill=tk.X, padx=12)
        tk.Label(search_frame, text="ティッカー:",
                 bg="#1a1a2e", fg="#ccc",
                 font=("Noto Sans JP", 11)).pack(side=tk.LEFT)
        self.symbol_var = tk.StringVar(value="AAPL")
        sym_entry = ttk.Entry(search_frame, textvariable=self.symbol_var,
                              font=("Arial", 12), width=12)
        sym_entry.pack(side=tk.LEFT, padx=8)
        sym_entry.bind("<Return>", lambda e: self._fetch())
        ttk.Button(search_frame, text="取得",
                   command=self._fetch).pack(side=tk.LEFT)

        # プリセット
        for sym in self.DEMO_SYMBOLS:
            tk.Button(search_frame, text=sym, bg="#0f3460",
                      fg="#e2b96f", relief=tk.FLAT, font=("Arial", 9),
                      padx=5, command=lambda s=sym: (
                          self.symbol_var.set(s), self._fetch())
                      ).pack(side=tk.LEFT, padx=2)

        # 期間選択
        period_frame = tk.Frame(self.root, bg="#1a1a2e")
        period_frame.pack(fill=tk.X, padx=12)
        tk.Label(period_frame, text="期間:",
                 bg="#1a1a2e", fg="#ccc").pack(side=tk.LEFT)
        self.period_var = tk.StringVar(value="1mo")
        for p, lbl in zip(self.PERIODS, self.PERIOD_LABELS):
            rb = tk.Radiobutton(period_frame, text=lbl, variable=self.period_var,
                                value=p, bg="#1a1a2e", fg="#ccc",
                                selectcolor="#0f3460", activebackground="#1a1a2e",
                                command=self._fetch)
            rb.pack(side=tk.LEFT, padx=4)

        # 株価情報パネル
        info_frame = tk.Frame(self.root, bg="#16213e", pady=6)
        info_frame.pack(fill=tk.X, padx=12, pady=4)
        self.info_labels = {}
        for key in ["銘柄", "現在値", "前日比", "始値", "高値", "安値", "出来高"]:
            f = tk.Frame(info_frame, bg="#16213e")
            f.pack(side=tk.LEFT, padx=12)
            tk.Label(f, text=key, bg="#16213e", fg="#888",
                     font=("Arial", 9)).pack()
            lbl = tk.Label(f, text="--", bg="#16213e", fg="#e2b96f",
                           font=("Arial", 12, "bold"))
            lbl.pack()
            self.info_labels[key] = lbl

        # チャートエリア
        chart_frame = tk.Frame(self.root, bg="#1a1a2e")
        chart_frame.pack(fill=tk.BOTH, expand=True, padx=12, pady=4)

        if LIBS_AVAILABLE:
            self.fig = Figure(figsize=(9, 4), dpi=90,
                              facecolor="#1a1a2e")
            self.ax = self.fig.add_subplot(111)
            self.ax.set_facecolor("#0f3460")
            self.fig.subplots_adjust(left=0.07, right=0.97,
                                     top=0.9, bottom=0.15)
            self.chart_canvas = FigureCanvasTkAgg(self.fig, master=chart_frame)
            self.chart_canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
        else:
            self.placeholder = tk.Label(
                chart_frame,
                text="yfinance と matplotlib をインストールしてください\n"
                     "pip install yfinance matplotlib",
                bg="#0f3460", fg="#e2b96f",
                font=("Noto Sans JP", 12))
            self.placeholder.pack(fill=tk.BOTH, expand=True)

        self.status_var = tk.StringVar(value="ティッカーシンボルを入力して取得してください")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#16213e", fg="#888", font=("Arial", 9),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    def _fetch(self):
        if not LIBS_AVAILABLE:
            return
        symbol = self.symbol_var.get().strip().upper()
        if not symbol:
            return
        self.status_var.set(f"取得中: {symbol} ...")
        threading.Thread(target=self._load_data, args=(symbol,),
                         daemon=True).start()

    def _load_data(self, symbol):
        try:
            ticker = yf.Ticker(symbol)
            period = self.period_var.get()
            hist = ticker.history(period=period)
            info = ticker.fast_info
            self.root.after(0, self._update_chart, symbol, hist, info)
        except Exception as e:
            self.root.after(0, lambda: self.status_var.set(f"エラー: {e}"))

    def _update_chart(self, symbol, hist, info):
        if hist.empty:
            self.status_var.set(f"データが見つかりません: {symbol}")
            return

        # 情報更新
        try:
            price = info.last_price
            prev = info.previous_close
            diff = price - prev
            pct = diff / prev * 100
            color = "#00e676" if diff >= 0 else "#ff5252"
            sign = "+" if diff >= 0 else ""
            self.info_labels["銘柄"].config(text=symbol)
            self.info_labels["現在値"].config(text=f"{price:.2f}", fg=color)
            self.info_labels["前日比"].config(
                text=f"{sign}{diff:.2f} ({sign}{pct:.2f}%)", fg=color)
            self.info_labels["始値"].config(text=f"{info.open:.2f}", fg="#e2b96f")
            self.info_labels["高値"].config(text=f"{hist['High'].max():.2f}", fg="#e2b96f")
            self.info_labels["安値"].config(text=f"{hist['Low'].min():.2f}", fg="#e2b96f")
            vol = info.three_month_average_volume
            self.info_labels["出来高"].config(text=f"{vol:,.0f}" if vol else "--",
                                             fg="#e2b96f")
        except Exception:
            pass

        # チャート描画
        self.ax.clear()
        self.ax.set_facecolor("#0f3460")
        dates = hist.index
        closes = hist["Close"]

        # 折れ線
        color = "#00e676" if closes.iloc[-1] >= closes.iloc[0] else "#ff5252"
        self.ax.plot(dates, closes, color=color, linewidth=1.5)
        self.ax.fill_between(dates, closes, closes.min(),
                             alpha=0.2, color=color)

        # 移動平均
        if len(closes) >= 20:
            ma20 = closes.rolling(20).mean()
            self.ax.plot(dates, ma20, color="#ffd700",
                         linewidth=1, alpha=0.7, label="MA20")
            self.ax.legend(facecolor="#16213e", labelcolor="#ccc",
                           fontsize=8)

        self.ax.set_title(f"{symbol}  株価チャート",
                          color="#e2b96f", fontsize=11)
        self.ax.tick_params(colors="#888")
        self.ax.spines["bottom"].set_color("#444")
        self.ax.spines["left"].set_color("#444")
        self.ax.spines["top"].set_visible(False)
        self.ax.spines["right"].set_visible(False)
        self.ax.xaxis.set_major_formatter(mdates.DateFormatter("%m/%d"))
        self.ax.xaxis.set_major_locator(mdates.AutoDateLocator())
        self.fig.autofmt_xdate()
        self.chart_canvas.draw()
        self.status_var.set(
            f"{symbol}  |  {len(hist)} 日分  |  "
            f"更新: {datetime.now().strftime('%H:%M:%S')}")


if __name__ == "__main__":
    root = tk.Tk()
    app = App09(root)
    root.mainloop()

LabelFrameによるセクション分け

ttk.LabelFrame を使うことで、入力エリアと結果エリアを視覚的に分けられます。padding引数でフレーム内の余白を設定し、見やすいレイアウトを実現しています。

import tkinter as tk
from tkinter import ttk, messagebox
import threading
import json
import urllib.request
import urllib.parse
from datetime import datetime, timedelta

try:
    import yfinance as yf
    import matplotlib
    matplotlib.use("TkAgg")
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    import matplotlib.dates as mdates
    LIBS_AVAILABLE = True
except ImportError:
    LIBS_AVAILABLE = False


class App09:
    """株価トラッカー"""

    DEMO_SYMBOLS = ["AAPL", "GOOGL", "MSFT", "AMZN", "META",
                    "TSLA", "NVDA", "7203.T", "6758.T", "9984.T"]
    PERIODS = ["1d", "5d", "1mo", "3mo", "6mo", "1y", "2y", "5y"]
    PERIOD_LABELS = ["1日", "5日", "1ヶ月", "3ヶ月", "6ヶ月", "1年", "2年", "5年"]

    def __init__(self, root):
        self.root = root
        self.root.title("株価トラッカー")
        self.root.geometry("900x620")
        self.root.configure(bg="#1a1a2e")
        self._build_ui()

        if not LIBS_AVAILABLE:
            self.status_var.set(
                "⚠ yfinance・matplotlib が必要です: "
                "pip install yfinance matplotlib")

    def _build_ui(self):
        # ヘッダー
        header = tk.Frame(self.root, bg="#16213e", pady=8)
        header.pack(fill=tk.X)
        tk.Label(header, text="📈 株価トラッカー",
                 font=("Noto Sans JP", 14, "bold"),
                 bg="#16213e", fg="#e2b96f").pack(side=tk.LEFT, padx=12)

        # 検索バー
        search_frame = tk.Frame(self.root, bg="#1a1a2e", pady=8)
        search_frame.pack(fill=tk.X, padx=12)
        tk.Label(search_frame, text="ティッカー:",
                 bg="#1a1a2e", fg="#ccc",
                 font=("Noto Sans JP", 11)).pack(side=tk.LEFT)
        self.symbol_var = tk.StringVar(value="AAPL")
        sym_entry = ttk.Entry(search_frame, textvariable=self.symbol_var,
                              font=("Arial", 12), width=12)
        sym_entry.pack(side=tk.LEFT, padx=8)
        sym_entry.bind("<Return>", lambda e: self._fetch())
        ttk.Button(search_frame, text="取得",
                   command=self._fetch).pack(side=tk.LEFT)

        # プリセット
        for sym in self.DEMO_SYMBOLS:
            tk.Button(search_frame, text=sym, bg="#0f3460",
                      fg="#e2b96f", relief=tk.FLAT, font=("Arial", 9),
                      padx=5, command=lambda s=sym: (
                          self.symbol_var.set(s), self._fetch())
                      ).pack(side=tk.LEFT, padx=2)

        # 期間選択
        period_frame = tk.Frame(self.root, bg="#1a1a2e")
        period_frame.pack(fill=tk.X, padx=12)
        tk.Label(period_frame, text="期間:",
                 bg="#1a1a2e", fg="#ccc").pack(side=tk.LEFT)
        self.period_var = tk.StringVar(value="1mo")
        for p, lbl in zip(self.PERIODS, self.PERIOD_LABELS):
            rb = tk.Radiobutton(period_frame, text=lbl, variable=self.period_var,
                                value=p, bg="#1a1a2e", fg="#ccc",
                                selectcolor="#0f3460", activebackground="#1a1a2e",
                                command=self._fetch)
            rb.pack(side=tk.LEFT, padx=4)

        # 株価情報パネル
        info_frame = tk.Frame(self.root, bg="#16213e", pady=6)
        info_frame.pack(fill=tk.X, padx=12, pady=4)
        self.info_labels = {}
        for key in ["銘柄", "現在値", "前日比", "始値", "高値", "安値", "出来高"]:
            f = tk.Frame(info_frame, bg="#16213e")
            f.pack(side=tk.LEFT, padx=12)
            tk.Label(f, text=key, bg="#16213e", fg="#888",
                     font=("Arial", 9)).pack()
            lbl = tk.Label(f, text="--", bg="#16213e", fg="#e2b96f",
                           font=("Arial", 12, "bold"))
            lbl.pack()
            self.info_labels[key] = lbl

        # チャートエリア
        chart_frame = tk.Frame(self.root, bg="#1a1a2e")
        chart_frame.pack(fill=tk.BOTH, expand=True, padx=12, pady=4)

        if LIBS_AVAILABLE:
            self.fig = Figure(figsize=(9, 4), dpi=90,
                              facecolor="#1a1a2e")
            self.ax = self.fig.add_subplot(111)
            self.ax.set_facecolor("#0f3460")
            self.fig.subplots_adjust(left=0.07, right=0.97,
                                     top=0.9, bottom=0.15)
            self.chart_canvas = FigureCanvasTkAgg(self.fig, master=chart_frame)
            self.chart_canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
        else:
            self.placeholder = tk.Label(
                chart_frame,
                text="yfinance と matplotlib をインストールしてください\n"
                     "pip install yfinance matplotlib",
                bg="#0f3460", fg="#e2b96f",
                font=("Noto Sans JP", 12))
            self.placeholder.pack(fill=tk.BOTH, expand=True)

        self.status_var = tk.StringVar(value="ティッカーシンボルを入力して取得してください")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#16213e", fg="#888", font=("Arial", 9),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    def _fetch(self):
        if not LIBS_AVAILABLE:
            return
        symbol = self.symbol_var.get().strip().upper()
        if not symbol:
            return
        self.status_var.set(f"取得中: {symbol} ...")
        threading.Thread(target=self._load_data, args=(symbol,),
                         daemon=True).start()

    def _load_data(self, symbol):
        try:
            ticker = yf.Ticker(symbol)
            period = self.period_var.get()
            hist = ticker.history(period=period)
            info = ticker.fast_info
            self.root.after(0, self._update_chart, symbol, hist, info)
        except Exception as e:
            self.root.after(0, lambda: self.status_var.set(f"エラー: {e}"))

    def _update_chart(self, symbol, hist, info):
        if hist.empty:
            self.status_var.set(f"データが見つかりません: {symbol}")
            return

        # 情報更新
        try:
            price = info.last_price
            prev = info.previous_close
            diff = price - prev
            pct = diff / prev * 100
            color = "#00e676" if diff >= 0 else "#ff5252"
            sign = "+" if diff >= 0 else ""
            self.info_labels["銘柄"].config(text=symbol)
            self.info_labels["現在値"].config(text=f"{price:.2f}", fg=color)
            self.info_labels["前日比"].config(
                text=f"{sign}{diff:.2f} ({sign}{pct:.2f}%)", fg=color)
            self.info_labels["始値"].config(text=f"{info.open:.2f}", fg="#e2b96f")
            self.info_labels["高値"].config(text=f"{hist['High'].max():.2f}", fg="#e2b96f")
            self.info_labels["安値"].config(text=f"{hist['Low'].min():.2f}", fg="#e2b96f")
            vol = info.three_month_average_volume
            self.info_labels["出来高"].config(text=f"{vol:,.0f}" if vol else "--",
                                             fg="#e2b96f")
        except Exception:
            pass

        # チャート描画
        self.ax.clear()
        self.ax.set_facecolor("#0f3460")
        dates = hist.index
        closes = hist["Close"]

        # 折れ線
        color = "#00e676" if closes.iloc[-1] >= closes.iloc[0] else "#ff5252"
        self.ax.plot(dates, closes, color=color, linewidth=1.5)
        self.ax.fill_between(dates, closes, closes.min(),
                             alpha=0.2, color=color)

        # 移動平均
        if len(closes) >= 20:
            ma20 = closes.rolling(20).mean()
            self.ax.plot(dates, ma20, color="#ffd700",
                         linewidth=1, alpha=0.7, label="MA20")
            self.ax.legend(facecolor="#16213e", labelcolor="#ccc",
                           fontsize=8)

        self.ax.set_title(f"{symbol}  株価チャート",
                          color="#e2b96f", fontsize=11)
        self.ax.tick_params(colors="#888")
        self.ax.spines["bottom"].set_color("#444")
        self.ax.spines["left"].set_color("#444")
        self.ax.spines["top"].set_visible(False)
        self.ax.spines["right"].set_visible(False)
        self.ax.xaxis.set_major_formatter(mdates.DateFormatter("%m/%d"))
        self.ax.xaxis.set_major_locator(mdates.AutoDateLocator())
        self.fig.autofmt_xdate()
        self.chart_canvas.draw()
        self.status_var.set(
            f"{symbol}  |  {len(hist)} 日分  |  "
            f"更新: {datetime.now().strftime('%H:%M:%S')}")


if __name__ == "__main__":
    root = tk.Tk()
    app = App09(root)
    root.mainloop()

Entryウィジェットとイベントバインド

ttk.Entryで入力フィールドを作成します。bind('', ...)でEnterキー押下時に処理を実行できます。これにより、マウスを使わずキーボードだけで操作できるUXが実現できます。

import tkinter as tk
from tkinter import ttk, messagebox
import threading
import json
import urllib.request
import urllib.parse
from datetime import datetime, timedelta

try:
    import yfinance as yf
    import matplotlib
    matplotlib.use("TkAgg")
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    import matplotlib.dates as mdates
    LIBS_AVAILABLE = True
except ImportError:
    LIBS_AVAILABLE = False


class App09:
    """株価トラッカー"""

    DEMO_SYMBOLS = ["AAPL", "GOOGL", "MSFT", "AMZN", "META",
                    "TSLA", "NVDA", "7203.T", "6758.T", "9984.T"]
    PERIODS = ["1d", "5d", "1mo", "3mo", "6mo", "1y", "2y", "5y"]
    PERIOD_LABELS = ["1日", "5日", "1ヶ月", "3ヶ月", "6ヶ月", "1年", "2年", "5年"]

    def __init__(self, root):
        self.root = root
        self.root.title("株価トラッカー")
        self.root.geometry("900x620")
        self.root.configure(bg="#1a1a2e")
        self._build_ui()

        if not LIBS_AVAILABLE:
            self.status_var.set(
                "⚠ yfinance・matplotlib が必要です: "
                "pip install yfinance matplotlib")

    def _build_ui(self):
        # ヘッダー
        header = tk.Frame(self.root, bg="#16213e", pady=8)
        header.pack(fill=tk.X)
        tk.Label(header, text="📈 株価トラッカー",
                 font=("Noto Sans JP", 14, "bold"),
                 bg="#16213e", fg="#e2b96f").pack(side=tk.LEFT, padx=12)

        # 検索バー
        search_frame = tk.Frame(self.root, bg="#1a1a2e", pady=8)
        search_frame.pack(fill=tk.X, padx=12)
        tk.Label(search_frame, text="ティッカー:",
                 bg="#1a1a2e", fg="#ccc",
                 font=("Noto Sans JP", 11)).pack(side=tk.LEFT)
        self.symbol_var = tk.StringVar(value="AAPL")
        sym_entry = ttk.Entry(search_frame, textvariable=self.symbol_var,
                              font=("Arial", 12), width=12)
        sym_entry.pack(side=tk.LEFT, padx=8)
        sym_entry.bind("<Return>", lambda e: self._fetch())
        ttk.Button(search_frame, text="取得",
                   command=self._fetch).pack(side=tk.LEFT)

        # プリセット
        for sym in self.DEMO_SYMBOLS:
            tk.Button(search_frame, text=sym, bg="#0f3460",
                      fg="#e2b96f", relief=tk.FLAT, font=("Arial", 9),
                      padx=5, command=lambda s=sym: (
                          self.symbol_var.set(s), self._fetch())
                      ).pack(side=tk.LEFT, padx=2)

        # 期間選択
        period_frame = tk.Frame(self.root, bg="#1a1a2e")
        period_frame.pack(fill=tk.X, padx=12)
        tk.Label(period_frame, text="期間:",
                 bg="#1a1a2e", fg="#ccc").pack(side=tk.LEFT)
        self.period_var = tk.StringVar(value="1mo")
        for p, lbl in zip(self.PERIODS, self.PERIOD_LABELS):
            rb = tk.Radiobutton(period_frame, text=lbl, variable=self.period_var,
                                value=p, bg="#1a1a2e", fg="#ccc",
                                selectcolor="#0f3460", activebackground="#1a1a2e",
                                command=self._fetch)
            rb.pack(side=tk.LEFT, padx=4)

        # 株価情報パネル
        info_frame = tk.Frame(self.root, bg="#16213e", pady=6)
        info_frame.pack(fill=tk.X, padx=12, pady=4)
        self.info_labels = {}
        for key in ["銘柄", "現在値", "前日比", "始値", "高値", "安値", "出来高"]:
            f = tk.Frame(info_frame, bg="#16213e")
            f.pack(side=tk.LEFT, padx=12)
            tk.Label(f, text=key, bg="#16213e", fg="#888",
                     font=("Arial", 9)).pack()
            lbl = tk.Label(f, text="--", bg="#16213e", fg="#e2b96f",
                           font=("Arial", 12, "bold"))
            lbl.pack()
            self.info_labels[key] = lbl

        # チャートエリア
        chart_frame = tk.Frame(self.root, bg="#1a1a2e")
        chart_frame.pack(fill=tk.BOTH, expand=True, padx=12, pady=4)

        if LIBS_AVAILABLE:
            self.fig = Figure(figsize=(9, 4), dpi=90,
                              facecolor="#1a1a2e")
            self.ax = self.fig.add_subplot(111)
            self.ax.set_facecolor("#0f3460")
            self.fig.subplots_adjust(left=0.07, right=0.97,
                                     top=0.9, bottom=0.15)
            self.chart_canvas = FigureCanvasTkAgg(self.fig, master=chart_frame)
            self.chart_canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
        else:
            self.placeholder = tk.Label(
                chart_frame,
                text="yfinance と matplotlib をインストールしてください\n"
                     "pip install yfinance matplotlib",
                bg="#0f3460", fg="#e2b96f",
                font=("Noto Sans JP", 12))
            self.placeholder.pack(fill=tk.BOTH, expand=True)

        self.status_var = tk.StringVar(value="ティッカーシンボルを入力して取得してください")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#16213e", fg="#888", font=("Arial", 9),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    def _fetch(self):
        if not LIBS_AVAILABLE:
            return
        symbol = self.symbol_var.get().strip().upper()
        if not symbol:
            return
        self.status_var.set(f"取得中: {symbol} ...")
        threading.Thread(target=self._load_data, args=(symbol,),
                         daemon=True).start()

    def _load_data(self, symbol):
        try:
            ticker = yf.Ticker(symbol)
            period = self.period_var.get()
            hist = ticker.history(period=period)
            info = ticker.fast_info
            self.root.after(0, self._update_chart, symbol, hist, info)
        except Exception as e:
            self.root.after(0, lambda: self.status_var.set(f"エラー: {e}"))

    def _update_chart(self, symbol, hist, info):
        if hist.empty:
            self.status_var.set(f"データが見つかりません: {symbol}")
            return

        # 情報更新
        try:
            price = info.last_price
            prev = info.previous_close
            diff = price - prev
            pct = diff / prev * 100
            color = "#00e676" if diff >= 0 else "#ff5252"
            sign = "+" if diff >= 0 else ""
            self.info_labels["銘柄"].config(text=symbol)
            self.info_labels["現在値"].config(text=f"{price:.2f}", fg=color)
            self.info_labels["前日比"].config(
                text=f"{sign}{diff:.2f} ({sign}{pct:.2f}%)", fg=color)
            self.info_labels["始値"].config(text=f"{info.open:.2f}", fg="#e2b96f")
            self.info_labels["高値"].config(text=f"{hist['High'].max():.2f}", fg="#e2b96f")
            self.info_labels["安値"].config(text=f"{hist['Low'].min():.2f}", fg="#e2b96f")
            vol = info.three_month_average_volume
            self.info_labels["出来高"].config(text=f"{vol:,.0f}" if vol else "--",
                                             fg="#e2b96f")
        except Exception:
            pass

        # チャート描画
        self.ax.clear()
        self.ax.set_facecolor("#0f3460")
        dates = hist.index
        closes = hist["Close"]

        # 折れ線
        color = "#00e676" if closes.iloc[-1] >= closes.iloc[0] else "#ff5252"
        self.ax.plot(dates, closes, color=color, linewidth=1.5)
        self.ax.fill_between(dates, closes, closes.min(),
                             alpha=0.2, color=color)

        # 移動平均
        if len(closes) >= 20:
            ma20 = closes.rolling(20).mean()
            self.ax.plot(dates, ma20, color="#ffd700",
                         linewidth=1, alpha=0.7, label="MA20")
            self.ax.legend(facecolor="#16213e", labelcolor="#ccc",
                           fontsize=8)

        self.ax.set_title(f"{symbol}  株価チャート",
                          color="#e2b96f", fontsize=11)
        self.ax.tick_params(colors="#888")
        self.ax.spines["bottom"].set_color("#444")
        self.ax.spines["left"].set_color("#444")
        self.ax.spines["top"].set_visible(False)
        self.ax.spines["right"].set_visible(False)
        self.ax.xaxis.set_major_formatter(mdates.DateFormatter("%m/%d"))
        self.ax.xaxis.set_major_locator(mdates.AutoDateLocator())
        self.fig.autofmt_xdate()
        self.chart_canvas.draw()
        self.status_var.set(
            f"{symbol}  |  {len(hist)} 日分  |  "
            f"更新: {datetime.now().strftime('%H:%M:%S')}")


if __name__ == "__main__":
    root = tk.Tk()
    app = App09(root)
    root.mainloop()

Textウィジェットでの結果表示

結果表示にはtk.Textウィジェットを使います。state=tk.DISABLEDでユーザーが直接編集できないようにし、表示前にNORMALに切り替えてからinsert()で内容を更新します。

import tkinter as tk
from tkinter import ttk, messagebox
import threading
import json
import urllib.request
import urllib.parse
from datetime import datetime, timedelta

try:
    import yfinance as yf
    import matplotlib
    matplotlib.use("TkAgg")
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    import matplotlib.dates as mdates
    LIBS_AVAILABLE = True
except ImportError:
    LIBS_AVAILABLE = False


class App09:
    """株価トラッカー"""

    DEMO_SYMBOLS = ["AAPL", "GOOGL", "MSFT", "AMZN", "META",
                    "TSLA", "NVDA", "7203.T", "6758.T", "9984.T"]
    PERIODS = ["1d", "5d", "1mo", "3mo", "6mo", "1y", "2y", "5y"]
    PERIOD_LABELS = ["1日", "5日", "1ヶ月", "3ヶ月", "6ヶ月", "1年", "2年", "5年"]

    def __init__(self, root):
        self.root = root
        self.root.title("株価トラッカー")
        self.root.geometry("900x620")
        self.root.configure(bg="#1a1a2e")
        self._build_ui()

        if not LIBS_AVAILABLE:
            self.status_var.set(
                "⚠ yfinance・matplotlib が必要です: "
                "pip install yfinance matplotlib")

    def _build_ui(self):
        # ヘッダー
        header = tk.Frame(self.root, bg="#16213e", pady=8)
        header.pack(fill=tk.X)
        tk.Label(header, text="📈 株価トラッカー",
                 font=("Noto Sans JP", 14, "bold"),
                 bg="#16213e", fg="#e2b96f").pack(side=tk.LEFT, padx=12)

        # 検索バー
        search_frame = tk.Frame(self.root, bg="#1a1a2e", pady=8)
        search_frame.pack(fill=tk.X, padx=12)
        tk.Label(search_frame, text="ティッカー:",
                 bg="#1a1a2e", fg="#ccc",
                 font=("Noto Sans JP", 11)).pack(side=tk.LEFT)
        self.symbol_var = tk.StringVar(value="AAPL")
        sym_entry = ttk.Entry(search_frame, textvariable=self.symbol_var,
                              font=("Arial", 12), width=12)
        sym_entry.pack(side=tk.LEFT, padx=8)
        sym_entry.bind("<Return>", lambda e: self._fetch())
        ttk.Button(search_frame, text="取得",
                   command=self._fetch).pack(side=tk.LEFT)

        # プリセット
        for sym in self.DEMO_SYMBOLS:
            tk.Button(search_frame, text=sym, bg="#0f3460",
                      fg="#e2b96f", relief=tk.FLAT, font=("Arial", 9),
                      padx=5, command=lambda s=sym: (
                          self.symbol_var.set(s), self._fetch())
                      ).pack(side=tk.LEFT, padx=2)

        # 期間選択
        period_frame = tk.Frame(self.root, bg="#1a1a2e")
        period_frame.pack(fill=tk.X, padx=12)
        tk.Label(period_frame, text="期間:",
                 bg="#1a1a2e", fg="#ccc").pack(side=tk.LEFT)
        self.period_var = tk.StringVar(value="1mo")
        for p, lbl in zip(self.PERIODS, self.PERIOD_LABELS):
            rb = tk.Radiobutton(period_frame, text=lbl, variable=self.period_var,
                                value=p, bg="#1a1a2e", fg="#ccc",
                                selectcolor="#0f3460", activebackground="#1a1a2e",
                                command=self._fetch)
            rb.pack(side=tk.LEFT, padx=4)

        # 株価情報パネル
        info_frame = tk.Frame(self.root, bg="#16213e", pady=6)
        info_frame.pack(fill=tk.X, padx=12, pady=4)
        self.info_labels = {}
        for key in ["銘柄", "現在値", "前日比", "始値", "高値", "安値", "出来高"]:
            f = tk.Frame(info_frame, bg="#16213e")
            f.pack(side=tk.LEFT, padx=12)
            tk.Label(f, text=key, bg="#16213e", fg="#888",
                     font=("Arial", 9)).pack()
            lbl = tk.Label(f, text="--", bg="#16213e", fg="#e2b96f",
                           font=("Arial", 12, "bold"))
            lbl.pack()
            self.info_labels[key] = lbl

        # チャートエリア
        chart_frame = tk.Frame(self.root, bg="#1a1a2e")
        chart_frame.pack(fill=tk.BOTH, expand=True, padx=12, pady=4)

        if LIBS_AVAILABLE:
            self.fig = Figure(figsize=(9, 4), dpi=90,
                              facecolor="#1a1a2e")
            self.ax = self.fig.add_subplot(111)
            self.ax.set_facecolor("#0f3460")
            self.fig.subplots_adjust(left=0.07, right=0.97,
                                     top=0.9, bottom=0.15)
            self.chart_canvas = FigureCanvasTkAgg(self.fig, master=chart_frame)
            self.chart_canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
        else:
            self.placeholder = tk.Label(
                chart_frame,
                text="yfinance と matplotlib をインストールしてください\n"
                     "pip install yfinance matplotlib",
                bg="#0f3460", fg="#e2b96f",
                font=("Noto Sans JP", 12))
            self.placeholder.pack(fill=tk.BOTH, expand=True)

        self.status_var = tk.StringVar(value="ティッカーシンボルを入力して取得してください")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#16213e", fg="#888", font=("Arial", 9),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    def _fetch(self):
        if not LIBS_AVAILABLE:
            return
        symbol = self.symbol_var.get().strip().upper()
        if not symbol:
            return
        self.status_var.set(f"取得中: {symbol} ...")
        threading.Thread(target=self._load_data, args=(symbol,),
                         daemon=True).start()

    def _load_data(self, symbol):
        try:
            ticker = yf.Ticker(symbol)
            period = self.period_var.get()
            hist = ticker.history(period=period)
            info = ticker.fast_info
            self.root.after(0, self._update_chart, symbol, hist, info)
        except Exception as e:
            self.root.after(0, lambda: self.status_var.set(f"エラー: {e}"))

    def _update_chart(self, symbol, hist, info):
        if hist.empty:
            self.status_var.set(f"データが見つかりません: {symbol}")
            return

        # 情報更新
        try:
            price = info.last_price
            prev = info.previous_close
            diff = price - prev
            pct = diff / prev * 100
            color = "#00e676" if diff >= 0 else "#ff5252"
            sign = "+" if diff >= 0 else ""
            self.info_labels["銘柄"].config(text=symbol)
            self.info_labels["現在値"].config(text=f"{price:.2f}", fg=color)
            self.info_labels["前日比"].config(
                text=f"{sign}{diff:.2f} ({sign}{pct:.2f}%)", fg=color)
            self.info_labels["始値"].config(text=f"{info.open:.2f}", fg="#e2b96f")
            self.info_labels["高値"].config(text=f"{hist['High'].max():.2f}", fg="#e2b96f")
            self.info_labels["安値"].config(text=f"{hist['Low'].min():.2f}", fg="#e2b96f")
            vol = info.three_month_average_volume
            self.info_labels["出来高"].config(text=f"{vol:,.0f}" if vol else "--",
                                             fg="#e2b96f")
        except Exception:
            pass

        # チャート描画
        self.ax.clear()
        self.ax.set_facecolor("#0f3460")
        dates = hist.index
        closes = hist["Close"]

        # 折れ線
        color = "#00e676" if closes.iloc[-1] >= closes.iloc[0] else "#ff5252"
        self.ax.plot(dates, closes, color=color, linewidth=1.5)
        self.ax.fill_between(dates, closes, closes.min(),
                             alpha=0.2, color=color)

        # 移動平均
        if len(closes) >= 20:
            ma20 = closes.rolling(20).mean()
            self.ax.plot(dates, ma20, color="#ffd700",
                         linewidth=1, alpha=0.7, label="MA20")
            self.ax.legend(facecolor="#16213e", labelcolor="#ccc",
                           fontsize=8)

        self.ax.set_title(f"{symbol}  株価チャート",
                          color="#e2b96f", fontsize=11)
        self.ax.tick_params(colors="#888")
        self.ax.spines["bottom"].set_color("#444")
        self.ax.spines["left"].set_color("#444")
        self.ax.spines["top"].set_visible(False)
        self.ax.spines["right"].set_visible(False)
        self.ax.xaxis.set_major_formatter(mdates.DateFormatter("%m/%d"))
        self.ax.xaxis.set_major_locator(mdates.AutoDateLocator())
        self.fig.autofmt_xdate()
        self.chart_canvas.draw()
        self.status_var.set(
            f"{symbol}  |  {len(hist)} 日分  |  "
            f"更新: {datetime.now().strftime('%H:%M:%S')}")


if __name__ == "__main__":
    root = tk.Tk()
    app = App09(root)
    root.mainloop()

例外処理とmessagebox

try-except で ValueError と Exception を捕捉し、messagebox.showerror() でユーザーにわかりやすいエラーメッセージを表示します。入力バリデーションは必ず実装しましょう。

import tkinter as tk
from tkinter import ttk, messagebox
import threading
import json
import urllib.request
import urllib.parse
from datetime import datetime, timedelta

try:
    import yfinance as yf
    import matplotlib
    matplotlib.use("TkAgg")
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    import matplotlib.dates as mdates
    LIBS_AVAILABLE = True
except ImportError:
    LIBS_AVAILABLE = False


class App09:
    """株価トラッカー"""

    DEMO_SYMBOLS = ["AAPL", "GOOGL", "MSFT", "AMZN", "META",
                    "TSLA", "NVDA", "7203.T", "6758.T", "9984.T"]
    PERIODS = ["1d", "5d", "1mo", "3mo", "6mo", "1y", "2y", "5y"]
    PERIOD_LABELS = ["1日", "5日", "1ヶ月", "3ヶ月", "6ヶ月", "1年", "2年", "5年"]

    def __init__(self, root):
        self.root = root
        self.root.title("株価トラッカー")
        self.root.geometry("900x620")
        self.root.configure(bg="#1a1a2e")
        self._build_ui()

        if not LIBS_AVAILABLE:
            self.status_var.set(
                "⚠ yfinance・matplotlib が必要です: "
                "pip install yfinance matplotlib")

    def _build_ui(self):
        # ヘッダー
        header = tk.Frame(self.root, bg="#16213e", pady=8)
        header.pack(fill=tk.X)
        tk.Label(header, text="📈 株価トラッカー",
                 font=("Noto Sans JP", 14, "bold"),
                 bg="#16213e", fg="#e2b96f").pack(side=tk.LEFT, padx=12)

        # 検索バー
        search_frame = tk.Frame(self.root, bg="#1a1a2e", pady=8)
        search_frame.pack(fill=tk.X, padx=12)
        tk.Label(search_frame, text="ティッカー:",
                 bg="#1a1a2e", fg="#ccc",
                 font=("Noto Sans JP", 11)).pack(side=tk.LEFT)
        self.symbol_var = tk.StringVar(value="AAPL")
        sym_entry = ttk.Entry(search_frame, textvariable=self.symbol_var,
                              font=("Arial", 12), width=12)
        sym_entry.pack(side=tk.LEFT, padx=8)
        sym_entry.bind("<Return>", lambda e: self._fetch())
        ttk.Button(search_frame, text="取得",
                   command=self._fetch).pack(side=tk.LEFT)

        # プリセット
        for sym in self.DEMO_SYMBOLS:
            tk.Button(search_frame, text=sym, bg="#0f3460",
                      fg="#e2b96f", relief=tk.FLAT, font=("Arial", 9),
                      padx=5, command=lambda s=sym: (
                          self.symbol_var.set(s), self._fetch())
                      ).pack(side=tk.LEFT, padx=2)

        # 期間選択
        period_frame = tk.Frame(self.root, bg="#1a1a2e")
        period_frame.pack(fill=tk.X, padx=12)
        tk.Label(period_frame, text="期間:",
                 bg="#1a1a2e", fg="#ccc").pack(side=tk.LEFT)
        self.period_var = tk.StringVar(value="1mo")
        for p, lbl in zip(self.PERIODS, self.PERIOD_LABELS):
            rb = tk.Radiobutton(period_frame, text=lbl, variable=self.period_var,
                                value=p, bg="#1a1a2e", fg="#ccc",
                                selectcolor="#0f3460", activebackground="#1a1a2e",
                                command=self._fetch)
            rb.pack(side=tk.LEFT, padx=4)

        # 株価情報パネル
        info_frame = tk.Frame(self.root, bg="#16213e", pady=6)
        info_frame.pack(fill=tk.X, padx=12, pady=4)
        self.info_labels = {}
        for key in ["銘柄", "現在値", "前日比", "始値", "高値", "安値", "出来高"]:
            f = tk.Frame(info_frame, bg="#16213e")
            f.pack(side=tk.LEFT, padx=12)
            tk.Label(f, text=key, bg="#16213e", fg="#888",
                     font=("Arial", 9)).pack()
            lbl = tk.Label(f, text="--", bg="#16213e", fg="#e2b96f",
                           font=("Arial", 12, "bold"))
            lbl.pack()
            self.info_labels[key] = lbl

        # チャートエリア
        chart_frame = tk.Frame(self.root, bg="#1a1a2e")
        chart_frame.pack(fill=tk.BOTH, expand=True, padx=12, pady=4)

        if LIBS_AVAILABLE:
            self.fig = Figure(figsize=(9, 4), dpi=90,
                              facecolor="#1a1a2e")
            self.ax = self.fig.add_subplot(111)
            self.ax.set_facecolor("#0f3460")
            self.fig.subplots_adjust(left=0.07, right=0.97,
                                     top=0.9, bottom=0.15)
            self.chart_canvas = FigureCanvasTkAgg(self.fig, master=chart_frame)
            self.chart_canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
        else:
            self.placeholder = tk.Label(
                chart_frame,
                text="yfinance と matplotlib をインストールしてください\n"
                     "pip install yfinance matplotlib",
                bg="#0f3460", fg="#e2b96f",
                font=("Noto Sans JP", 12))
            self.placeholder.pack(fill=tk.BOTH, expand=True)

        self.status_var = tk.StringVar(value="ティッカーシンボルを入力して取得してください")
        tk.Label(self.root, textvariable=self.status_var,
                 bg="#16213e", fg="#888", font=("Arial", 9),
                 anchor="w", padx=8).pack(fill=tk.X, side=tk.BOTTOM)

    def _fetch(self):
        if not LIBS_AVAILABLE:
            return
        symbol = self.symbol_var.get().strip().upper()
        if not symbol:
            return
        self.status_var.set(f"取得中: {symbol} ...")
        threading.Thread(target=self._load_data, args=(symbol,),
                         daemon=True).start()

    def _load_data(self, symbol):
        try:
            ticker = yf.Ticker(symbol)
            period = self.period_var.get()
            hist = ticker.history(period=period)
            info = ticker.fast_info
            self.root.after(0, self._update_chart, symbol, hist, info)
        except Exception as e:
            self.root.after(0, lambda: self.status_var.set(f"エラー: {e}"))

    def _update_chart(self, symbol, hist, info):
        if hist.empty:
            self.status_var.set(f"データが見つかりません: {symbol}")
            return

        # 情報更新
        try:
            price = info.last_price
            prev = info.previous_close
            diff = price - prev
            pct = diff / prev * 100
            color = "#00e676" if diff >= 0 else "#ff5252"
            sign = "+" if diff >= 0 else ""
            self.info_labels["銘柄"].config(text=symbol)
            self.info_labels["現在値"].config(text=f"{price:.2f}", fg=color)
            self.info_labels["前日比"].config(
                text=f"{sign}{diff:.2f} ({sign}{pct:.2f}%)", fg=color)
            self.info_labels["始値"].config(text=f"{info.open:.2f}", fg="#e2b96f")
            self.info_labels["高値"].config(text=f"{hist['High'].max():.2f}", fg="#e2b96f")
            self.info_labels["安値"].config(text=f"{hist['Low'].min():.2f}", fg="#e2b96f")
            vol = info.three_month_average_volume
            self.info_labels["出来高"].config(text=f"{vol:,.0f}" if vol else "--",
                                             fg="#e2b96f")
        except Exception:
            pass

        # チャート描画
        self.ax.clear()
        self.ax.set_facecolor("#0f3460")
        dates = hist.index
        closes = hist["Close"]

        # 折れ線
        color = "#00e676" if closes.iloc[-1] >= closes.iloc[0] else "#ff5252"
        self.ax.plot(dates, closes, color=color, linewidth=1.5)
        self.ax.fill_between(dates, closes, closes.min(),
                             alpha=0.2, color=color)

        # 移動平均
        if len(closes) >= 20:
            ma20 = closes.rolling(20).mean()
            self.ax.plot(dates, ma20, color="#ffd700",
                         linewidth=1, alpha=0.7, label="MA20")
            self.ax.legend(facecolor="#16213e", labelcolor="#ccc",
                           fontsize=8)

        self.ax.set_title(f"{symbol}  株価チャート",
                          color="#e2b96f", fontsize=11)
        self.ax.tick_params(colors="#888")
        self.ax.spines["bottom"].set_color("#444")
        self.ax.spines["left"].set_color("#444")
        self.ax.spines["top"].set_visible(False)
        self.ax.spines["right"].set_visible(False)
        self.ax.xaxis.set_major_formatter(mdates.DateFormatter("%m/%d"))
        self.ax.xaxis.set_major_locator(mdates.AutoDateLocator())
        self.fig.autofmt_xdate()
        self.chart_canvas.draw()
        self.status_var.set(
            f"{symbol}  |  {len(hist)} 日分  |  "
            f"更新: {datetime.now().strftime('%H:%M:%S')}")


if __name__ == "__main__":
    root = tk.Tk()
    app = App09(root)
    root.mainloop()

6. ステップバイステップガイド

このアプリをゼロから自分で作る手順を解説します。コードをコピーするだけでなく、実際に手順を追って自分で書いてみましょう。

  1. 1
    ファイルを作成する

    新しいファイルを作成して app09.py と保存します。

  2. 2
    クラスの骨格を作る

    App09クラスを定義し、__init__とmainloop()の最小構成を作ります。

  3. 3
    タイトルバーを作る

    Frameを使ってカラーバー付きのタイトルエリアを作ります。

  4. 4
    入力フォームを実装する

    LabelFrameとEntryウィジェットで入力エリアを作ります。

  5. 5
    処理ロジックを実装する

    _calculate()メソッドに計算・処理ロジックを実装します。

  6. 6
    結果表示を実装する

    TextウィジェットかLabelに結果を表示する_show_result()を実装します。

  7. 7
    エラー処理を追加する

    try-exceptとmessageboxでエラーハンドリングを追加します。

7. カスタマイズアイデア

基本機能を習得したら、以下のカスタマイズに挑戦してみましょう。少しずつ機能を追加することで、Pythonのスキルが飛躍的に向上します。

💡 ダークモードを追加する

bg色・fg色を辞書で管理し、ボタン1つでダークモード・ライトモードを切り替えられるようにしましょう。

💡 データのエクスポート機能

計算結果をCSV・TXTファイルに保存するエクスポート機能を追加しましょう。filedialog.asksaveasfilename()でファイル保存ダイアログが使えます。

💡 入力履歴機能

以前の入力値を覚えておいてComboboxのドロップダウンで再選択できる履歴機能を追加しましょう。

8. よくある問題と解決法

❌ 日本語フォントが表示されない

原因:システムに日本語フォントが見つからない場合があります。

解決法:font引数を省略するかシステムに合ったフォントを指定してください。

❌ ウィンドウのサイズが変更できない

原因:resizable(False, False)が設定されています。

解決法:resizable(True, True)に変更してください。

9. 練習問題

アプリの理解を深めるための練習問題です。難易度順に挑戦してみてください。

  1. 課題1:機能拡張

    株価トラッカーに新しい機能を1つ追加してみましょう。どんな機能があると便利か考えてから実装してください。

  2. 課題2:UIの改善

    色・フォント・レイアウトを変更して、より使いやすいUIにカスタマイズしてみましょう。

  3. 課題3:保存機能の追加

    入力値や計算結果をファイルに保存する機能を追加しましょう。jsonやcsvモジュールを使います。

🚀
次に挑戦するアプリ

このアプリをマスターしたら、次のNo.10に挑戦しましょう。