Python, risk finance, volatility, financial markets, volatility measurement, financial data
This project aims to investigate and analyze volatility in financial markets using Python. Volatility is a critical parameter in finance, influencing risk management, pricing models, and investment strategies.
The project focuses on developing Python-based tools to measure, model, and analyze volatility, utilizing real-world financial data.
[...] This function should be vectorized as above. [...]
[...] Why the benchmark volatility is lower ? This indicates that AAPL's price experiences larger fluctuations and is considered to be riskier than SPY based on this measure. [source, ipython3] benchmark_df = get_stock_data("SPY", start_date, end_date) historical_volatility_bm = calculate_historical_volatility(benchmark_df) def plot_return_volatility_with_benchmark(stock_data, historical_volatility, benchmark_historical_volatility): fig = plt.figure(figsize=(15, color = 'tab:red' ax1 = fig.add_subplot( price = stock_data["Adj Close"] price.plot(ax=ax1, color=color) ax1.set_xlabel('Date') ax1.set_ylabel('Stock price', color=color) ax1.set_title('Stock price and historical volatility') ax1.tick_params(axis='y', labelcolor=color) color = 'tab:blue' ax2 = ax1.twinx() ax2.set_ylabel('Volatility color=color) vol = historical_volatility*100 vol.plot(ax=ax2, color=color) ax2.tick_params(axis='y', labelcolor=color) color = volbm = benchmark_historical_volatility*100 volbm.plot(ax=ax2, color=color) plt.show() plot_return_volatility_with_benchmark(stock_df.loc['2021-01-01':'2023-01-01'], historical_volatility.loc['2021-01-01':'2023-01-01'], historical_volatility_bm.loc['2021-01-01':'2023-01-01']) [png](output_16_1.png) [source, ipython3] historical_volatility_bm_bis = calculate_historical_volatility(benchmark_df, 252) plot_return_volatility_with_benchmark(stock_df.loc['2021-01-01':'2023-01-01'], historical_volatility_bis.loc['2021-01-01':'2023-01-01'], historical_volatility_bm_bis.loc['2021-01-01':'2023-01-01']) [png](output_17_0.png) Once again take time windows = 252 to have similar graph than in the example 1.2) Optional: plot high volatility periods on the graph [source, ipython3] def detect_high_volatility_periods(historical_volatility, threshold=30): Detect periods of high volatility based on a threshold. [...]
[...] Do you see anything familiar ? [source, ipython3] def plot_option_price_vs_spot(S_range, options_prices): Plot option price vs. spot value for a call option. Parameters: - S_range: Range of spot values - options_prices: list of options price fig = plt.figure(figsize=(10,7.5)) ax = fig.add_subplot(111) for ydata in options_prices: plot, = ax.plot(S_range, ydata) plt.xlabel('Spot value plt.ylabel(' Option price') plt.title(' Option price vs Spot value') plt.show() S_range = np.linspace( 100) T_range = np.array([ 0.01]) sigma = 0.2 K=100 r = 0.05 options_prices = for t in T_range: options_prices.append(black_scholes_vectorized(S_range, sigma)) plot_option_price_vs_spot(S_range, options_prices) [png](output_27_0.png) [source, ipython3] options_prices Write a function to compute implied volatility. [...]
[...] - end_date End date in the format 'YYYY-MM-DD'. Returns: - DataFrame: Historical stock data with Date as the index. stock_data = yf.download(ticker, start_date, end_date) return stock_data def calculate_historical_volatility(stock_data, window_size=21): Calculate historical volatility of a stock. Parameters: - stock_data: Stock symbol data - window_size: Rolling window size for calculating volatility (default is 21) Returns: - historical_volatility: Pandas Series with historical volatility values # Calculate logarithmic returns on 'Adj Close' stock_data['log_return'] = np.log1p(stock_data["Adj Close"].pct_change()) #stock_data['log_return'] = np.log(stock_data["Adj Close"]) - np.log(stock_data["Adj Close"].shift(1)) # Calculate historical volatility stock_data["hist_vol"] = np.sqrt(stock_data['log_return'].rolling(window_size).var()) # Annualized historical volatility days_per_year = 252 # trading days per year ann_factor = days_per_year / window_size #stock_data['ann_hist_vol'] = np.sqrt(stock_data['log_return'].rolling(window_size).var() * ann_factor) stock_data['ann_hist_vol'] = np.sqrt(ann_factor)*stock_data["hist_vol"] annualized_historical_volatility = stock_data['ann_hist_vol'] return annualized_historical_volatility ticker_symbol = "AAPL" # Apple Inc. [...]
[...] Exploring Volatility Dynamics in Financial Markets This project aims to investigate and analyze volatility in financial markets using Python. Volatility is a critical parameter in finance, influencing risk management, pricing models, and investment strategies. The project focuses on developing Python-based tools to measure, model, and analyze volatility, utilizing real-world financial data. [source, ipython3] #Import libraries import yfinance as yf import pandas as pd import matplotlib.pyplot as plt import numpy as np from scipy.stats import norm import seaborn as sns Volatility Measurement Implement and compare different volatility measures (e.g., historical volatility, implied volatility) 1.1) Historical volatility [source, ipython3] # Function to fetch historical stock price data def get_stock_data(ticker, start_date, end_date): Retrieve historical stock data for a given symbol and date range. [...]
APA Style reference
For your bibliographyOnline reading
with our online readerContent validated
by our reading committee