Beispiel #1
0
    def computeImpliedVolatility(self):
        output = {}
        for type, contracts in tqdm({
                'call': self.chain.calls,
                'put': self.chain.puts
        }.items(),
                                    desc='Compute ImpliedVolatility',
                                    disable=not self.progressBar):
            IVs = []
            d2 = []
            for index, contract in contracts.iterrows():
                strike = contract['strike']

                marketPrice = contract['avgPrice']
                option = BSM(self.underliyngPrice, strike, self.r, None,
                             self.maturity.days)

                IV = option.getImpliedVolatility(marketPrice, type)
                IVs.append(IV)

                d2.append(option.computeValues(sigma=IVs[-1]).d2)

            if self.interpolate:
                IVs = interpolateNaN(IVs)
                d2 = interpolateNaN(d2)

            contracts['IV'] = IVs
            contracts['d2'] = d2
            output[type] = contracts.rename(
                columns={'impliedVolatility': 'naturalIV'})

        return namedtuple('IV', ['calls', 'puts'])(**{
            "calls": output['call'],
            "puts": output['put'],
        })
"""
optionGreeks.py

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".
"""

from EcoFin.options.blackScholesModel import BSM

option = BSM(100, 100, 0.05, 0.2, 70)

print(option.computeValues())
# -----
print(option.price())
print('Greeks:')
print(' • {}'.format(option.delta()))
print(' • {}'.format(option.gamma()))
print(' • {}'.format(option.theta()))
print(' • {}'.format(option.vega()))
print(' • {}'.format(option.rho()))
    end=optionChain.getChainDate()).tail(volatility_back)
price = optionChain.getSpotPrice()

r = optionChain.getRiskFreeRate()
sigma = EquityVolatility(series).meanSigma()
maturity = optionChain.getTimeToMaturity().days

forwardPrice = optionChain.getForwardPrice()

fig, ax = plt.subplots()

chain = optionChain.getChain()
theoreticalPrices = {'call': [], 'put': []}

for strike in strikeList:
    option = BSM(price, strike, r, sigma, maturity)
    optPrice = option.computePrice()

    theoreticalPrices['call'].append(optPrice.call)
    theoreticalPrices['put'].append(optPrice.put)

ax.plot(strikeList,
        theoreticalPrices['call'],
        linestyle="dotted",
        label='Theoretical call')
ax.plot(strikeList,
        theoreticalPrices['put'],
        linestyle="dotted",
        label='Theoretical put')

ax.plot(chain.calls.strike, chain.calls.avgPrice, label='$Call_{AVG}$')
Beispiel #4
0
    def computeDeepOptionChain(self):
        ticker = self.optionChain.getTicker()
        series = ticker.getHistory(period="1y", interval="1d")
        price = self.optionChain.getSpotPrice()

        r = self.optionChain.getRiskFreeRate()
        sigma = EquityVolatility(series).meanSigma()
        maturity = self.optionChain.getTimeToMaturity()

        chain = self.optionChain.getChain()

        # compute theoretical prices
        data = chain.full.copy()
        if self.computeBSM:
            data['TheoPrice_call'] = None
            data['TheoPrice_put'] = None
            for strike in data.strike:
                if self.optionChain.isPlainVanilla():  # PlainVanilla
                    option = BSM(price, strike, r, sigma, maturity.days)
                    optPrice = option.computePrice()
                else:  # American exercise
                    option = BinomialTree(price,
                                          strike,
                                          maturity.days,
                                          r,
                                          sigma,
                                          N=80,
                                          plainVanilla=False)
                    optPrice = option.computePrice()

                data.loc[data.strike == strike,
                         ['TheoPrice_call', 'TheoPrice_put']] = [
                             optPrice.call, optPrice.put
                         ]

            data['avgPrice_call'] = interpolateNaN(data.avgPrice_call)
            data['avgPrice_put'] = interpolateNaN(data.avgPrice_put)
            data[
                'spread_call'] = data['avgPrice_call'] - data['TheoPrice_call']
            data['spread_put'] = data['avgPrice_put'] - data['TheoPrice_put']
            data['spreadSummary'] = data['spread_call'] - data['spread_put']
        else:
            data['spreadSummary'] = data['avgPrice_call'] - data['avgPrice_put'] - \
                                    (self.optionChain.getSpotPrice() - data['strike'] *
                                     np.exp(-self.optionChain.getRiskFreeRate() * self.optionChain.getTimeToMaturity().years))

        if self.computeIV:
            # compute IVs and IV spread
            impliedVolatility = ImpliedVolatility(self.optionChain, True,
                                                  self.progressbar)
            IVs = impliedVolatility.getImpliedVolatility()
            data = data.merge(IVs.calls[['strike', 'IV', 'd2']],
                              on=['strike'],
                              how='left')
            data = data.merge(IVs.puts[['strike', 'IV', 'd2']],
                              on=['strike'],
                              how='left',
                              suffixes=['_call', '_put'])
            data['IV_spread'] = data['IV_call'] - data['IV_put']

            # compute volatility smile
            self.volatilitysmile = VolatilitySmile(impliedVolatility)
            smile = self.volatilitysmile.getVolatilitySmile()
            data = data.merge(
                smile[['strike', 'smile', 'naturalSmile', 'avgPrice']],
                on=['strike'],
                how='left')
        else:
            F = self.optionChain.getForwardPrice()
            data.loc[data.strike >= F, 'avgPrice'] = data['avgPrice_call']
            data.loc[data.strike < F, 'avgPrice'] = data['avgPrice_put']

        # compute no-arbitrage bounds
        div = 0
        data['S_U'] = data['ask_call'] + data['strike'] + div - data['bid_put']
        data['S_L'] = data['bid_call'] + data['strike'] * np.exp(
            -r * maturity.years) - data['ask_put']

        # compute Open Interest Ratio
        data['openInterestRatio'] = (
            (data['openInterest_call'] /
             (data['openInterest_put'] + data['openInterest_call'])).replace(
                 {
                     np.inf: 0,
                     np.nan: 0
                 }) - 0.5) * 2

        # compute price delta
        data['PutCallDelta'] = (data['avgPrice_call'] -
                                data['avgPrice_put']).abs()

        return data
