def main(): # -------------------------[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) # ---------------------------------------------------------- start_time = time.time() impliedVolatility = ImpliedVolatility(optionChain) curve = impliedVolatility.getImpliedVolatility() print('chrono: {}'.format(time.time() - start_time)) fig, ax = plt.subplots(figsize=(8, 5)) ax.set(xlabel='Strike', ylabel='Volatility', title='Option implied volatility ({})'.format( ticker.getInfo().ticker)) ax.plot(curve.calls.strike, curve.calls.IV, label='Calls', color='green', alpha=.5) ax.plot(curve.puts.strike, curve.puts.IV, label='Puts', color='red', alpha=.5) ax.plot(curve.calls.strike, curve.calls.naturalIV, linestyle='dotted', label='Original Calls', color='green') ax.plot(curve.puts.strike, curve.puts.naturalIV, linestyle='dotted', label='Original Puts', color='red') plt.legend() plt.show()
All rights reserved. This file is part of the EcoFin-Library (https://github.com/LucaCamerani/EcoFin-Library), and is released under the "BSD Open Source License". """ import os 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)
All rights reserved. This file is part of the EcoFin-Library (https://github.com/LucaCamerani/EcoFin-Library), and is released under the "BSD Open Source License". """ import matplotlib.pyplot as plt import numpy as np from EcoFin.dataDownload.optionsManager import OptionManager from EcoFin.dataDownload.ticker import Ticker from EcoFin.options.blackScholesModel import BSM from EcoFin.stat.equityVolatility import EquityVolatility # -------------------------[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) # ---------------------------------------------------------- strikeList = optionChain.getStrikeList() volatility_back = 260 series = ticker.getHistory( end=optionChain.getChainDate()).tail(volatility_back) price = optionChain.getSpotPrice()
This file is part of the EcoFin-Library (https://github.com/LucaCamerani/EcoFin-Library), and is released under the "BSD Open Source License". """ import matplotlib.pyplot as plt import numpy as np import pandas as pd from EcoFin.assetAllocation.markowitzModel import MarkowitzModel from EcoFin.dataDownload.ticker import Ticker market = ['AAPL', 'AMZN', 'CSCO', 'MSFT', 'GOOGL'] marketDataFrame = pd.DataFrame(columns=market) for company in market: ticker = Ticker(company) df = ticker.getHistory().tail(260) marketDataFrame[company] = df['Close'] model = MarkowitzModel(marketDataFrame) randW = model.randomWeights(10000) rets = [] stds = [] for r in randW: performance = model.portfolioPerformance(r) rets.append(performance.ret) stds.append(performance.std) plt.scatter(stds,
Created by Luca Camerani at 31/08/2020, University of Milano-Bicocca. ([email protected]) All rights reserved. This file is part of the EcoFin-Library (https://github.com/LucaCamerani/EcoFin-Library), and is released under the "BSD Open Source License". """ import time import matplotlib.pyplot as plt from EcoFin.dataDownload.ticker import Ticker from EcoFin.options.optionChain import OptionChain ticker = Ticker('MSFT') i = 0 while time.time() >= ticker.optionsExp[i]: i += 1 exp = ticker.optionsExp[i] optionChain = OptionChain(ticker, expiration=exp) data = getPricesCurve(optionChain) fig, ax = plt.subplots() for type in ['call', 'put']: if type == 'call': ax.plot(data.call['strike'], data.call['prices'], label=type) else:
import os import matplotlib.pyplot as plt import numpy as np import pandas as pd import tqdm from mpl_toolkits.mplot3d import axes3d from EcoFin.dataDownload.optionsManager import OptionManager from EcoFin.dataDownload.ticker import Ticker from EcoFin.options.deepOptionSurface import DeepOptionSurface from EcoFin.options.utils import daysToMaturity # ---------------------------[Set-Up]-------------------------------- ticker = Ticker('MSFT') increment = 86400 # 1 day date1 = 1551657600 # Monday 4 March 2019 date2 = date1 + increment * 1 # ------------------------------------------------------------------- for now in tqdm.tqdm(range(date1, date2, increment), desc='Generate frames'): # Compute day by day try: optionManager = OptionManager(ticker, now=now) optSurface = optionManager.getOptionSurface() deepSurface = DeepOptionSurface(optSurface, computeIV=False, computeBSM=False, progressBar=False)
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
All rights reserved. This file is part of the EcoFin-Library (https://github.com/LucaCamerani/EcoFin-Library), and is released under the "BSD Open Source License". """ import matplotlib.pyplot as plt import numpy as np from EcoFin.dataDownload.optionsManager import OptionManager from EcoFin.dataDownload.ticker import Ticker from EcoFin.options.impliedVolatility import ImpliedVolatility from EcoFin.options.volatilitySmile import VolatilitySmile # -------------------------[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) # ---------------------------------------------------------- price = optionChain.getSpotPrice() forwardPrice = optionChain.getForwardPrice() impliedVolatility = ImpliedVolatility(optionChain) volatilitySmile = VolatilitySmile(impliedVolatility) smile = volatilitySmile.getVolatilitySmile()
and is released under the "BSD Open Source License". """ import os from datetime import datetime import matplotlib.pyplot as plt import numpy as np 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=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()) history_back = 100
This file is part of the EcoFin-Library (https://github.com/LucaCamerani/EcoFin-Library), and is released under the "BSD Open Source License". """ import matplotlib.pyplot as plt import numpy as np from EcoFin.dataDownload.optionsManager import OptionManager from EcoFin.dataDownload.ticker import Ticker from EcoFin.options.chainWeights import ChainWeights from EcoFin.options.impliedVolatility import ImpliedVolatility from EcoFin.options.volatilitySmile import VolatilitySmile # -------------------------[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) # ---------------------------------------------------------- fig, axs = plt.subplots(2, figsize=(15, 8), sharex=True) fig.suptitle('Weigh implied volatility ({})'.format(ticker.getInfo().ticker), fontsize=16) forwardPrice = optionChain.getForwardPrice() impliedVolatility = ImpliedVolatility(optionChain) volatilitySmile = VolatilitySmile(impliedVolatility)
""" tickerHistory.py Created by Luca Camerani at 06/10/2020, University of Milano-Bicocca. ([email protected]) All rights reserved. This file is part of the EcoFin-Library (https://github.com/LucaCamerani/EcoFin-Library), and is released under the "BSD Open Source License". """ import matplotlib.pyplot as plt from EcoFin.dataDownload.ticker import Ticker ticker = Ticker('MSFT') history = ticker.getHistory().tail(100) plt.plot(history.index, history.Close, label='Price ($S_t$)') plt.show() print(ticker.getInfo())