This is just a small notebook/back I run on the cloud to compute the Gamma on XIU/TSX for the day. This take a helluva long time to run, so I should switch to a lighter option model.
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
import re
import pandas as pd
from pprint import pprint
import networkx as nx
import json
import matplotlib.pyplot as plt
#Sci-Kit Learn Classification Trees
import sklearn as skl
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import DecisionTreeRegressor
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import PassiveAggressiveRegressor
from sklearn.linear_model import PassiveAggressiveClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import VotingClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn import tree
# Gensim
import gensim
import gensim.corpora as corpora
from gensim.utils import simple_preprocess
from gensim.models import CoherenceModel
from gensim.test.utils import datapath
import spacy
import csv
!pip install mibian
import mibian as mb
from google.colab import drive
drive.mount('/content/gdrive')
symbol = 'XIU'
datapath = 'https://www.m-x.ca/nego_fin_jour_en.php?symbol='+symbol+'&from=2020-05-05&to=2020-05-05&dnld=1'
raw_dataset = pd.read_csv(datapath)
print(raw_dataset
)
dataset = raw_dataset.iloc[1:]
print(dataset.columns)
sharesFilter = dataset['Symbol'] == symbol
share_data = dataset[sharesFilter]
optionsFilter = dataset['Symbol'] != symbol
option_data = dataset[optionsFilter]
share_data['Date'] = pd.to_datetime(share_data['Date'], unit = 'ns')
option_data['Date'] = pd.to_datetime(option_data['Date'], unit = 'ns')
option_data['Expiry'] = pd.to_datetime(option_data['Expiry Date'], unit = 'ns')
#share_data.set_index('Date')
#option_data.set_index('Date')
option_data['Time_To_Expiry'] = (option_data['Expiry'] - option_data['Date']).dt.days + 1
option_data.loc[(option_data['Time_To_Expiry'] < 1)] = 1
print(raw_dataset['Last Close Price'][0])
#print(option_data[['Symbol', 'Call/Put']])
option_data['Underlying'] = raw_dataset['Last Close Price'][0]
option_data['Call/Put'].loc[option_data['Call/Put'] == 1] = -1 #Set PUTS to -1
option_data['Call/Put'].loc[option_data['Call/Put'] == 0] = 1 #Set CALLS to 1
#share_data = share_data[['Date','Last Close Price']]
option_data = option_data[['Date', 'Symbol', 'Last Close Price','Time_To_Expiry', 'Strike Price', 'Call/Put', 'Underlying', 'Implied Volatility', 'Open Interest']]
print(share_data.tail())
print(option_data.tail())
def parse_gamma(date) :
today_options = option_data.loc[option_data['Date'] == date]
today_options['Delta'] = today_options.apply(lambda a: mb.BS([a['Underlying'], a['Strike Price'], 0, a['Time_To_Expiry']], volatility = a['Implied Volatility']).callDelta, axis = 1)
today_options['Theta'] = today_options.apply(lambda a: mb.BS([a['Underlying'], a['Strike Price'], 0, a['Time_To_Expiry']], volatility = a['Implied Volatility']).callTheta, axis = 1)
today_options['Gamma'] = today_options.apply(lambda a: mb.BS([a['Underlying'], a['Strike Price'], 0, a['Time_To_Expiry']], volatility = a['Implied Volatility']).gamma, axis = 1)
today_options['Vega'] = today_options.apply(lambda a: mb.BS([a['Underlying'], a['Strike Price'], 0, a['Time_To_Expiry']], volatility = a['Implied Volatility']).vega, axis = 1)
today_options['Dollar Gamma'] = today_options['Open Interest'] * today_options['Gamma'] * today_options['Call/Put'] * 100
print(today_options['Dollar Gamma'].cumsum())
return today_options['Dollar Gamma']
def parse_strike_gamma(strike) :
strike_options = option_data.loc[option_data['Strike Price'] == strike]
strike_options['Delta'] = strike_options.apply(lambda a: mb.BS([a['Underlying'], a['Strike Price'], 0, a['Time_To_Expiry']], volatility = a['Implied Volatility']).callDelta, axis = 1)
strike_options['Theta'] = strike_options.apply(lambda a: mb.BS([a['Underlying'], a['Strike Price'], 0, a['Time_To_Expiry']], volatility = a['Implied Volatility']).callTheta, axis = 1)
strike_options['Gamma'] = strike_options.apply(lambda a: mb.BS([a['Underlying'], a['Strike Price'], 0, a['Time_To_Expiry']], volatility = a['Implied Volatility']).gamma, axis = 1)
strike_options['Vega'] = strike_options.apply(lambda a: mb.BS([a['Underlying'], a['Strike Price'], 0, a['Time_To_Expiry']], volatility = a['Implied Volatility']).vega, axis = 1)
strike_options['Dollar Gamma'] = strike_options['Open Interest'] * strike_options['Gamma'] * strike_options['Call/Put'] * 100
print('Strike: %f', strike)
print(strike_options['Dollar Gamma'].sum())
return strike_options['Dollar Gamma']
full_gex = []
day_gex = []
def find_gex() :
for date in share_data['Date'] :
mask = (option_data['Date'] < date)
prior_options = option_data[mask]
for strike in prior_options['Strike Price'] :
strike_gex = parse_strike_gamma(strike)
gex = strike_gex.sum()
day_gex.append(gex)
day_gex_sum = np.sum(day_gex)
full_gex.append(day_gex_sum)
find_gex()
day_gex = parse_gamma(option_data['Date'])
dayGEX = pd.DataFrame(day_gex)
dayGEX['Date'] = share_data['Date']
share_data['GEX'] = day_gex
print(share_data['GEX'])
share_data['Day Move'] = share_data['Last Price'] - share_data['Open Price']
share_data['Day P/L'] = share_data['Day Move'] / share_data['Open Price'] * 100
x = share_data['GEX']
y = share_data['Day P/L']
plt.figure(0)
plt.scatter(x, y)
plt.xlabel('Market Gamma (Billions)')
plt.ylabel('Market P/L (%)')
plt.grid(color='g', linestyle='-', linewidth=0.3)
plt.show()
option_data['Delta'] = option_data.apply(lambda a: mb.BS([a['Underlying'], a['Strike Price'], 0, a['Time_To_Expiry']], volatility = a['Implied Volatility']).callDelta, axis = 1)
option_data['Theta'] = option_data.apply(lambda a: mb.BS([a['Underlying'], a['Strike Price'], 0, a['Time_To_Expiry']], volatility = a['Implied Volatility']).callTheta, axis = 1)
option_data['Gamma'] = option_data.apply(lambda a: mb.BS([a['Underlying'], a['Strike Price'], 0, a['Time_To_Expiry']], volatility = a['Implied Volatility']).gamma, axis = 1)
option_data['Vega'] = option_data.apply(lambda a: mb.BS([a['Underlying'], a['Strike Price'], 0, a['Time_To_Expiry']], volatility = a['Implied Volatility']).vega, axis = 1)
print(option_data[['Delta', 'Theta', 'Vega', 'Gamma']])
option_data['Dollar Gamma'] = option_data['Open Interest'] * option_data['Gamma'] * option_data['Call/Put'] * 100
#(option_data['Open Interest'] * 100 * option_data['Gamma']) * (option_data['Underlying'] ^ 2 / 100)
print(option_data.dtypes)
print(option_data[['Symbol', 'Delta', 'Theta', 'Gamma', 'Dollar Gamma']])
print(option_data['Dollar Gamma'].cumsum())
strike_data = option_data.groupby('Strike Price').cumsum()
print(strike_data['Dollar Gamma'])
output_datapath = '/content/gdrive/My Drive/MX Option Data/TSX_Gamma.csv'
strike_data.to_csv(path_or_buf=output_datapath)