6.3 KiB
This code retrieves historical stock price data for Netflix from Yahoo Finance and performs statistical analysis. It calculates the rolling z-score of the closing prices over a 30-day window, allowing for the detection of significant deviations from the mean. The z-score is then plotted and its distribution visualized using a histogram. Additionally, it computes the minimum percentage change in closing prices over a 30-day rolling window and visualizes it. This is useful for identifying extreme price movements and understanding the stock's volatility.
import yfinance as yf
Download historical stock price data for Netflix from Yahoo Finance
data = yf.download("NFLX", start="2020-01-01", end="2022-06-30")
Define a function to calculate the z-score for a given chunk of data
def z_score(chunk): """Calculate z-score for a given chunk. Parameters ---------- chunk : pd.Series A series of stock prices or values. Returns ------- float The z-score of the last value in the chunk. Notes ----- This method computes the z-score, which is the number of standard deviations a value is from the mean. """ return (chunk[-1] - chunk.mean()) / chunk.std()
Calculate the rolling z-score of the closing prices over a 30-day window
rolled = data.Close.rolling(window=30).apply(z_score)
Plot the rolling z-score to visualize deviations from the mean
rolled.plot()
Plot a histogram of the rolling z-score to understand its distribution
rolled.hist(bins=20)
Find the minimum z-score value to identify significant deviations
rolled.min()
Calculate the percentage change from the closing price on 20 April 2022
(226.19 - 348.61) / 348.61
Calculate the minimum percentage change in closing prices over a 30-day rolling window
min_pct_change = ( data .Close .pct_change() .rolling(window=30) .min() )
Plot the minimum percentage change to visualize extreme price movements
min_pct_change.plot()
Plot a histogram of the minimum percentage change to understand its distribution
min_pct_change.hist(bins=20)
PyQuant News is where finance practitioners level up with Python for quant finance, algorithmic trading, and market data analysis. Looking to get started? Check out the fastest growing, top-selling course to get started with Python for quant finance. For educational purposes. Not investment advise. Use at your own risk.