"""
impliedVolatility.py

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

from EcoFin.options.blackScholesModel import BSM

marketPrice = 3
option = BSM(100, 100, 0.05, 0.2, 70)

start_time = time.time()  # [START]

print(option.getImpliedVolatility(marketPrice, 'call'))

print('chrono: ' + str(time.time() - start_time))  # [STOP]
([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.options.blackScholesModel import BSM

prices = {'call': [], 'put': []}
strikes = range(1, 200, 5)

for strike in strikes:
    option = BSM(100, strike, 0.05, 0.2, 365)
    price = option.price()
    prices['call'].append(price.call)
    prices['put'].append(price.put)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))
fig.suptitle('Sample option price')

ax1.set_title('Call')
ax1.plot(strikes, prices['call'], color='green', label='Call option')
ax1.set(xlabel='Strike')
ax1.set(ylabel='Price')
ax1.legend()

ax2.set_title('Put')
ax2.plot(strikes, prices['put'], color='red', label='Put option')
import matplotlib.pyplot as plt
import pandas as pd

from EcoFin.options.blackScholesModel import BSM

greeks = {'Delta': [], 'Gamma': [], 'Theta': [], 'Vega': [], 'Rho': []}

strikes = range(1, 200, 1)
data = pd.DataFrame(index=strikes, columns=greeks)
data = data.merge(data,
                  left_index=True,
                  right_index=True,
                  suffixes=['_call', '_put'])

for strike, row in data.iterrows():
    option = BSM(100, strike, 0.05, 0.2, 40)

    data.loc[strike, 'Delta_call'] = option.delta().call
    data.loc[strike, 'Gamma_call'] = option.gamma().call
    data.loc[strike, 'Theta_call'] = option.theta().call
    data.loc[strike, 'Vega_call'] = option.vega().call
    data.loc[strike, 'Rho_call'] = option.rho().call

    data.loc[strike, 'Delta_put'] = option.delta().put
    data.loc[strike, 'Gamma_put'] = option.gamma().put
    data.loc[strike, 'Theta_put'] = option.theta().put
    data.loc[strike, 'Vega_put'] = option.vega().put
    data.loc[strike, 'Rho_put'] = option.rho().put

# create plots with results
for greek in greeks.keys():
Beispiel #8
0
([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.options.blackScholesModel import BSM

prices = {'call': [], 'put': []}
strikes = range(1, 200, 5)

for strike in strikes:
    option = BSM(100, strike, 0.05, 0.2, 365)
    price = option.computePrice()
    prices['call'].append(price.call)
    prices['put'].append(price.put)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))
fig.suptitle('Sample option price')

ax1.set_title('Call')
ax1.plot(strikes, prices['call'], color='green', label='Call option')
ax1.set(xlabel='Strike')
ax1.set(ylabel='Price')
ax1.legend()

ax2.set_title('Put')
ax2.plot(strikes, prices['put'], color='red', label='Put option')