def __init__(self, deepOptionChain: DeepOptionChain, volatilityBack=260): self.optionChain = deepOptionChain.getOptionChain() self.deepChain = deepOptionChain.getDeepOptionChain() self.chainWeights = ChainWeights(self.optionChain) if deepOptionChain.computeIV: self.smile = self.deepChain.smile else: self.smile = None ticker = self.optionChain.getTicker() self.history = ticker.getHistory( end=self.optionChain.getChainDate()).tail(volatilityBack)
def __init__(self, deepOptionChain: DeepOptionChain, weights): """ weightsMode: * EW -> equally weighted (default); * ATM * OI -> open interest; """ self.deepOptionChain = deepOptionChain self.deepChain = deepOptionChain.getDeepOptionChain() self.optionChain = deepOptionChain.getOptionChain() self.data = self.deepChain self.avaiableIV = deepOptionChain.computeIV self.weights = weights
def computeDeepOptionSurface(self): deep_data = {} for expiration in tqdm(self.optionSurface.getExpirations(), desc='Compute IV surface', disable=not self.progressBar): chain = self.getOptionSurface().getChainByDate(expiration) deep_data[expiration] = DeepOptionChain(chain, computeIV=self.computeIV, computeBSM=self.computeBSM, progressBar=False) return deep_data
import pandas as pd from EcoFin.dataDownload.optionsManager import OptionManager from EcoFin.dataDownload.ticker import Ticker from EcoFin.options.deepOptionChain import DeepOptionChain # -------------------------[Set-up]------------------------- ticker = Ticker('MSFT') optionManager = OptionManager(ticker) exp = optionManager.getExpirationByMaturity(30, method='greater') optionChain = optionManager.getOptionChain(exp=exp) # ---------------------------------------------------------- ticker_info = ticker.getInfo() forwardPrice = optionChain.getForwardPrice() deepOptionChain = DeepOptionChain(optionChain, computeIV=False) data = deepOptionChain.getDeepOptionChain() # ----------------------[EXPORT BLOCK]-------------------------------- path = '../Export/[{}]'.format(ticker.ticker) if not os.path.exists(path): os.makedirs(path) with pd.ExcelWriter('{}/deepOptionChain_[{}].xlsx'.format(path, exp)) as writer: data.to_excel(writer, sheet_name='Chain', index=False) print('\nFile saved!') # ----------------------[EXPORT BLOCK]--------------------------------
from EcoFin.dataDownload.optionsManager import OptionManager from EcoFin.dataDownload.ticker import Ticker from EcoFin.options.deepOptionChain import DeepOptionChain from EcoFin.stat.utils import weightedAvg, weightedStd # -------------------------[Set-up]------------------------- ticker = Ticker('MSFT') optionManager = OptionManager(ticker, now=1492646400) exp = optionManager.getExpirationByMaturity(30, method='greater') optionChain = optionManager.getOptionChain(exp=exp) # ---------------------------------------------------------- ticker_info = ticker.getInfo() forwardPrice = optionChain.getForwardPrice() deepOptionChain = DeepOptionChain(optionChain) data = deepOptionChain.getDeepOptionChain() data['weights'] = data.loc[:, ['openInterest_call', 'openInterest_put']].sum(axis=1) / \ np.nansum(data.loc[:, ['openInterest_call', 'openInterest_put']].to_numpy()) fig, axs = plt.subplots(2, gridspec_kw={'height_ratios': [3, 2]}, figsize=(10, 5), sharex=True) """ # chart 1 axs[0].plot(data.strike, data['TheoPrice_call'], linewidth=3, label='Theoretical call', color='green') axs[0].plot(data.strike, data['TheoPrice_put'], linewidth=3, label='Theoretical put', color='red') axs[0].plot(data.strike, data.avgPrice_call, linewidth=3, linestyle="dashed", label='$Call_{AVG}$') axs[0].plot(data.strike, data.avgPrice_put, linewidth=3, linestyle="dashed", label='$Put_{AVG}$')
# Custom increment = 86400 # 1 day date1 = 1483228800 # Sunday 01 January 2017 date2 = date1 + increment * 365 * 3 # ---------------------------------------------------------- ticker_info = ticker.getInfo() output = [] for now in tqdm(range(date1, date2, increment), desc='Compute history'): # Compute day by day if optionManager.setNow(now) is not False: exp = optionManager.getExpirationByMaturity(5, method='greater') optionChain = optionManager.getOptionChain(exp=exp) deepOptionChain = DeepOptionChain(optionChain, computeIV=True, progressBar=False) VIX = EquityVIX(deepOptionChain) summary = { 'Date': unixtimestamp_to_date(optionChain.getChainDate()), 'SpotPrice': optionChain.getSpotPrice(), 'CBOE_VIX': VIX.getCBOEVIX(), 'Mean': VIX.getMeanVIX().value, 'Beta': VIX.getBetaVIX().value, 'ATM': VIX.getATMVIX().value, 'OI': VIX.getOpenInterestVIX().value } if len(output) == 0:
from EcoFin.dataDownload.optionsManager import OptionManager from EcoFin.dataDownload.ticker import Ticker from EcoFin.options.chainWeights import ChainWeights from EcoFin.options.deepOptionChain import DeepOptionChain from EcoFin.options.optionChainSynopsis import OptionChainSinopsys # -------------------------[Set-up]------------------------- ticker = Ticker('MSFT') optionManager = OptionManager(ticker) exp = optionManager.getExpirationByMaturity(30, method='greater') optionChain = optionManager.getOptionChain(exp=exp) # ---------------------------------------------------------- ticker_info = ticker.getInfo() deepOptChain = DeepOptionChain(optionChain, True) chainWeights = ChainWeights(optionChain) for mode, weights in { 'EW': chainWeights.computeEquallyWeights(), 'Beta': chainWeights.computeBetaWeights(), 'ATM': chainWeights.computeATMWeights(), 'OI': chainWeights.computeOpenInterestsWeights(), 'Moneyness': chainWeights.computeMoneynessWeights() }.items(): print('----[{}]----'.format(mode)) synopsis = OptionChainSinopsys(deepOptChain, weights=weights) OPS = synopsis.computeOptionPriceSpread() print('OPS:\n • {}\n • {}'.format(OPS.mean, OPS.std))
def execute(tick: str): ticker = Ticker(tick) optionManager = OptionManager(ticker) output = pd.DataFrame for now in range(date1, date2, increment): # Compute day by day try: # Exclude bad results and weekends if optionManager.setNow(now) is not False and datetime.fromtimestamp(now).weekday() not in [5, 6]: exp = optionManager.getExpirationByMaturity(maturity_min, method='greater') optionChain = optionManager.getOptionChain(exp=exp) deepOptionChain = DeepOptionChain(optionChain, computeIV=computeIV, progressBar=False) summary = {'Date': unixtimestamp_to_date(optionChain.getChainDate()), 'Exp': unixtimestamp_to_date(optionChain.getChainExpiration()), 'Maturity': optionChain.getTimeToMaturity().days, 'ForwardPrice': optionChain.getForwardPrice(), 'SpotPrice': optionChain.getSpotPrice(), } # compute signals chainWeights = ChainWeights(optionChain) for mode, weights in {'EW': chainWeights.computeEquallyWeights(), 'Beta': chainWeights.computeBetaWeights(), 'ATM': chainWeights.computeATMWeights(), 'OI': chainWeights.computeOpenInterestsWeights(), 'Moneyness': chainWeights.computeMoneynessWeights()}.items(): synopsis = OptionChainSinopsys(deepOptionChain, weights=weights) OPS = synopsis.computeOptionPriceSpread() IVS = synopsis.computeImpliedVolatilitySpread() NAP = synopsis.computeNoArbitragePrice() OIR = synopsis.computeOpenInterestRatio() summary['OPS_[{}]'.format(mode)] = OPS.mean summary['IVS_[{}]'.format(mode)] = IVS.mean summary['NAP_[{}]'.format(mode)] = NAP.value summary['NAP_ret_[{}]'.format(mode)] = NAP.ret summary['OIR_[{}]'.format(mode)] = OIR.mean PCD = synopsis.computePutCallDelta() summary['PCD'] = PCD # Compute volatility metrics VIX = EquityVIX(deepOptionChain) summary['VIX_[hist]'] = VIX.getHistoricalVolatility() summary['VIX_[mean]'] = VIX.getMeanVIX().value summary['VIX_[beta]'] = VIX.getBetaVIX().value summary['VIX_[CBOE]'] = VIX.getCBOEVIX() if output.empty: output = pd.DataFrame(columns=list(summary.keys()), index=[]) output = output.append(summary, ignore_index=True) except Exception as e: logs.append('Error with [{}] - [{}]: {}'.format(ticker.ticker, now, e)) pass # ----------------------[EXPORT BLOCK]-------------------------------- path = '../Export/BackTest/{}'.format(ticker.ticker) if not os.path.exists(path): os.makedirs(path) try: with pd.ExcelWriter('{}/backTest_[{}].xlsx'.format(path, maturity_min)) as writer: output.to_excel(writer, sheet_name='Results', index=False) except: pass
from EcoFin.dataDownload.optionsManager import OptionManager from EcoFin.dataDownload.ticker import Ticker from EcoFin.options.deepOptionChain import DeepOptionChain from EcoFin.options.equityVIX import EquityVIX # -------------------------[Set-up]------------------------- ticker = Ticker('MSFT') optionManager = OptionManager(ticker, now=None) i = 0 # <- Time To Maturity curve exp = optionManager.getExpirations()[i] optionChain = optionManager.getOptionChain(exp=exp) # ---------------------------------------------------------- deepOptionChain = DeepOptionChain(optionChain) equityVIX = EquityVIX(deepOptionChain) VIX = { 'MeanVIX': equityVIX.getMeanVIX().value, 'BetaVIX': equityVIX.getBetaVIX().value, 'CBOEVIX': equityVIX.getCBOEVIX(), 'Historical': equityVIX.getHistoricalVolatility(), 'VE': equityVIX.getVolatilityExcess() } print('\n---------------------------') print(' • Mean VIX: {}'.format(VIX['MeanVIX'])) print(' • Beta VIX: {}'.format(VIX['BetaVIX'])) print(' • CBOE VIX: {}'.format(VIX['CBOEVIX'])) print(' • Historical volatility: {}'.format(VIX['Historical']))
This file is part of the EcoFin-Library (https://github.com/LucaCamerani/EcoFin-Library), and is released under the "BSD Open Source License". """ import pandas as pd from EcoFin.dataDownload.optionsManager import OptionManager from EcoFin.dataDownload.ticker import Ticker from EcoFin.options.deepOptionChain import DeepOptionChain # -------------------------[Set-up]------------------------- ticker = Ticker('MSFT') optionManager = OptionManager(ticker, now=None) i = 0 # <- Time To Maturity curve exp = optionManager.getExpirations()[i] optionChain = optionManager.getOptionChain(exp=exp) # ---------------------------------------------------------- chain = optionChain.getChain() deepChain = DeepOptionChain(optionChain).getDeepOptionChain() path = '../Export/[{}]_deepOptionChain.xlsx'.format(ticker.ticker) with pd.ExcelWriter(path) as writer: chain.full.to_excel(writer, sheet_name='Chain') deepChain.to_excel(writer, sheet_name='Deep Chain') print('file saved! ({})'.format(path))