Skip to content

Commit

Permalink
Merge pull request #176 from thrasibule/fix_examples
Browse files Browse the repository at this point in the history
Fix examples
  • Loading branch information
dpinte authored Mar 2, 2017
2 parents ec420ef + bef1903 commit a502e16
Show file tree
Hide file tree
Showing 7 changed files with 49 additions and 65 deletions.
7 changes: 5 additions & 2 deletions examples/scripts/Download_USD_LIBOR.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@
# December 2011. The data is stored in a pandas DataFrame.

import os
import urllib
try:
import urllib.request as urllib
except ImportError:
import urllib
import numpy as np

from pandas.io.parsers import read_csv
Expand Down Expand Up @@ -105,4 +108,4 @@ def good_row(z):
df_libor = df_libor.rename(columns=columns_dic)
good_rows = df_libor.apply(good_row, axis=1)
df_libor_good = df_libor[good_rows]
df_libor_good.save(os.path.join('..', 'data', 'df_libor.pkl'))
df_libor_good.to_pickle(os.path.join('..', 'data', 'df_libor.pkl'))
2 changes: 1 addition & 1 deletion examples/scripts/Libor_to_ZC.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@

if __name__ == '__main__':

df_libor = pd.load(os.path.join('..', 'data', 'df_libor.pkl'))
df_libor = pd.read_pickle(os.path.join('..', 'data', 'df_libor.pkl'))

dtObs = df_libor.index

Expand Down
43 changes: 21 additions & 22 deletions examples/scripts/OptionQuotes.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,23 +204,21 @@ def impvol(cp, strike, premium):
except:
vol = np.nan
return vol/np.sqrt(timeToMaturity)

# implied bid/ask vol for all options

df_call['IVBid'] = [impvol('C', strike, price) for strike, price
in zip(df_call['Strike'], df_call['PBid'])]
df_call['IVAsk'] = [impvol('C', strike, price) for strike, price
in zip(df_call['Strike'], df_call['PAsk'])]

df_call['IVMid'] = (df_call['IVBid'] + df_call['IVAsk'])/2

df_put['IVBid'] = [impvol('P', strike, price) for strike, price
in zip(df_put['Strike'], df_put['PBid'])]
df_put['IVAsk'] = [impvol('P', strike, price) for strike, price
in zip(df_put['Strike'], df_put['PAsk'])]

df_put['IVMid'] = (df_put['IVBid'] + df_put['IVAsk'])/2


df_call = df_call.assign(IVBid = [impvol('C', strike, price) for strike, price
in zip(df_call['Strike'], df_call['PBid'])],
IVAsk = [impvol('C', strike, price) for strike, price
in zip(df_call['Strike'], df_call['PBid'])])
df_call = df_call.assign(IVMid = (df_call.IVBid + df_call.IVAsk)/2)

df_put = df_put.assign(IVBid = [impvol('P', strike, price) for strike, price
in zip(df_put['Strike'], df_put['PBid'])],
IVAsk = [impvol('P', strike, price) for strike, price
in zip(df_put['Strike'], df_put['PAsk'])])
df_put = df_put.assign(IVMid = (df_put['IVBid'] + df_put['IVAsk'])/2)

f_call = interp1d(df_call['Strike'].values, df_call['IVMid'].values)
f_put = interp1d(df_put['Strike'].values, df_put['IVMid'].values)

Expand All @@ -229,10 +227,12 @@ def impvol(cp, strike, premium):

# Quick Delta, computed with ATM vol
rv = norm()
df_call['QuickDelta'] = [rv.cdf(np.log(Fwd/strike)/(atmVol*np.sqrt(timeToMaturity))) \
for strike in df_call['Strike']]
df_put['QuickDelta'] = [rv.cdf(np.log(Fwd/strike)/(atmVol*np.sqrt(timeToMaturity))) \
for strike in df_put['Strike']]
df_call = (df_call.
assign(QuickDelta=
rv.cdf(np.log(Fwd/df_call.Strike.values) / (atmVol*np.sqrt(timeToMaturity)))))
df_put = (df_put.
assign(QuickDelta=
rv.cdf(np.log(Fwd/df_put.Strike.values)/(atmVol*np.sqrt(timeToMaturity)))))

# keep data within QD range

Expand Down Expand Up @@ -282,5 +282,4 @@ def impvol(cp, strike, premium):

# save a csv file and pickled data frame
df_final.to_csv('../data/df_options_SPX_24jan2011.csv', index=False)
df_final.save('../data/df_options_SPX_24jan2011.pkl')

df_final.to_pickle('../data/df_options_SPX_24jan2011.pkl')
2 changes: 1 addition & 1 deletion examples/scripts/SPX_Options.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,6 @@ def read_SPX_file(option_data_file):

# save a csv file and pickled data frame
df_SPX.to_csv('../data/df_SPX_24jan2011.csv', index=False)
df_SPX.save('../data/df_SPX_24jan2011.pkl')
df_SPX.to_pickle('../data/df_SPX_24jan2011.pkl')
print('File saved')

