ホームページ  >  記事  >  バックエンド開発  >  過去 n 日間の株価チャートを生成する Python コード。

過去 n 日間の株価チャートを生成する Python コード。

Mary-Kate Olsen
Mary-Kate Olsenオリジナル
2024-10-21 14:47:02652ブラウズ

Python code that generates a stock price chart for the last n days.

コードの各部分の動作について詳しく説明します:

ライブラリのインポート:

matplotlib.pyplot はプロットの作成に使用されます。
yahooquery.Ticker は、Yahoo Finance から過去の株式データを取得するために使用されます。
datetime と timedelta は日付の操作に使用されます。
データ処理には pandas が使用されます。
pytz はタイムゾーンを操作するために使用されます。
os はファイル システムの操作に使用されます。

関数plot_stock_last_n_days:

関数パラメータ:
シンボル: 株式ティッカー (例: 「NVDA」)。
n_days: 履歴データが表示される日数。
filename: プロットが保存されるファイルの名前。
timezone: データを表示するためのタイムゾーン。

日付範囲:

現在の日付と期間の開始日は、n_days に基づいて計算されます。

データの取得:

yahooquery は、指定された期間の過去の株価データを取得するために使用されます。

データの可用性を確認する:

利用可能なデータがない場合は、メッセージが出力され、関数は終了します。

データ処理:

データのインデックスが日時形式に変換され、タイムゾーンが設定されます。
週末 (土曜日と日曜日) は除外されます。
終値の変化率が計算されます。

プロットの作成と構成:

メイン プロットは終値で作成されます。
終値と変化率を示す注釈がプロットに追加されます。
X 軸と Y 軸が構成され、日付がフォーマットされ、グリッド線が追加されます。
取引高の追加プロットが追加され、終値のプラスとマイナスの変化が異なる色で表示されます。

透かしを追加する:

プロットの左下隅と右上隅に透かしが追加されます。

プロットの保存と表示:

プロットは、指定したファイル名で画像ファイルとして保存され、表示されます。

使用例:

この関数はティッカー「NVDA」(NVIDIA) で呼び出され、過去 14 日間のデータを表示し、プロットを「output.png」として保存し、GMT タイムゾーンを使用します。

要約すると、このコードは、終値や取引高などの過去の株価データを、変化率やタイムゾーンの考慮事項の注釈とともに視覚的に表現したものを生成します。

import matplotlib.pyplot as plt
from yahooquery import Ticker
from datetime import datetime, timedelta
import matplotlib.dates as mdates
import os
import pandas as pd
import pytz

def plot_stock_last_n_days(symbol, n_days=30, filename='stock_plot.png', timezone='UTC'):
    # Define the date range
    end_date = datetime.now(pytz.timezone(timezone))
    start_date = end_date - timedelta(days=n_days)

    # Convert dates to the format expected by Yahoo Finance
    start_date_str = start_date.strftime('%Y-%m-%d')
    end_date_str = end_date.strftime('%Y-%m-%d')

    # Fetch historical data for the last n days
    ticker = Ticker(symbol)
    historical_data = ticker.history(start=start_date_str, end=end_date_str, interval='1d')

    # Check if the data is available
    if historical_data.empty:
        print("No data available.")
        return

    # Ensure the index is datetime for proper plotting and localize to the specified timezone
    historical_data.index = pd.to_datetime(historical_data.index.get_level_values('date')).tz_localize('UTC').tz_convert(timezone)

    # Filter out weekends
    historical_data = historical_data[historical_data.index.weekday < 5]

    # Calculate percentage changes
    historical_data['pct_change'] = historical_data['close'].pct_change() * 100

    # Ensure the output directory exists
    output_dir = 'output'
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # Adjust the filename to include the output directory
    filename = os.path.join(output_dir, filename)

    # Plotting the closing price
    fig, ax1 = plt.subplots(figsize=(10, 5))
    ax1.plot(historical_data.index, historical_data['close'], label='Close Price', color='blue', marker='o')

    # Annotate each point with its value and percentage change
    for i in range(1, len(historical_data)):
        date = historical_data.index[i]
        close = historical_data['close'].iloc[i]
        pct_change = historical_data['pct_change'].iloc[i]
        color = 'green' if pct_change > 0 else 'red'
        ax1.text(date, close, f'{close:.2f}\n({pct_change:.2f}%)', fontsize=9, ha='right', color=color)

    # Set up daily gridlines and print date for every day
    ax1.xaxis.set_major_locator(mdates.DayLocator(interval=1))
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

    ax1.set_xlabel('Date')
    ax1.set_ylabel('Price (USD)')
    ax1.set_title(f'{symbol} Stock Price - Last {n_days} Days')
    ax1.legend(loc='upper left')
    ax1.grid(True)
    ax1.tick_params(axis='x', rotation=80)
    fig.tight_layout()

    # Adding the trading volume plot
    ax2 = ax1.twinx()
    calm_green = (0.6, 1, 0.6)  # Calm green color
    calm_red = (1, 0.6, 0.6)    # Calm red color
    colors = [calm_green if historical_data['close'].iloc[i] > historical_data['open'].iloc[i] else calm_red for i in range(len(historical_data))]
    ax2.bar(historical_data.index, historical_data['volume'], color=colors, alpha=0.5, width=0.8)
    ax2.set_ylabel('Volume')
    ax2.tick_params(axis='y')

    # Format y-axis for volume in millions
    def millions(x, pos):
        'The two args are the value and tick position'
        return '%1.0fM' % (x * 1e-6)

    ax2.yaxis.set_major_formatter(plt.FuncFormatter(millions))

    # Adjust the visibility and spacing of the volume axis
    fig.subplots_adjust(right=0.85)
    ax2.spines['right'].set_position(('outward', 60))
    ax2.yaxis.set_label_position('right')
    ax2.yaxis.set_ticks_position('right')

    # Add watermarks
    plt.text(0.01, 0.01, 'medium.com/@dmitry.romanoff', fontsize=12, color='grey', ha='left', va='bottom', alpha=0.5, transform=plt.gca().transAxes)
    plt.text(0.99, 0.99, 'medium.com/@dmitry.romanoff', fontsize=12, color='grey', ha='right', va='top', alpha=0.5, transform=plt.gca().transAxes)

    # Save the plot as an image file
    plt.savefig(filename)
    plt.show()

# Example usage
plot_stock_last_n_days('NVDA', n_days=14, filename='output.png', timezone='GMT')

以上が過去 n 日間の株価チャートを生成する Python コード。の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。