Files
strategy-lab/to_explore/pyquantnews/6_RollingZScore.ipynb
David Brazda e3da60c647 daily update
2024-10-21 20:57:56 +02:00

6.3 KiB

No description has been provided for this image

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.

In [ ]:
import yfinance as yf

Download historical stock price data for Netflix from Yahoo Finance

In [ ]:
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

In [ ]:
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

In [ ]:
rolled = data.Close.rolling(window=30).apply(z_score)

Plot the rolling z-score to visualize deviations from the mean

In [ ]:
rolled.plot()

Plot a histogram of the rolling z-score to understand its distribution

In [ ]:
rolled.hist(bins=20)

Find the minimum z-score value to identify significant deviations

In [ ]:
rolled.min()

Calculate the percentage change from the closing price on 20 April 2022

In [ ]:
(226.19 - 348.61) / 348.61

Calculate the minimum percentage change in closing prices over a 30-day rolling window

In [ ]:
min_pct_change = (
    data
    .Close
    .pct_change()
    .rolling(window=30)
    .min()
)

Plot the minimum percentage change to visualize extreme price movements

In [ ]:
min_pct_change.plot()

Plot a histogram of the minimum percentage change to understand its distribution

In [ ]:
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.