forked from kubadlugosz/algorithmic-trading
-
Notifications
You must be signed in to change notification settings - Fork 0
/
volatility.py
30 lines (24 loc) · 1021 Bytes
/
volatility.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# =============================================================================
# Measuring the volatility of a buy and hold strategy
# Author : Mayank Rasu (http://rasuquant.com/wp/)
# Please report bug/issues in the Q&A section
# =============================================================================
# Import necesary libraries
import yfinance as yf
import numpy as np
# Download historical data for required stocks
tickers = ["AMZN","GOOG","MSFT"]
ohlcv_data = {}
# looping over tickers and storing OHLCV dataframe in dictionary
for ticker in tickers:
temp = yf.download(ticker,period='7mo',interval='1d')
temp.dropna(how="any",inplace=True)
ohlcv_data[ticker] = temp
def volatility(DF):
"function to calculate annualized volatility of a trading strategy"
df = DF.copy()
df["daily_ret"] = DF["Adj Close"].pct_change()
vol = df["daily_ret"].std() * np.sqrt(252)
return vol
for ticker in ohlcv_data:
print("vol for {} = {}".format(ticker,volatility(ohlcv_data[ticker])))