12 changes: 4 additions & 8 deletions examples/scripts/USD_Deposit_Swap.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,20 +40,16 @@
dt_obs = datetime.datetime(2011, 12, 20)

# extract a yield curve from data frame
libor_rates = pd.load(os.path.join('..', 'data', 'df_libor.pkl'))
df_libor = pd.DataFrame(libor_rates.xs(dt_obs), columns=['Rate'])

libor_rates = pd.read_pickle(os.path.join('..', 'data', 'df_libor.pkl'))
df_libor = pd.DataFrame({'Rate': libor_rates.loc[dt_obs]})
# add maturity column
df_libor['Maturity'] = [maturities_dic[k] for k in df_libor.index]

# add maturity column
df_libor['Maturity'] = [col_mat_dic[k] for k in df_libor.index]

# ... and sort by increasing maturity
df_libor = df_libor.sort_index(by='Maturity')
df_libor = df_libor.sort_values('Maturity')

print(df_libor)

pl.plot(df_libor['Maturity'], df_libor['Rate'])
pl.xlabel('Maturity (Yr)')
pl.ylabel('Deposit/Libor Rate')
Expand Down
40 changes: 13 additions & 27 deletions examples/scripts/make_zero_coupon.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from quantlib.time.api import (ModifiedFollowing, Actual360,
Thirty360, Semiannual, ActualActual)

from quantlib.time.api import ISDA
from quantlib.time.api import ISDA, pydate_from_qldate
from quantlib.currency.api import USDCurrency
from quantlib.quotes import SimpleQuote

Expand All @@ -35,19 +35,6 @@
import matplotlib.pyplot as plt
import pandas


def QLDateTodate(dt):
"""
Converts a QL Date to a datetime
"""

return datetime.datetime(dt.year, dt.month, dt.day)


def dateToDate(dt):
return Date(dt.day, dt.month, dt.year)


def get_term_structure(df_libor, dtObs):

settings = Settings()
Expand All @@ -56,7 +43,7 @@ def get_term_structure(df_libor, dtObs):
calendar = TARGET()

# must be a business day
eval_date = calendar.adjust(dateToDate(dtObs))
eval_date = calendar.adjust(Date.from_datetime(dtObs))
settings.evaluation_date = eval_date

settlement_days = 2
Expand Down Expand Up @@ -114,28 +101,27 @@ def get_term_structure(df_libor, dtObs):
ts_day_counter = ActualActual(ISDA)
tolerance = 1.0e-15

ts = PiecewiseYieldCurve(BootstrapTrait.Discount,
Interpolator.LogLinear,
settlement_date,
rate_helpers,
ts_day_counter,
tolerance)

ts = PiecewiseYieldCurve.from_reference_date(BootstrapTrait.Discount,
Interpolator.LogLinear,
settlement_date,
rate_helpers,
ts_day_counter,
tolerance)
ts.extrapolation = True
return ts


def zero_curve(ts, dtObs):
dtMax = ts.max_date

calendar = TARGET()
days = range(10, 365 * 20, 30)
dtMat = [min(dtMax, calendar.advance(dateToDate(dtObs), d, Days))
dtMat = [min(dtMax, calendar.advance(Date.from_datetime(dtObs), d, Days))
for d in days]
# largest dtMat < dtMax, yet QL run time error

df = np.array([ts.discount(dt, extrapolate=True) for dt in dtMat])
dtMat = [QLDateTodate(dt) for dt in dtMat]
dtToday = QLDateTodate(dtObs)
df = np.array([ts.discount(dt) for dt in dtMat])
dtMat = [pydate_from_qldate(dt) for dt in dtMat]
dtToday = dtObs.date()
dt = np.array([(d - dtToday).days / 365.0 for d in dtMat])
zc = -np.log(df) / dt
return (dtMat, zc)
Expand Down
8 changes: 4 additions & 4 deletions examples/scripts/stovol_calibration.py
Original file line number Diff line number Diff line change
Expand Up @@ -385,17 +385,17 @@ def batesdoubleexp_calibration(df_option, ival=None):

# Calibration
# -----------
#
#
# Finally, the calibration is performed by first loading the option data and calling the calibration routine.

# Plot Actual vs. Fitted Implied Volatility
# -----------------------------------------
#
#
# We display 4 graphs in one plot, and show the bid/ask market volatility with the fitted volatility
# for selected maturities.

def calibration_subplot(ax, group, i, model_name):
group = group.sort_index(by='Strike')
group = group.sort_values(by='Strike')
dtExpiry = group.get_value(group.index[0], 'dtExpiry')
K = group['Strike']
VB = group['IVBid']
Expand Down Expand Up @@ -440,7 +440,7 @@ def calibration_plot(df_calibration, model_name):
plt.show(block=False)

if __name__ == '__main__':
df_options = pandas.load('../data/df_options_SPX_24jan2011.pkl')
df_options = pandas.read_pickle('../data/df_options_SPX_24jan2011.pkl')

df_heston_cal = heston_calibration(df_options)
calibration_plot(df_heston_cal, 'Heston')
Expand Down

0 comments on commit a502e16

Please sign in to comment.