Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Leverage Python for Quantitative Finance
Leverage Python for Quantitative Finance
Volatility is a key factor that affects investment decisions in the stock market. It refers to the amount of fluctuation in the price of a security over a given period of time. There are two main types of volatility: historical volatility and implied volatility. In this post, we will explore the differences between these two types of volatility and how we can use them to make informed investment decisions.
Historical volatility is a measure of the actual volatility of a security over a specific period of time, based on its past price movements. It is calculated by measuring the standard deviation of the security’s daily price changes over the given time period. Historical volatility provides a measure of how much the security has fluctuated in the past and can be used as an indicator of how much it may fluctuate in the future.
Historical volatility is useful for investors who are interested in assessing the risk of a particular security. If a security has a high historical volatility, it may be more risky than a security with a low historical volatility. However, historical volatility is limited in its ability to predict future price movements, as it is based solely on past data.
Implied volatility is a measure of the expected volatility of a security in the future, as implied by the current market price of its options contracts. Implied volatility is derived from the prices of call and put options on the security, which reflect the market’s expectation of how much the security will move up or down in the future.
Implied volatility is useful for investors who are interested in trading options contracts. If the implied volatility of a security is high, it means that the options contracts on that security are more expensive, as the market expects larger price movements in the future. Conversely, if the implied volatility is low, it means that the options contracts are cheaper, as the market expects smaller price movements.
Both historical and implied volatility can be useful for making investment decisions, depending on the specific investment strategy and goals of the investor. Here are some ways that historical and implied volatility can be used for investment decisions:
Historical and implied volatility are important measures of price fluctuation in the stock market. By understanding the differences between these two types of volatility and how they can be used for investment decisions, investors can make more informed decisions and manage their risk effectively. It is important to note that volatility is just one of many factors that affect investment decisions, and investors should consider other factors, such as fundamental analysis and market trends, in their investment strategies.
So, here is an example Python code for a basic stock trading strategy that uses historical and implied volatility:
import yfinance as yf # Set the ticker symbols and date range for the analysis tickers = ['AAPL', 'MSFT', 'AMZN'] start_date = '2019-01-01' end_date = '2021-01-01' # Get the historical price data for the selected tickers data = yf.download(tickers, start=start_date, end=end_date) # Calculate the historical volatility for each ticker historical_volatility = data['Adj Close'].pct_change().rolling(window=252).std() * np.sqrt(252) # Calculate the implied volatility for each ticker using the Black-Scholes model from scipy.stats import norm def black_scholes(S, K, r, T, sigma, option='call'): d1 = (np.log(S/K) + (r + 0.5*sigma**2)*T) / (sigma*np.sqrt(T)) d2 = d1 - sigma*np.sqrt(T) if option == 'call': return S*norm.cdf(d1) - K*np.exp(-r*T)*norm.cdf(d2) elif option == 'put': return K*np.exp(-r*T)*norm.cdf(-d2) - S*norm.cdf(-d1) implied_volatility = pd.DataFrame(index=data.index, columns=tickers) for ticker in tickers: option_chain = yf.Ticker(ticker).option_chain('2021-12-17') option_data = option_chain.calls.iloc[0] S = data['Adj Close'][ticker][-1] K = option_data['strike'] r = 0.02 T = (pd.Timestamp('2021-12-17') - pd.Timestamp.today()).days / 365 C = option_data['lastPrice'] # Use the Black-Scholes model to estimate the implied volatility implied_volatility[ticker] = black_scholes(S, K, r, T, sigma, option='call') # Create a trading signal based on the difference between historical and implied volatility trading_signal = (implied_volatility - historical_volatility).apply(np.sign) # Calculate the returns of the trading strategy returns = (data['Adj Close'].pct_change() * trading_signal.shift(1)).sum(axis=1) # Plot the returns of the trading strategy import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(10, 5)) returns.cumsum().plot(ax=ax) ax.set(title='Historical vs Implied Volatility Trading Strategy', ylabel='Cumulative Returns')
In this example, we first set the ticker symbols and date range for the analysis, and then use the yfinance
library to download the historical price data for the selected tickers. We then calculate the historical volatility for each ticker using the rolling
function, which calculates the standard deviation of the daily percentage changes over a rolling window of 252 days (1 trading year), multiplied by the square root of 252 to annualize the volatility.
Next, we use the Black-Scholes model to estimate the implied volatility for each ticker, based on the market prices of call options expiring on December 17, 2021. We assume a constant risk-free rate of 2% and estimate the implied volatility using the black_scholes
function, which calculates the option price using the Black-Scholes formula and solves for the implied volatility.
We then create a trading signal based on the difference between historical and implied volatility, using the apply
and np.sign
functions to determine whether the implied volatility is higher or lower than the historical volatility. If the implied volatility is higher, we assume that the market is expecting higher volatility in the future and take a short position in the stock, while if the implied volatility is lower, we assume that the market is expecting lower volatility in the future and take a long position in the stock.
Finally, we calculate the returns of the trading strategy by multiplying the daily percentage changes in the stock prices by the trading signal from the previous day and summing over all the tickers. We then plot the cumulative returns of the trading strategy over the analysis period.