My aim is to see how the histogram of a stock changes over time. So I want to animate the difference in specified time. Based on some articles in web I tried the following to make it. But I don't get some histogram-data. What is my problem of understanding the way of animations in matplotlib?
import pandas_datareader as web
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
stock = 'ALB'
df = web.DataReader(stock, 'yahoo', "01.01.2021", "14.11.2021")
def update_hist(step):
plt.cla()
df_step = df[:][step:step+30]
df_step.hist(column=stock)
animation.FuncAnimation(fig, update_hist, fargs=([1, 30, 60, 90, 120]))
plt.show()
I made a NumPy array of the stock and plotted it. Here my code. I think there is a much more direct way only use of the df above.
##
# generates an animation of histograms of the stocks in the file
##
def histogram_builder(filename):
df = pd.read_csv(f"Webscrapper/{filename}_DailyChanges.csv", index_col="Date")
fig = plt.figure()
stock = 'ALB'
data = np.empty((0, 30), float)
for index, val in enumerate(df[stock][:-30]):
array_buffer = np.array(df[stock][index: index + 30])
array_buffer = np.reshape(array_buffer, (1, 30))
data = np.append(data, array_buffer, axis=0)
iterations = data.shape[0]
print(iterations)
def update_hist(step):
plt.cla()
df_step = df[:][step:step+30]
stock_data = df_step.loc[:, stock]
plt.hist(data[step])
# calculates the expected value of the histogram
n, bins = np.histogram(stock_data.values)
mid = 0.5 * (bins[1:] + bins[:-1])
mean = np.average(mid, weights=n)
update_hist(1)
anim = animation.FuncAnimation(fig, update_hist, frames=iterations)
plt.show()