Add logic for retrieving options chain data

This commit is contained in:
moshferatu 2023-10-23 12:23:31 -07:00
parent c94d03fc17
commit 1b853f34cf
3 changed files with 53 additions and 1 deletions

View File

@ -1 +1,2 @@
from .insert import insert
from .insert import insert
from .options_chain import options_chain

View File

@ -0,0 +1,39 @@
import pandas as pd
from datetime import datetime
from dotenv import load_dotenv
from os import getenv
from sqlalchemy import create_engine
load_dotenv()
def options_chain(symbol: str, date: datetime, expiration: datetime, timestamp: datetime):
"""
Retrieve options chain data for the specified symbol, date, expiration, and timestamp.
Example Usage:
data = options_chain('AAPL', datetime(2023, 9, 20), datetime(2023, 12, 17), datetime(2023, 9, 20, 14, 30, 0))
:param symbol: The stock, etf, etc. symbol.
:param date: The date for which data is being requested.
:param expiration: The expiration date of the options.
:param timestamp: The specific timestamp for which the options chain data is requested.
:return: A pandas DataFrame containing the options chain data.
"""
database_url = (
f"postgresql+psycopg2://{getenv('DATABASE_USER')}:{getenv('DATABASE_PASSWORD')}"
f"@{getenv('DATABASE_HOST')}:{getenv('DATABASE_PORT')}/{getenv('DATABASE_NAME')}"
)
engine = create_engine(database_url)
query = f"""
SELECT *
FROM "Options"
WHERE "Symbol" = %s AND "Date" = %s AND "Expiration" = %s AND "Timestamp" = %s
ORDER BY "Strike", "Type";
"""
params = (symbol, date, expiration, timestamp)
return pd.read_sql_query(query, engine, params=params)

12
options_chain_example.py Normal file
View File

@ -0,0 +1,12 @@
from database.options import options_chain
from datetime import datetime
timestamp = datetime(2023, 10, 6, 9, 35, 0)
data = options_chain(
symbol='SPX',
date=timestamp.date(),
expiration=datetime(2023, 10, 13),
timestamp=timestamp)
print(data)