0
2

Pythonで株価アニメーション動画を作成する方法

Last updated at Posted at 2024-08-28

この記事では、Pythonを使用してApple Inc.(AAPL)の株価データを取得し、インスタグラムに適したアニメーションを作成する方法について解説します。このアニメーションでは、株価の変動を可視化し、ドル表示で最新の価格を表示します。

完成イメージ

必要なライブラリ

まず、以下のライブラリをインストールしておきましょう。

pip install matplotlib yfinance pandas

コードの解説

以下に示すのが、アニメーションを作成するためのコードです。

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import yfinance as yf
import pandas as pd
import datetime

1. グラフの設定

コードの最初の部分では、グラフの見た目を設定しています。背景色やラベルの色、サイズなどを指定し、インスタグラムに適した正方形の画像サイズを設定しています。

# グラフの設定
plt.rcParams['font.family'] = 'AppleGothic'
plt.rcParams['axes.facecolor'] = 'white'  
plt.rcParams['axes.edgecolor'] = 'black'
plt.rcParams['axes.labelcolor'] = 'black'
plt.rcParams['axes.labelsize'] = 0
plt.rcParams['xtick.color'] = 'black'
plt.rcParams['ytick.color'] = 'black'
plt.rcParams['xtick.labelsize'] = 8
plt.rcParams['ytick.labelsize'] = 8
plt.rcParams['figure.facecolor'] = 'white'  
plt.rcParams['figure.edgecolor'] = 'white'

# 画像サイズ
fig, ax = plt.subplots(figsize=(10.8, 10.8))

2. データの取得

次に、yfinanceライブラリを使用して、Appleの株価データを取得します。start_dateからend_dateまでの日付範囲でデータを取得し、月ごとの平均値を計算します。

# 設定
symbol = 'AAPL'  # AAPLのティッカーシンボル
start_date = '2019-01-01'
end_date = datetime.datetime.now().strftime('%Y-%m-%d')
stock_data_daily = yf.download(symbol, start=start_date, end=end_date)
stock_data_monthly = stock_data_daily['Close'].resample('M').mean()  # 月足データを使用

3. 初期投資と株価の計算

ここでは、初期投資額を100ドルとし、月ごとの株価データを基に投資額をドルで計算します。

# 初期投資を100ドル換算に設定
initial_investment = 100  # 初期投資額(100ドル)
initial_price = stock_data_monthly.iloc[0]  # 初期の株価
shares_bought = initial_investment / initial_price  # 購入した株数

4. アニメーションの作成

FuncAnimationを使用して、アニメーションを作成します。update関数では、各フレームごとにグラフを更新し、最新の株価をドル表示で描画します。

def update(frame):
    ax.clear()
    current_data = stock_data_monthly.iloc[:max(1, frame)]
    ax.plot(current_data.index, current_data, color='lightblue')  # 折れ線グラフを水色に設定
    ax.fill_between(current_data.index, 0, current_data, color='lightblue', alpha=0.3)  # 塗りつぶしを水色に設定
    ax.set_facecolor('white')  # 背景を白に設定
    ax.set_xlim(current_data.index[0], current_data.index[-1])
    ax.set_ylim(current_data.min(), current_data.max())
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.yaxis.tick_right()
    ax.tick_params(axis='x', rotation=45)

    current_price = stock_data_monthly.iloc[frame]
    text = f"${current_price:,.2f} USD"  # 現在の価格をドルで表示
    ax.text(0.5, 0.1, text, color='black', horizontalalignment='center',  # テキスト色を黒に設定
            verticalalignment='center', fontsize=15, transform=ax.transAxes)

ani = FuncAnimation(fig, update, frames=len(stock_data_monthly), interval=1000 / 30)
ani.save('apple_stock_animation_with_text.mp4', writer='ffmpeg', fps=25)

5. アニメーションの保存

最後に、作成したアニメーションをmp4形式で保存します。このアニメーションは、株価の変動を視覚的に表現し、インスタグラムに投稿するのに最適です。

以上が、Appleの株価アニメーションを作成するための基本的な手順です。これにより、株価データの可視化がより簡単かつ効果的に行えるようになります。

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import yfinance as yf
import pandas as pd
import datetime

# グラフの設定
plt.rcParams['font.family'] = 'AppleGothic'
plt.rcParams['axes.facecolor'] = 'white'  # 背景を白に設定
plt.rcParams['axes.edgecolor'] = 'black'
plt.rcParams['axes.labelcolor'] = 'black'
plt.rcParams['axes.labelsize'] = 0
plt.rcParams['xtick.color'] = 'black'
plt.rcParams['ytick.color'] = 'black'
plt.rcParams['xtick.labelsize'] = 8
plt.rcParams['ytick.labelsize'] = 8
plt.rcParams['figure.facecolor'] = 'white'  # 背景を白に設定
plt.rcParams['figure.edgecolor'] = 'white'

# インスタグラムに適した画像サイズに設定
fig, ax = plt.subplots(figsize=(10.8, 10.8))

# 設定
symbol = 'AAPL'  # AAPLのティッカーシンボル
start_date = '2000-01-01'
end_date = datetime.datetime.now().strftime('%Y-%m-%d')
stock_data_daily = yf.download(symbol, start=start_date, end=end_date)
stock_data_monthly = stock_data_daily['Close'].resample('M').mean()  # 月足データを使用

# 初期投資を100ドル換算に設定
initial_investment = 100  # 初期投資額(100ドル)
initial_price = stock_data_monthly.iloc[0]  # 初期の株価
shares_bought = initial_investment / initial_price  # 購入した株数

def update(frame):
    ax.clear()
    current_data = stock_data_monthly.iloc[:max(1, frame)]
    ax.plot(current_data.index, current_data, color='lightblue')  # 折れ線グラフを水色に設定
    ax.fill_between(current_data.index, 0, current_data, color='lightblue', alpha=0.3)  # 塗りつぶしを水色に設定
    ax.set_facecolor('white')  # 背景を白に設定
    ax.set_xlim(current_data.index[0], current_data.index[-1])
    ax.set_ylim(current_data.min(), current_data.max())
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.yaxis.tick_right()
    ax.tick_params(axis='x', rotation=45)

    current_price = stock_data_monthly.iloc[frame]
    text = f"${current_price:,.2f} USD"  # 現在の価格をドルで表示
    ax.text(0.5, 0.1, text, color='black', horizontalalignment='center',  # テキスト色を黒に設定
            verticalalignment='center', fontsize=15, transform=ax.transAxes)

ani = FuncAnimation(fig, update, frames=len(stock_data_monthly), interval=1000 / 30)
ani.save('apple_stock_animation_with_text.mp4', writer='ffmpeg', fps=25)

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2