import os
import sys
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import date
from time import time
import re
import http.client
import thetadata
from thetadata import ThetaClient, DateRange, StockReqType, SecType, OptionRight, OptionReqType
# Create timer wrapper
def timer(func):
def wrap_func(*args, **kwargs):
t1 = time()
result = func(*args, **kwargs)
t2 = time()
print(f'\nfunction {func.__name__!r} executed in {(t2-t1):.4f}s')
return result
return wrap_func
@timer
def options_quote(exp_date: str = '0', ticker: str = 'SPX'):
conn = http.client.HTTPConnection("127.0.0.1:25510")
headers = { 'Accept': "application/json" }
conn.request("GET", f"/bulk_snapshot/option/quote?root={ticker}&exp={exp_date}", headers=headers)
res = conn.getresponse()
data = res.read()
#print(data.decode("utf-8"))
s = str(data, 'utf-8')
list_s = s.split('},')
columns = list_s[0]
columns = columns.split('\t')
columns = list(filter(None, columns))
columns = columns[-1].split(':')[1].split('[')[1].split(']')[0].split(',')
columns = [''.join(filter(str.isalnum, cols)) for cols in columns]
columns = columns + ['ticker', 'expiration', 'strike', 'option type']
def clean_data(d):
d = data[0]
d = d.split('\t')
d = list(filter(None, d))
d = d[3:-1]
d.remove(d[1])
d = [_.replace(f"\n", '') for _ in d]
d = [_.replace(f"", '') for _ in d]
d = [_.split(':') for _ in d]
vals = [_[1] for _ in d]
tick = vals[0]
tick = tick.replace('[', '')
tick = tick.replace(']', '')
tick = tick[:-1].strip()
tick = tick.split(',')
vals = tick + [''.join(filter(str.isalnum, _)) for _ in vals[1:]]
return vals
data = list_s[1:]
data = [clean_data(d) for d in data]
df = pd.DataFrame(data=data, columns=columns)
return df
df = options_quote()
df