aboutsummaryrefslogtreecommitdiffstats
path: root/python/calibrate_tranches_BC.py
diff options
context:
space:
mode:
Diffstat (limited to 'python/calibrate_tranches_BC.py')
-rw-r--r--python/calibrate_tranches_BC.py184
1 files changed, 94 insertions, 90 deletions
diff --git a/python/calibrate_tranches_BC.py b/python/calibrate_tranches_BC.py
index 3da19a69..7ea71277 100644
--- a/python/calibrate_tranches_BC.py
+++ b/python/calibrate_tranches_BC.py
@@ -36,7 +36,7 @@ def build_sql_str(df, use_markit=False):
if __name__ == "__main__":
from serenitas.utils import SerenitasFileHandler
- from serenitas.utils.db import dbconn
+ from serenitas.utils.db2 import serenitas_pool
from serenitas.utils.env import CONFIG_DIR
logger = logging.getLogger("tranche_calib")
@@ -128,102 +128,106 @@ if __name__ == "__main__":
"eu36": datetime.date(2021, 9, 24),
}
- serenitas_conn = dbconn("serenitasdb")
- if args.config is None:
- if args.index is None:
- raise ValueError("Please provide an index to run")
- config = {"runs": [(args.index, args.tenor, args.skewtype)]}
- else:
- with (CONFIG_DIR / args.config).open("r") as fh:
- config = full_load(fh)
-
- for index, tenor, skewtype in config["runs"]:
- begin_date = None
- index, series = index[:2].upper(), int(index[2:])
- if args.start_from is not None:
- begin_date = args.start_from
- if args.update:
- begin_date = get_lastdate(serenitas_conn, index, series, tenor)
- if begin_date is None:
- continue
- if not args.update and begin_date is None:
- try:
- begin_date = start_dates[f"{index.lower()}{series}"]
- except KeyError:
- print(index, series)
- continue
+ with serenitas_pool.connection() as serenitas_conn:
+ if args.config is None:
+ if args.index is None:
+ raise ValueError("Please provide an index to run")
+ config = {"runs": [(args.index, args.tenor, args.skewtype)]}
+ else:
+ with (CONFIG_DIR / args.config).open("r") as fh:
+ config = full_load(fh)
- dr = pd.bdate_range(begin_date, args.until)
- if dr.empty:
- continue
- logger.info(f"calibrating {index}, {series}, {tenor}")
- tranche_index = None
+ for index, tenor, skewtype in config["runs"]:
+ begin_date = None
+ index, series = index[:2].upper(), int(index[2:])
+ if args.start_from is not None:
+ begin_date = args.start_from
+ if args.update:
+ begin_date = get_lastdate(serenitas_conn, index, series, tenor)
+ if begin_date is None:
+ continue
+ if not args.update and begin_date is None:
+ try:
+ begin_date = start_dates[f"{index.lower()}{series}"]
+ except KeyError:
+ print(index, series)
+ continue
- data = {}
- for d in dr.date:
- logger.debug(f"calibrating for {d}")
- try:
- if tranche_index is None:
- tranche_index = TrancheBasket(index, series, tenor, value_date=d)
- else:
- tranche_index.value_date = d
- except (RuntimeError, ValueError) as e:
- logger.error(e)
+ dr = pd.bdate_range(begin_date, args.until)
+ if dr.empty:
continue
+ logger.info(f"calibrating {index}, {series}, {tenor}")
+ tranche_index = None
- try:
- tranche_index.tweak()
- except ValueError as e:
- logger.error(e)
- break
- try:
- tranche_index.build_skew(skewtype)
- except ValueError as e:
- logger.error(e)
- logger.debug("Trying topdown")
- tranche_index.rho[:] = np.nan
+ data = {}
+ for d in dr.date:
+ logger.debug(f"calibrating for {d}")
try:
- tranche_index.build_skew("topdown")
- except ValueError:
+ if tranche_index is None:
+ tranche_index = TrancheBasket(
+ index, series, tenor, value_date=d
+ )
+ else:
+ tranche_index.value_date = d
+ except (RuntimeError, ValueError) as e:
logger.error(e)
continue
- df = pd.concat(
- [
- tranche_index.tranche_deltas(),
- tranche_index.tranche_fwd_deltas(),
- tranche_index.tranche_durations(),
- tranche_index.tranche_EL(),
- tranche_index.tranche_spreads(),
- ],
- axis=1,
- )
- try:
- df["theta"] = tranche_index.tranche_thetas(method="TLP")
- except ValueError:
- df["theta"] = None
+ try:
+ tranche_index.tweak()
+ except ValueError as e:
+ logger.error(e)
+ break
+ try:
+ tranche_index.build_skew(skewtype)
+ except ValueError as e:
+ logger.error(e)
+ logger.debug("Trying topdown")
+ tranche_index.rho[:] = np.nan
+ try:
+ tranche_index.build_skew("topdown")
+ except ValueError:
+ logger.error(e)
+ continue
+
+ df = pd.concat(
+ [
+ tranche_index.tranche_deltas(),
+ tranche_index.tranche_fwd_deltas(),
+ tranche_index.tranche_durations(),
+ tranche_index.tranche_EL(),
+ tranche_index.tranche_spreads(),
+ ],
+ axis=1,
+ )
+ try:
+ df["theta"] = tranche_index.tranche_thetas(method="TLP")
+ except ValueError:
+ df["theta"] = None
- (
- df["index_duration"],
- df["index_expected_loss"],
- df["index_price"],
- ) = tranche_index.index_pv(clean=True)
- df["index_expected_loss"] *= -1
- df["index_basis"] = tranche_index.tweaks[0]
- df["index_theta"] = tranche_index.theta()[tenor]
- df["tranche_id"] = tranche_index.tranche_quotes.id.values
- df["corr_at_detach"] = tranche_index.rho[1:]
- df["corr01"] = tranche_index.tranche_corr01()
- del df["fwd_gamma"]
- df["quote_price"] = (
- 1 - tranche_index.tranche_quotes.quotes.values - tranche_index._accrued
- )
- df["calibrated_price"] = tranche_index.tranche_pvs().bond_price
- data[d] = df
+ (
+ df["index_duration"],
+ df["index_expected_loss"],
+ df["index_price"],
+ ) = tranche_index.index_pv(clean=True)
+ df["index_expected_loss"] *= -1
+ df["index_basis"] = tranche_index.tweaks[0]
+ df["index_theta"] = tranche_index.theta()[tenor]
+ df["tranche_id"] = tranche_index.tranche_quotes.id.values
+ df["corr_at_detach"] = tranche_index.rho[1:]
+ df["corr01"] = tranche_index.tranche_corr01()
+ del df["fwd_gamma"]
+ df["quote_price"] = (
+ 1
+ - tranche_index.tranche_quotes.quotes.values
+ - tranche_index._accrued
+ )
+ df["calibrated_price"] = tranche_index.tranche_pvs().bond_price
+ data[d] = df
- if data:
- data = pd.concat(data)
- sql_str = build_sql_str(data, args.markit)
- with serenitas_conn.cursor() as c:
- c.executemany(sql_str, data.to_dict(orient="records"))
- serenitas_conn.commit()
+ if data:
+ data = pd.concat(data)
+ sql_str = build_sql_str(data, args.markit)
+ with serenitas_conn.cursor() as c:
+ c.executemany(sql_str, data.to_dict(orient="records"))
+ serenitas_conn.commit()