Calculate the volatility of a stock over a period of time.
For the price of a stock, when the stock price on any day is $ S_ {i} $, the rate of change from the previous day $ c_ {i} $ is defined as follows.
c_{i} = \biggl({\frac{S_i}{S_{i-1}}} \biggl)
At this time, the volatility of the stock from the start date to n business days later is defined by the following formula.
vol_{n} = \sqrt{\sum_{i=1}^{n} {(c_{i}-\bar{c})}^{2}}
test.py
#Annual volatirity(Setting trading date 252 days)A function that calculates.
def volatility(DF):
df = DF.copy()
df["daily_ret"] = DF["Close"].pct_change()
vol = df["daily_ret"].std() * np.sqrt(252)
return vol
Recommended Posts