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()
Esempio n. 2
0
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)
with pd.ExcelWriter('{}/deepOptionChain_[{}].xlsx'.format(path,
Esempio n. 3
0
"""

import os

import matplotlib.pyplot as plt
from tqdm import tqdm

from EcoFin.dataDownload.optionsManager import OptionManager
from EcoFin.dataDownload.ticker import Ticker
from EcoFin.options.deepOptionChain import DeepOptionChain
from EcoFin.options.equityVIX import EquityVIX
from EcoFin.utils.utils import *

# -------------------------[Set-up]-------------------------
ticker = Ticker('MSFT')
optionManager = OptionManager(ticker)

# 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)
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()

r = optionChain.getRiskFreeRate()
Esempio n. 5
0
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)

        # get IV surface data
        exps = optSurface.getExpirations()

        fig = plt.figure(figsize=(15, 10))
        fig.suptitle('Option Prices Spread Analysis', fontsize=16)

        # Plot option price surfaces
        ax = fig.add_subplot(211, projection='3d')
        ax.set_title('Option Prices Surfaces')
"""
surfaceAnalysis.py

Created by Luca Camerani at 11/12/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".
"""

from EcoFin.dataDownload.optionsManager import OptionManager
from EcoFin.dataDownload.ticker import Ticker

ticker = Ticker('MSFT')
ticker_info = ticker.getInfo()

optionManager = OptionManager(ticker, now=None)
optionSurface = optionManager.getOptionSurface()

print(optionSurface.getChainByMaturity(30))
Esempio n. 7
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
This file is part of the EcoFin-Library (https://github.com/LucaCamerani/EcoFin-Library),
and is released under the "BSD Open Source License".
"""

from EcoFin.dataDownload.optionsManager import OptionManager
from EcoFin.dataDownload.ticker import Ticker

# -------------------------[Set-up]-------------------------
ticker = Ticker('MSFT')

# 1Y
increment = 86400
maturity = 30
date1 = 1546300800
date2 = 1577664000
# ----------------------------------------------------------

optionManager = OptionManager(ticker)
ticker_info = ticker.getInfo()

for now in range(date1, date2, increment):  # Compute day by day
    try:
        optionManager.setNow(now)

        exp = optionManager.getExpirationByMaturity(maturity, 'greater')
        optionChain = optionManager.getOptionChain(exp=exp)

        print('Maturity: {} days'.format(optionChain.getTimeToMaturity().days))
    except:
        pass
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 matplotlib import cm

from EcoFin.dataDownload.optionsManager import OptionManager
from EcoFin.dataDownload.ticker import Ticker
from EcoFin.options.deepOptionSurface import DeepOptionSurface
from EcoFin.options.utils import daysToMaturity

ticker = Ticker('MSFT')
optionManager = OptionManager(ticker, now=1551657600)

optSurface = optionManager.getOptionSurface()
deepSurface = DeepOptionSurface(optSurface, computeIV=True)

# get IV surface data
exps = optSurface.getExpirations()

extraction = ['strike', 'smile']
surfaceData = deepSurface.getDeepChainByDate(exps[0]).getDeepOptionChain()[extraction]. \
    rename(columns={'smile': 'smile_{}'.format(exps[0])})

for exp in exps[1:]:
    currentDeepChain = deepSurface.getDeepChainByDate(exp).getDeepOptionChain()

    surfaceData = pd.merge(surfaceData,