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 mathematics
import numpy as np
import math
import statistics

# For plotting
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib.animation as animation
import itertools # for joining lists inside a list
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
epsilon=[] # storing errors
Window=30; # business days in 1.5 months
for b in range(math.floor(len(y_1)/Window)-1):
    st=0+Window*b; ed=st+Window; print(st,ed)

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

    fig, ax = plt.subplots()
    x_value = []
    y1_value = []
    y2_value = []
    epsilon_value=[]

    count_ = count();
    def animate(a):
        counts=next(count_)
        x_value=Dates[st+counts:ed+counts].copy()
        y1_value=y_1[st+counts:ed+counts].copy()
        y2_value=y_2[st+counts:ed+counts].copy()
        #epsilon_value=[abs((y1_value[w]-y2_value[w])/y2_value[w]) for w in range(len(y1_value))] # Relative
        epsilon_value=[abs((y1_value[w]-y2_value[w])) for w in range(len(y1_value))] # Absolute
        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)
        plt.title(f'From {Dates[st]} to {Dates[ed+Window]}')
        ax.set_xlim(0,Window)
        epsilon.append(epsilon_value)
    Animation=animation.FuncAnimation(fig, animate, frames=Window, interval = 500)
    display(Animation)

# Separating figures
plt.show(block=False)

# Analysing errors
# joininig lists inside a list
epsilon=list(itertools.chain.from_iterable(epsilon))

print(statistics.mean(epsilon))
plt.figure(); plt.hist(epsilon); plt.show(block=False)