2024-02-08 11:22:31 +00:00
|
|
|
from datetime import datetime
|
|
|
|
from dotenv import load_dotenv
|
|
|
|
from os import getenv
|
|
|
|
|
|
|
|
from tradestation import TradeStationClient
|
|
|
|
|
|
|
|
from option_type import OptionType
|
|
|
|
|
|
|
|
load_dotenv()
|
|
|
|
|
|
|
|
class OptionsChain:
|
|
|
|
|
|
|
|
def __init__(self, symbol, expiration):
|
|
|
|
self.symbol = symbol
|
|
|
|
self.expiration = expiration
|
|
|
|
self.options_chain = self.get_options_chain(symbol, expiration)
|
|
|
|
|
|
|
|
def get_options_chain(self, symbol: str, expiration: datetime):
|
|
|
|
tradestation_client = TradeStationClient(getenv('TRADESTATION_REFRESH_TOKEN'))
|
|
|
|
return tradestation_client.get_options_chain(symbol, expiration)
|
|
|
|
|
|
|
|
def options_by_type(self, option_type: OptionType):
|
|
|
|
return self.options_chain[self.options_chain['Type'] == option_type.value].copy()
|
|
|
|
|
|
|
|
def closest_contract_by_credit(self, target_credit: float, option_type: OptionType):
|
|
|
|
options = self.options_by_type(option_type)
|
|
|
|
options['Credit Distance'] = abs(options['Bid'] - target_credit)
|
|
|
|
return options.loc[options['Credit Distance'].idxmin()]
|
|
|
|
|
|
|
|
def closest_contract_by_delta(self, target_delta: float, option_type: OptionType):
|
|
|
|
options = self.options_by_type(option_type)
|
|
|
|
options['Delta Distance'] = abs(options['Delta'] - target_delta)
|
|
|
|
return options.loc[options['Delta Distance'].idxmin()]
|
|
|
|
|
|
|
|
def closest_contract_by_strike(self, target_strike: float, option_type: OptionType):
|
|
|
|
options = self.options_by_type(option_type)
|
|
|
|
options['Strike Distance'] = abs(options['Strike'] - target_strike)
|
2024-02-13 16:36:20 +00:00
|
|
|
return options.loc[options['Strike Distance'].idxmin()]
|
|
|
|
|
|
|
|
def __repr__(self) -> str:
|
2024-02-22 21:15:15 +00:00
|
|
|
return self.options_chain.to_string()
|
2024-02-13 20:19:30 +00:00
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
options_chain = OptionsChain('$SPXW.X', datetime.now())
|
|
|
|
print(options_chain)
|
|
|
|
print(options_chain.closest_contract_by_credit(5.0, OptionType.PUT))
|