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()
Beispiel #2
0
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)
with pd.ExcelWriter('{}/deepOptionChain_[{}].xlsx'.format(path,
                                                          exp)) as writer:
    data.to_excel(writer, sheet_name='Chain', index=False)
Beispiel #3
0
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