I'm trying to keep this as simple as possible, while keeping the object oriented in-tact. I'm a beginner, but I'm struggling to figure out why I'm getting the error below and how to correct it, while keeping the object oriented style in-tact.
import json
from datetime import datetime, timedelta
from dateutil import tz
import numpy as np
import pandas as pd
import requests
def run(ticker):
today_date, data = scrape_data(ticker)
calculate_gamma_levels(today_date,data)
def scrape_data(ticker):
#Scrape data from CBOE website
raw_data = requests.get(f"https://cdn.cboe.com/api/global/delayed_quotes/options/{ticker}.json")
dict_data = pd.DataFrame.from_dict(raw_data.json())
data = pd.DataFrame(dict_data.loc["options", "data"])
data_update_time = dict_data.timestamp[0]
data["data_update_time"] = data_update_time
data["expiration_date"] = str(20)+ data.option.str.extract(r"[A-Z](\d+)").astype(str)
expiration_date = pd.to_datetime(data["expiration_date"], format="%Y-%m-%d")
print(expiration_date)
today_date = data["data_update_time"][0]
today_date = datetime.strptime(str(today_date), "%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d")
data["today_date"] = today_date
return data, today_date
def calculate_gamma_levels(today_date,data):
print(today_date)
data['days_till_exp'] = [1/262 if (np.busday_count(today_date.date(), x.date())) == 0 \
else np.busday_count(today_date.date(), x.date())/262 for x in int(data["expiration_date"])]
next_expire = data['expiration_date'].min()
if __name__ == "__main__":
ticker = "SPY"
run(ticker)
The error that I'm getting is the following:
File "c:\python\example option date.py", line 46, in calculate_gamma_levels
else np.busday_count(today_date.date(), x.date())/262 for x in int(data["expiration_date"])]
TypeError: string indices must be integers
I've tried doing the following and several other attempts on the expiration date, but had no success and continued to get the error above.
# expiration_date = datetime.strptime(str(data["expiration_date"].values), "%Y%m%d").strftime("%Y-%m-%d")
# expiration_date = datetime.strptime(str(data["expiration_date"]), "%Y%m%d").strftime("%Y-%m-%d")
print(expiration_date)
# print(data["expiration_date"])
# data["expiration_date"] = pd.to_datetime(data["expiration_date"], format="%Y%m%d")
#print(data["expiration_date"])