Tuesday, November 26, 2024

Python, matplotlib.animation: Test showing changing values of Index Vs Stock

I am testing "matplotlib.animation" using the stock market index (NASDAQ in this case example) and the stock market price (Amazon in this case example)

# Parameter Adjustment

# Set Ticker Symbol
# e.g. Ticker="^GSPC" for S&P 500, Ticker="NDAQ" for NASDAQ, Ticker="TOPX" for TOPIX
Ticker_index="NDAQ" # Ticker sympol for the index
# Ticker="AMZN" for Amazon, Ticker="NTDOY" for NINTENDO
Ticker_stock="AMZN" # Ticker symbok for a stock

# Set the number of years to download data
No_Years_Data=1;

# Set the numbers of days for the future forecast
No_Days_FutureForecast=250*1


# For statistics
import random
import numpy as np
from scipy import stats
from scipy.stats import norm
# For plotting
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib.animation as animation
from itertools import count

# Setting Plot Size
plt.rcParams["figure.figsize"] = (10,7)

# Calling stock values from Yahoo finance API
# Ref. https://www.kaggle.com/code/alessandrozanette/s-p500-analysis-using-yfinance-data
import yfinance as yf
%config InlineBackend.figure_format='retina'
import warnings
warnings.filterwarnings("ignore")

# Now, let's retrieve the data of the past x years using yfinance
Years="".join([str(No_Years_Data),'y']) # Set the number of years ! Adjust
Index = yf.Ticker(Ticker_index).history(period=Years)  # Ticker Symbokl ! Adjust !
Stock = yf.Ticker(Ticker_stock).history(period=Years)  # Ticker Symbokl ! Adjust !
# Let's take a look at the data
display(Index.tail())
display(Stock.tail())

# Change to list
# https://stackoverflow.com/questions/39597553/from-datetimeindex-to-list-of-times
Dates=Stock.index.tolist()
Dates=[Dates[t].strftime("%Y-%m-%d") for t in range(len(Dates))]
Values_Index=Index["Close"].tolist()
Values_Stock=Stock["Close"].tolist()

# Taking a difference of natural log of these values
y_1=np.diff(np.log(Index["Close"])).tolist()
y_2=np.diff(np.log(Stock["Close"])).tolist()

# Inline animations in Jupyter
# https://stackoverflow.com/questions/43445103/inline-animations-in-jupyter

plt.rcParams["animation.html"] = "jshtml"
plt.rcParams['figure.dpi'] = 150  

fig, ax = plt.subplots()
x_value = []
y1_value = []
y2_value = []
index = count();

Window=30
index = count();
def animate(t):
    n=next(index)
    x_value=Dates[n:n+Window].copy()
    y1_value=y_1[n:n+Window].copy()
    y2_value=y_2[n:n+Window].copy()
    ax.cla()
    ax.plot(x_value,y1_value, label=Ticker_index, color='slategrey')
    ax.plot(x_value,y2_value, label=Ticker_stock, color='darkseagreen')
    plt.legend(loc="upper right")
    plt.xticks(rotation=90)
    ax.set_xlim(0,Window)

animation.FuncAnimation(fig, animate, frames=Window, interval = 500)