diff options
Diffstat (limited to 'python')
| -rw-r--r-- | python/TAGS | 4044 |
1 files changed, 1824 insertions, 2220 deletions
diff --git a/python/TAGS b/python/TAGS index 75a85491..f6cadc16 100644 --- a/python/TAGS +++ b/python/TAGS @@ -1,1060 +1,1159 @@ -daemon.py,296 -class Daemon:Daemon5,93 - def __init__(self, pidfile): self.pidfile = pidfile__init__10,205 - def daemonize(self):daemonize12,259 - def delpid(self):delpid58,1240 - def start(self):start61,1286 - def stop(self):stop82,1711 - def restart(self):restart112,2386 - def run(self):run117,2464 +exploration/tranches.py,281 +import analytics.tranche_functions as tchtch4,74 +import analytics.tranche_basket as bktbkt5,116 +import analytics.basket_index as idx_bktidx_bkt6,155 +import numpy as npnp7,196 +import pandas as pdpd8,215 +def rv_calc1():rv_calc118,593 +def dispersion():dispersion70,2851 -globeop_reports.py,854 -def get_monthly_pnl(group_by = ['identifier']):get_monthly_pnl15,288 -def get_portfolio(report_date = None):get_portfolio24,871 -def curr_port_PNL(date = datetime.date.today(), asset_class='Subprime'):curr_port_PNL36,1488 -def trade_performance():trade_performance44,1934 -def get_net_navs():get_net_navs82,3689 -def alloc(alloc = 'pnl'):alloc95,4348 -def pnl_alloc_plot(df):pnl_alloc_plot123,5588 -def cap_alloc_plot_pie(df):cap_alloc_plot_pie144,6143 -def avg_turnover():avg_turnover157,6581 -def num_bond_by_strat():num_bond_by_strat168,7187 -def num_bond_trades():num_bond_trades175,7518 -def shift_cash(date, amount, df, strat):shift_cash183,7915 -def cap_alloc_plot_bar(df):cap_alloc_plot_bar189,8157 -def calc_trade_performance_stats():calc_trade_performance_stats207,8726 -def get_rmbs_pos_df(date = None):get_rmbs_pos_df230,9649 +exploration/test_mlp.py,57 +import pandas as pdpd1,0 +def get_conn():get_conn6,97 -GHquad.h,0 +exploration/hy_flattener.py,46 +from matplotlib import pyplot as pltplt3,56 -bbg_index_quotes.py,835 -securities = {}securities5,103 -sql_str = (f"INSERT INTO bbg_index_quotes VALUES({','.join(['%s'] * 8)}) "sql_str17,558 -start_date = datetime.date.today() - datetime.timedelta(days=7) ## one weeek of overlapstart_date19,670 -conn = dbconn('serenitasdb')conn20,758 - d = retrieve_data(session, securities.keys(), fields=["TICKER", "VERSION"])d22,829 - ticker_mapping = {v['TICKER']: securities[k] + (v['VERSION'],)ticker_mapping23,909 - securities = [f"{e['TICKER']} {pcs} Curncy" for e in d.values()]securities26,1062 - d2 = retrieve_data(session, securities, fields=["PX_LAST"],d227,1135 - start_date=start_date)start_date28,1203 - ticker = k.split()[0]ticker31,1322 - index = "EU"index34,1466 - index = "XO"index36,1536 +exploration/beta_trade.py,525 +import pandas as pdpd5,55 +import numpy as npnp13,253 +import matplotlib.pyplot as pltplt17,356 +def calc_returns(index_list=['HY', 'IG'], save_feather=False):calc_returns19,389 +def calc_betas(returns=None, spans=[5, 20], index_list=['HY', 'IG']):calc_betas30,916 +def plot_betas(betas=None):plot_betas40,1312 +def calc_realized_vol(returns=None):calc_realized_vol50,1576 +def spreads_ratio(series=list(range(22, 29)), index=['IG', 'HY'], tenor='5yr'):spreads_ratio73,2461 +def loglik(beta, returns):loglik79,2726 -test_igoption.py,409 -index = Index.from_name("ig", 27, "5yr",index3,54 - trade_date = datetime.date(2016, 11, 18))trade_date4,95 -exercise_date = datetime.date(2017, 3, 15)exercise_date6,181 -strike = 80strike7,224 -payer = Swaption(index, exercise_date, strike, strike_is_price = False)payer8,236 -receiver = Swaption(index, exercise_date, strike, "receiver", strike_is_price = False)receiver13,377 +exploration/marketing.py,417 +import numpy as npnp2,66 +import pandas as pdpd3,85 +import matplotlib as pltplt4,105 +def run_scenario(pool_size, rho, successprob, issuerweights, amount):run_scenario8,147 +def plot_scenarios(df, bins = [0,0.1, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 2000]):plot_scenarios17,553 +def stats(df):stats37,1333 +def plot_prob_over(df):plot_prob_over44,1565 +def add_to_plot(df, ax):add_to_plot51,1763 -markit_red.py,277 -def request_payload(payload):request_payload8,143 -def download_report(report):download_report22,626 -def update_redcodes(conn, fname):update_redcodes37,1132 -def update_redindices(fname):update_redindices59,2265 - fname = download_report("REDIndexCodes")fname80,3379 +exploration/backtest.py,185 +import pandas as pdpd2,24 +import numpy as npnp3,44 +def calc_mark_diff():calc_mark_diff5,64 + def closest(s):closest12,385 + def avg_minus_maxmin(s):avg_minus_maxmin20,592 -parse_gs_exchange.py,577 -class ParseError(Exception):ParseError10,176 -def parse_email(email, fwd_index):parse_email13,215 -def clean_df(all_df):clean_df85,3114 - fwd_index = []fwd_index104,3913 - swaption_quotes = {}swaption_quotes105,3932 - index_df = pd.DataFrame(fwd_index)index_df113,4211 - index_df = index_df.drop_duplicates(['quotedate', 'index', 'series', 'expiry'])index_df114,4250 - swaption_quotes = clean_df(swaption_quotes)swaption_quotes116,4370 - swaption_quotes = swaption_quotes.set_index(['quotedate', 'index', 'series', 'expiry'])swaption_quotes117,4418 +exploration/VaR.py,107 +import pandas as pdpd5,136 +def hist_var(portf, index_type="IG", quantile=0.05, years=5):hist_var13,253 -yieldcurve.py,1499 -def load_curves(currency="USD", date=None):load_curves25,929 -def get_curve(effective_date, currency="USD"):get_curve44,1694 -def getMarkitIRData(effective_date=datetime.date.today(),getMarkitIRData66,2554 -def get_futures_data(date=datetime.date.today()):get_futures_data82,3306 -def rate_helpers(currency="USD", MarkitData=None, evaluation_date=None):rate_helpers89,3615 -def get_dates(date, currency="USD"):get_dates133,5679 -def roll_yc(yc, forward_date):roll_yc149,6473 -def YC(helpers=None, currency="USD", MarkitData=None, evaluation_date=None):YC155,6783 -def jpYC(effective_date, currency="USD", MarkitData=None):jpYC165,7261 -def ql_to_jp(ql_yc):ql_to_jp184,8049 -def build_curves(currency="USD"):build_curves194,8502 - helpers = rate_helpers("USD")helpers235,10603 - ts = YC(helpers)ts236,10637 - cal = calendar_from_name('USA')cal237,10658 - p1 = Period('1M')p1238,10694 - p2 = Period('2M')p2239,10716 - p3 = Period('3M')p3240,10738 - p6 = Period('6M')p6241,10760 - p12 = Period('12M')p12242,10782 - sched = Schedule.from_rule(ts.reference_date, ts.reference_date + Period('5Y'), Period('3M'), cal)sched243,10806 - days = [pydate_from_qldate(d) for d in sched]days244,10909 - f3 = [ts.forward_rate(d, d + p3, Actual360(), 0).rate for d in sched]f3245,10959 - f6 = [ts.forward_rate(d, d + p6, Actual360(), 0).rate for d in sched]f6246,11033 - f2 = [ts.forward_rate(d, d + p2, Actual360(), 0).rate for d in sched]f2247,11107 +exploration/test_scenarios.py,54 +import numpy as npnp1,0 +import pandas as pdpd2,19 -bbg_cds_quotes.py,935 -logger = logging.getLogger('bbg_quotes')logger9,209 -fh = logging.FileHandler(filename=os.path.join(os.environ['LOG_DIR'], 'bbg_quotes.log'))fh10,250 -formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')formatter11,339 -workdate = datetime.date.today()workdate16,505 -serenitasdb = dbconn('serenitasdb')serenitasdb17,538 -index_list = get_index_list(serenitasdb, workdate)index_list18,574 -basket_ids = get_basketids(serenitasdb, index_list, workdate)basket_ids19,625 -bbg_tickers = set(get_bbg_tickers(serenitasdb, basket_ids, workdate))bbg_tickers20,687 -securities = [f'{ticker} Curncy' for ticker in bbg_tickers]securities22,788 -fields = ['UPFRONT_RUNNING_SPREAD', 'UPFRONT_BID', 'UPFRONT_ASK', 'CDS_RECOVERY_RT']fields23,848 -r = {}r25,934 -sql_str = f"INSERT INTO cds_quotes VALUES({','.join(['%s'] * 8)})"sql_str31,1184 -def build_tuple(k, v, workdate, source):build_tuple33,1252 +exploration/test_swaption.py,77 +def theta(swaption):theta27,1117 +def dv01(swaption, helpers):dv0135,1306 -db.py,499 -class InfDateAdapter:InfDateAdapter11,278 - def __init__(self, wrapped):__init__12,300 - def getquoted(self):getquoted14,364 -def nan_to_null(f, _NULL=AsIs('NULL'),nan_to_null22,653 -def dbconn(dbname):dbconn32,945 -def dbengine(dbname):dbengine43,1308 -def with_connection(dbname):with_connection55,1803 - def decorator(f):decorator56,1832 - def with_connection_(*args, **kwargs):with_connection_58,1884 -def query_db(conn, sqlstr, params=None, one=True):query_db70,2238 +exploration/option_trades.py,1020 +import numpy as npnp4,41 +import pandas as pdpd5,60 +def realized_vol(index, series, tenor='5yr', date=None, years=None, return_type='spread'):realized_vol16,349 +def lr_var(res):lr_var29,1048 +def atm_vol_calc(df, index_type, moneyness):atm_vol_calc42,1443 +def atm_vol(index, date, series=None, moneyness=0.2):atm_vol75,3123 +def rolling_vol(df, col='atm_vol', term=[3]):rolling_vol91,3914 + def aux(s, col, term):aux95,4128 +def vol_var(percentile=0.975, index='IG', start_date=datetime.date(2014, 6, 11)):vol_var106,4606 +def get_index_spread(index, series, date, conn):get_index_spread119,5093 +def get_index_ref(index, series, date, expiry, conn):get_index_ref131,5487 +def get_option_pnl(strike, expiry, index, series, start_date, engine):get_option_pnl144,5988 +def sell_vol_strategy(index="IG", months=3):sell_vol_strategy179,7669 +def aggregate_trades(d):aggregate_trades205,8976 +def compute_allocation(df):compute_allocation211,9119 + import statsmodels.formula.api as smfsmf244,10361 -backpopulate.py,449 -p = Path('/home/serenitas/CorpCDOs/Tranche_data/CDS')p4,58 -quotefiles = (f for f in p.iterdir() if f.is_file())quotefiles5,112 -tenors = ['6m', '1y', '2y', '3y', '4y', '5y', '7y', '10y']tenors6,165 -conn = dbconn('serenitasdb')conn7,224 -sql_str = "INSERT INTO cds_quotes VALUES({})".format(",".join(["%s"] * 8))sql_str8,253 -tickers = ['CT659914', 'CT391460', 'CT391464', 'CT391468', 'CT391472',tickers10,329 -def convert(s):convert13,448 +exploration/portfolio_example.py,57 +import pandas as pdpd4,176 +import numpy as npnp5,196 -mark_backtest.py,152 -def calc_mark_diff(asset_class = 'Subprime'):calc_mark_diff4,45 - def closest(x):closest30,1357 - def remove_max_min(x):remove_max_min51,2174 +exploration/vcube.py,260 +import pandas as pdpd6,149 +def ticker(expiry, tenor, spread, vol_type, source):ticker12,287 +def get_tickers(vol_type="V", source="GFIS"):get_tickers24,719 +def to_tenor(s):to_tenor32,985 +def get_vol_cube(conn, date, source='GFIS'):get_vol_cube36,1075 -tests/test_scenarios.py,514 -class TestSenarios(unittest.TestCase):TestSenarios10,293 - option_delta = Index.from_tradeid(874)option_delta11,332 - option1 = BlackSwaption.from_tradeid(7, option_delta)option112,375 - option2 = BlackSwaption.from_tradeid(8, option_delta)option213,433 - portf = Portfolio([option1, option2, option_delta])portf14,491 - date_range = pd.bdate_range(option_delta.trade_date, pd.Timestamp('2017-05-17') - BDay(), freq = '5B')date_range15,547 - def test_portfolio(self):test_portfolio17,655 +exploration/.ropeproject/config.py,90 +def set_prefs(prefs):set_prefs5,45 +def project_opened(project):project_opened120,4706 -tests/test_swaption.py,1230 -class TestPutCallParity(unittest.TestCase):TestPutCallParity9,150 - index = Index.from_name("ig", 27, "5yr",index10,194 - trade_date = datetime.date(2016, 10, 25))trade_date11,239 - exercise_date = datetime.date(2017, 3, 15)exercise_date13,331 - strike = 82.5strike14,378 - def test_parity(self):test_parity16,397 - def test_parity_black(self):test_parity_black26,927 - def test_calibration(self):test_calibration36,1473 - def test_hy(self):test_hy44,1748 -class TestBreakeven(unittest.TestCase):TestBreakeven54,2141 - exercise_date = datetime.date(2017, 3, 15)exercise_date56,2182 - hyindex = Index.from_name("hy", 27, "5yr",hyindex57,2229 - trade_date=datetime.date(2016, 11, 16))trade_date58,2276 - hystrike = 102.5hystrike60,2373 - igindex = Index.from_name("ig", 27, "5yr",igindex62,2395 - trade_date=datetime.date(2016, 11, 18))trade_date63,2442 - igstrike = 80igstrike65,2538 - def test_hypayer(self):test_hypayer67,2557 - def test_hyreceiver(self):test_hyreceiver73,2790 - def test_igpayer(self):test_igpayer80,3078 - def test_igreceiver(self):test_igreceiver86,3303 +exploration/realized_vol_quantiles.py,39 +def implied_vol(q):implied_vol13,476 -tests/test_yieldcurve.py,207 -class TestYieldCurve(unittest.TestCase):TestYieldCurve10,233 - def assertListAlmostEqual(self, list1, list2, places = 7):assertListAlmostEqual12,275 - def test_bloomberg(self):test_bloomberg17,476 +exploration/portfolio_var.py,469 +import numpy as npnp7,223 +import pandas as pdpd8,242 +import exploration.curve_trades as cvcv12,291 +def on_the_run(index):on_the_run17,397 +def rel_spread_diff(report_date = datetime.date.today(), index='HY', rolling=10):rel_spread_diff23,600 +def get_pos(report_date):get_pos38,1249 +def cleared_cds_margins(report_date=datetime.date.today()):cleared_cds_margins49,1712 +def index_curve_margins(report_date=datetime.date.today()):index_curve_margins71,2856 -tests/test_cds.py,345 -class TestUpfront(unittest.TestCase):TestUpfront12,246 - index = Index.from_name("ig", 26, "5yr",index13,284 - trade_date = datetime.date(2016, 9, 21))trade_date14,329 - def test_upfront(self):test_upfront18,447 - def test_cdsone(self):test_cdsone21,537 - def test_annuity(self):test_annuity43,1672 +exploration/sell_vol.py,41 +def get_trades(df, d):get_trades10,338 -tests/test_swap_index.py,107 -class UsdLiborSwap(unittest.TestCase):UsdLiborSwap8,176 - def test_creation(self):test_creation9,215 +exploration/test_cms.py,208 +import pandas as pdpd8,214 +def lmcg_navs(trade_id):lmcg_navs13,288 +def gs_navs(trade_id, orig_nav):gs_navs25,607 +def ms_navs(trade_id="JWY3N"):ms_navs54,1599 + def myfun(corr, args):myfun100,3216 -tests/test_dates.py,668 -class TestStartDate(unittest.TestCase):TestStartDate10,166 - def test_previous_twentieth(self):test_previous_twentieth12,207 - def test_previous_twentieth_timestamp(self):test_previous_twentieth_timestamp22,755 -class TestEndDate(unittest.TestCase):TestEndDate32,1309 - def test_enddate(self):test_enddate33,1347 - def test_enddate_pre2015(self):test_enddate_pre201543,1860 -class TestEndDateC(unittest.TestCase):TestEndDateC57,2624 - roll_date_c = lambda d, t: TDate_to_pydate(end_dates(pydate_to_TDate(d), t))roll_date_c58,2663 - def test_enddate(self):test_enddate60,2745 - def test_enddate_pre2015(self):test_enddate_pre201570,3266 +test_dispersion.py,0 -tests/.ropeproject/config.py,90 -def set_prefs(prefs):set_prefs5,45 -def project_opened(project):project_opened110,4652 +cds_rebook.py,208 +def get_outstanding_positions(trade_date, fcm):get_outstanding_positions9,231 +def default_adjustment(company_id, end_date):default_adjustment22,669 +def rebook(trade_date, company_id, fcm):rebook44,1249 -tests/test_index.py,1159 -class TestPickle(unittest.TestCase):TestPickle12,219 - index = Index.from_name("ig", 26, "5yr",index13,256 - trade_date=datetime.date(2016, 7, 1))trade_date14,301 - def test_pickle(self):test_pickle18,416 -class TestStrike(unittest.TestCase):TestStrike22,548 - index = Index.from_name("ig", 26, "5yr",index23,585 - trade_date = datetime.date(2016, 7, 1))trade_date24,630 - exercise_date = datetime.date(2016, 8, 19)exercise_date27,746 - def test_pv(self):test_pv29,794 - def test_strike(self):test_strike34,1011 - def test_strike_vec(self):test_strike_vec43,1456 - def test_price_setting(self):test_price_setting54,1997 -class TestForwardIndex(unittest.TestCase):TestForwardIndex58,2130 - index = Index.from_name("ig", 26, "5yr",index59,2173 - trade_date = datetime.date(2016, 7, 1))trade_date60,2218 - exercise_date = datetime.date(2016, 8, 19)exercise_date63,2334 - fi = ForwardIndex(index, exercise_date)fi64,2381 - def test_forward_pv(self):test_forward_pv66,2426 - def test_forward_pv(self):test_forward_pv72,2726 +xmltotab.py,0 -tests/test_upfront_cds.py,2424 -def snac_pv(spread, term_date, fixed_coupon=0.01, recovery=0.4, ts=YC()):snac_pv23,1037 -def jpmorgan_curves(trade_date, value_date, start_date, end_date, spread, recovery=0.4):jpmorgan_curves45,2479 - settings = Settings()settings54,2880 - yield_helpers = rate_helpers()yield_helpers56,2955 - ts = YC(helpers = yield_helpers)ts57,2990 - tenor = Period(5, Years)tenor58,3027 - trade_date = datetime.date(2009, 5, 21)trade_date59,3056 - stepin_date = trade_date + datetime.timedelta(days=1)stepin_date60,3100 - value_date = datetime.date(2009, 5, 26)value_date61,3158 - term_date = datetime.date(2019, 6, 20)term_date62,3202 - start_date = datetime.date(2009, 3, 20)start_date63,3245 - spread = 0.001spread64,3289 - sc_data = sc.inspect()['data']sc_data66,3408 - hazard_rate = math.log(1 + sc_data[0][1])hazard_rate67,3443 - contingent_leg = ContingentLeg(start_date, term_date, 10000000)contingent_leg68,3489 - fee_leg = FeeLeg(start_date, term_date, True, 10000000, 0.01)fee_leg69,3557 - flat_curve = FlatHazardRate(0, WeekendsOnly(), hazard_rate, Actual365Fixed())flat_curve71,3624 - cds_schedule = Schedule(Date.from_datetime(trade_date), Date.from_datetime(term_date),cds_schedule72,3706 - cds_trade = CreditDefaultSwap.from_upfront(BUYER, 10000000, 0., 0.01, cds_schedule, Following, Actual360(),cds_trade75,3919 - protection_start = Date.from_datetime(trade_date) + 1,protection_start76,4031 - last_period_day_counter = Actual360(True))last_period_day_counter77,4133 - isda_pricer = IsdaCdsEngine(flat_curve, 0.4, ts, accrual_bias=AccrualBias.HalfDayBias,isda_pricer78,4223 - forwards_in_coupon_period = ForwardsInCouponPeriod.Piecewise)forwards_in_coupon_period79,4314 - cds_trade2 = CreditDefaultSwap(BUYER, 10000000, spread, cds_schedule, Following, Actual360(),cds_trade283,4472 - protection_start = Date.from_datetime(trade_date) + 1,protection_start84,4570 - last_period_day_counter = Actual360(True))last_period_day_counter85,4660 - h = 0.00168276528775h87,4786 - flat_curve2 = FlatHazardRate(0, WeekendsOnly(), h, Actual365Fixed())flat_curve288,4811 - isda_pricer2 = IsdaCdsEngine(flat_curve2, 0.4, ts)isda_pricer289,4884 +Makefile,201 +CFLAGS=-O2 -march=native -fpicCFLAGS1,0 +LDLIBS=-lm -llapackLDLIBS2,31 +LDFLAGS=-fpic -sharedLDFLAGS3,51 +tests:tests5,74 +tags:tags9,127 +GHquad.so: GHquad.oGHquad.so12,185 +clean:clean15,243 -tests/test_sabr_quantlib.py,720 -strikes = np.array([50, 55, 57.5, 60, 62.5, 65, 67.5, 70, 75, 80, 85])strikes7,257 -pvs = np.array([53.65, 37.75, 31.55, 26.45, 22.25, 18.85, 16.15, 13.95, 10.55,pvs8,328 -option_date = Settings().instance().evaluation_date + Period(3, Months)option_date10,461 -forward = SimpleQuote(58.71e-4)forward11,533 -strikes = np.array([50, 55, 57.5, 60, 62.5, 65, 67.5, 70, 75, 80, 85, 90, 95, 100]) * 1e-4strikes12,565 -vol = np.array([28.5, 31.6, 33.7, 36.1, 38.7, 41.5, 44.1,vol13,656 -vol_quotes = [SimpleQuote(q) for q in vol]vol_quotes15,780 -section = SabrInterpolatedSmileSection(option_date, forward, strikes, False,section17,824 - is_beta_fixed=True)is_beta_fixed19,988 +quote_parsing/.pytest_cache/README.md,54 +# pytest cache directory #pytest cache directory1,0 -database_consistency.py,248 - engine = create_engine('postgresql://et_user@debian/ET')engine6,99 - data12 = pd.merge(data1, data2, left_index=True, right_index=True)data1221,1249 - data13 = pd.merge(data1bis, data3, left_index=True, right_index=True)data1322,1320 +quote_parsing/parse_emails.py,1696 +import pandas as pdpd1,0 +import psycopg2.sql as sqlsql3,30 +def list_imm_dates(date):list_imm_dates13,280 +def makedf(r, indextype, quote_source):makedf22,461 +def parse_quotedate(fh, date_received):parse_quotedate81,2260 +def parse_refline(line):parse_refline107,3198 +def parse_baml(fh, index_desc, *args):parse_baml122,3646 +def parse_baml_block(fh, indextype):parse_baml_block143,4201 +def parse_bnp_block(fh, indextype, skip_header=True):parse_bnp_block160,4667 +def parse_cs_block(fh, indextype):parse_cs_block181,5278 +def parse_ms_block(fh, indextype):parse_ms_block203,6011 +def parse_nomura_block(fh, indextype):parse_nomura_block246,7540 +def parse_sg_block(fh, indextype, expiration_dates):parse_sg_block278,8446 +def parse_gs_block(fh, indextype):parse_gs_block317,9653 +def parse_citi_block(fh, indextype):parse_citi_block354,10679 +def parse_ms(fh, index_desc, *args):parse_ms407,12221 +def parse_nom(fh, index_desc, *args):parse_nom424,12821 + def aux(line, fh, index_desc, option_stack, fwd_index):aux428,12901 +def parse_sg(fh, index_desc):parse_sg447,13620 +def parse_gs(fh, index_desc):parse_gs461,14056 +def parse_citi(fh, index_desc):parse_citi497,15184 +def parse_cs(fh, index_desc):parse_cs515,15849 +def parse_bnp(fh, index_desc):parse_bnp538,16766 +def get_current_version(index, series, d, conn):get_current_version582,18653 +def parse_email(email, date_received, conn):parse_email593,18970 +def write_todb(swaption_stack, index_data, conn):write_todb653,21579 + def gen_sql_str(query, table_name, columns):gen_sql_str654,21629 +def get_email_list(date):get_email_list694,23152 +def pickle_drop_date(date):pickle_drop_date709,23565 -trace_update.py,493 -def get_universe():get_universe7,182 -def get_bbg_data(cusips, universe):get_bbg_data12,347 -def insert_data(dfs, conn):insert_data22,835 -def get_cusips():get_cusips37,1428 -_alphabet = '0123456789ABCDEFGH JKLMN PQRSTUVWXYZ*@#'_alphabet42,1569 -def calc_check_digit(number):calc_check_digit44,1624 - universe = get_universe()universe52,1951 - cusips = get_cusips()cusips53,1981 - dfs = get_bbg_data(cusips, universe)dfs54,2007 - conn = dbconn('serenitasdb')conn55,2048 +quote_parsing/__main__.py,28 +import pandas as pdpd3,31 -pyisda/tests/test_pickle.py,327 -class TestPickle(unittest.TestCase):TestPickle9,201 - trade_date = datetime.date(2016, 10, 6)trade_date10,238 - yc = build_yc(trade_date, ql_curve = True)yc11,282 - def assertListAlmostEqual(self, l1, l2):assertListAlmostEqual13,330 - def test_yc(self):test_yc19,514 - def test_legs(self):test_legs25,794 +quote_parsing/tests/test_cs.py,38 +def test_subject():test_subject4,40 -pyisda/pyisda/credit_index.pxd,92 -cdef class CurveList:CurveList8,210 -cdef class CreditIndex(CurveList):CreditIndex16,449 +quote_parsing/tests/__init__.py,0 -pyisda/pyisda/logging.pxd,0 +quote_parsing/download_emails.py,100 +def print_citi_html(email):print_citi_html16,307 +def save_emails(update=True):save_emails35,869 -pyisda/pyisda/date.pxd,364 -cdef long dcc(str day_count) except -1dcc7,206 -cpdef TDate pydate_to_TDate(c_datetime.date d)pydate_to_TDate50,1790 -cpdef c_datetime.date TDate_to_pydate(TDate d)TDate_to_pydate52,1838 -cdef void _roll_date(TDate d, double* tenors, int n_dates, TDate* output) nogil_roll_date54,1886 -cdef TDate _previous_twentieth(TDate d) nogil_previous_twentieth55,1966 +quote_parsing/__init__.py,0 -pyisda/pyisda/__init__.py,0 +.pytest_cache/README.md,54 +# pytest cache directory #pytest cache directory1,0 -pyisda/pyisda/cdsone.pxd,0 +database_consistency.py,27 +import pandas as pdpd1,0 -pyisda/pyisda/logging.pyx,244 -def enable_logging():enable_logging3,53 -def disable_logging():disable_logging11,239 -def set_logging_file(str file_name, TBoolean append = True):set_logging_file15,312 -def log_message(str msg):log_message22,554 -def flush():flush27,679 +rmbs/CRT_data.py,189 +import pandas as pdpd3,33 +import .load_globeop_report as load_globeopload_globeop6,93 +def get_CRT_notional():get_CRT_notional10,159 +def calc_CRT_notional():calc_CRT_notional36,1221 -pyisda/pyisda/date.pyx,593 -cpdef TDate pydate_to_TDate(c_datetime.date d):pydate_to_TDate13,250 -cpdef c_datetime.date TDate_to_pydate(TDate d):TDate_to_pydate16,363 -cdef long dcc(str day_count) except -1:dcc23,600 -def dcc_tostring(long day_count):dcc_tostring33,904 -cdef TDate _previous_twentieth(TDate d) nogil:_previous_twentieth41,1112 -def previous_twentieth(d):previous_twentieth64,1671 -cdef TMonthDayYear next_twentieth(TDate d) nogil:next_twentieth68,1794 -cdef void _roll_date(TDate d, double* tenors, int n_dates, TDate* output) nogil:_roll_date86,2235 -def roll_date(d, tenor):roll_date122,3355 +rmbs/marketing.py,183 +import pandas as pdpd1,0 +def ver_one():ver_one6,87 +def plot_strat():plot_strat29,1253 + import seaborn as snssns31,1272 +def wavg(group, avg_name, weight_name):wavg54,2014 -pyisda/pyisda/cdsone.pyx,198 -def upfront_charge(date, value_date, benchmark_start_date, stepin_date,upfront_charge6,116 -def spread_from_upfront(date, value_date, benchmark_start_date, stepin_date,spread_from_upfront69,2787 +compute_price.py,0 -pyisda/pyisda/legs.pyx,837 -cdef class ContingentLeg:ContingentLeg7,218 - def __cinit__(self, start_date, end_date, double notional,__cinit__20,529 - def __dealloc__(self):__dealloc__30,986 - def __reduce__(self):__reduce__34,1084 - def __hash__(self):__hash__41,1456 - def pv(self, today, step_in_date, value_date, YieldCurve yc, SpreadCurve sc,pv47,1695 -cdef class FeeLeg:FeeLeg75,2818 - def __cinit__(self, start_date, end_date, bint pay_accrued_on_default,__cinit__95,3406 - def __reduce__(self):__reduce__118,4480 - def __hash__(self):__hash__127,5001 - def inspect(self):inspect136,5388 - def cashflows(self):cashflows151,6036 - def pv(self, today, step_in_date, value_date, YieldCurve yc, SpreadCurve sc,pv161,6366 - def accrued(self, today):accrued189,7477 - def __dealloc__(self):__dealloc__204,7783 +mark_backtest_underpar.py,978 +import pandas as pdpd1,0 +import numpy as npnp3,38 +import matplotlib.pyplot as pltplt4,57 +import statsmodels.api as smsm5,89 +import seaborn as sbsb7,158 +import globeop_reports as opsops11,237 +def get_mark_df(asset_class = 'Subprime'):get_mark_df13,268 +def calc_mark_diff(df, sources= ['PRICESERVE', 'PRICINGDIRECT','BVAL','MARKIT','BROKER', 'REUTERcalc_mark_diff27,1083 +def closest(x):closest53,2307 +def remove_max_min(x):remove_max_min60,2514 +def diff_by_source(df):diff_by_source66,2655 +def diff_by_source_percentage(df):diff_by_source_percentage75,3063 +def count_sources(df):count_sources82,3273 +def alt_navs():alt_navs88,3566 +def annual_performance(nav_100):annual_performance102,4267 +def alt_nav_impact():alt_nav_impact108,4459 +def back_test(begindate = '2013-01-01', enddate = '2018-01-01', sell_price_threshold = 200):back_test115,4649 +def stats(df_long, diff_threshold = 5):stats136,5949 +def pretty_plot(df_long):pretty_plot147,6308 -pyisda/pyisda/curve.pyx,2697 - FOLLOW = <long>'F'FOLLOW32,1096 - PREVIOUS = <long>'P'PREVIOUS33,1119 - NONE = <long>'N'NONE34,1144 - MODIFIED = <long>'M'MODIFIED35,1165 -cdef class Curve(object):Curve44,1373 - def __getstate__(self):__getstate__46,1400 - def __setstate__(self, bytes state):__setstate__54,1713 - def from_bytes(cls, object state):from_bytes62,1966 - def __hash__(self):__hash__77,2487 - def inspect(self):inspect87,2849 - def to_series(self, bint forward=True):to_series103,3412 - def __iter__(self):__iter__131,4549 - def __len__(self):__len__138,4783 - def __deepcopy__(self, dict memo):__deepcopy__141,4852 - def forward_hazard_rates(self):forward_hazard_rates149,5097 - def base_date(self):base_date180,6343 - def __forward_zero_price(self, d2, d1=None):__forward_zero_price183,6431 -cdef fArray_to_list(TRatePt* fArray, int fNumItems):fArray_to_list205,7162 -cdef class YieldCurve(Curve):YieldCurve212,7369 - def __init__(self, date, str types,__init__241,8331 - def __getstate__(self):__getstate__297,10508 - def __setstate__(self, bytes state):__setstate__308,10967 - def __deepcopy__(self, dict memo):__deepcopy__321,11441 - def from_bytes(cls, object state):from_bytes329,11721 - def __hash__(self):__hash__352,12505 - def from_discount_factors(cls, base_date, list dates, double[:] dfs, str day_count_conv):from_discount_factors369,13161 - discount_factor = Curve.__forward_zero_pricediscount_factor386,14021 - def dates(self):dates389,14085 - def expected_forward_curve(self, forward_date):expected_forward_curve395,14225 -cdef void tweak_curve(TCurve* sc, TCurve* sc_tweaked, double epsilon,tweak_curve419,15287 -cdef class SpreadCurve(Curve):SpreadCurve442,16027 - def __init__(self, today, YieldCurve yc, start_date, step_in_date,__init__464,16700 - survival_probability = Curve.__forward_zero_pricesurvival_probability570,21409 - def __getstate__(self):__getstate__572,21464 - def __setstate__(self, bytes state):__setstate__585,22071 - def __deepcopy__(self, dict memo):__deepcopy__602,22797 - def from_bytes(cls, bytes state):from_bytes613,23296 - def __hash__(self):__hash__639,24277 - def from_flat_hazard(cls, base_date, double rate, Basis basis=CONTINUOUS,from_flat_hazard655,24970 - def tweak_curve(self, double epsilon, bint multiplicative=True,tweak_curve681,25940 - def par_spread(self, today, step_in_date, start_date, end_dates,par_spread726,27588 - def ticker(self):ticker773,29630 - def recovery_rates(self):recovery_rates777,29703 -cdef TCurve* _fill_curve(TCurve* sc, TDate* end_dates, int n_dates):_fill_curve786,30061 +populate_risk_numbers.py,209 +def get_index_list(basedir):get_index_list6,98 +def get_attach_from_name(index_type, series):get_attach_from_name16,559 +def convert(s):convert33,1066 +def populate_risk(basedir, db):populate_risk36,1124 -pyisda/pyisda/curve.pxd,527 - CONTINUOUS = 5000CONTINUOUS193,8215 - DISCOUNT_RATE = 512DISCOUNT_RATE194,8237 - SIMPLE_BASIS = 0SIMPLE_BASIS195,8261 - ANNUAL_BASIS = 1ANNUAL_BASIS196,8282 - DISCOUNT_FACTOR = -2DISCOUNT_FACTOR197,8303 -cdef class Curve:Curve208,8559 -cdef class YieldCurve(Curve):YieldCurve211,8615 -cdef class SpreadCurve(Curve):SpreadCurve214,8675 -cdef fArray_to_list(TRatePt* fArray, int fNumItems)fArray_to_list218,8773 -cdef void tweak_curve(TCurve* sc, TCurve* sc_tweaked, double epsilon,tweak_curve220,8826 +task_server/rest.py,238 +def get_db():get_db13,280 +def get_queue():get_queue23,582 +def close_db(error):close_db31,767 +def intex():intex39,948 +def globeop():globeop46,1117 +def insert_tranches():insert_tranches54,1401 +def run_tasks():run_tasks60,1513 -pyisda/pyisda/credit_index.pyx,1813 -cdef TFeeLeg* copyFeeLeg(TFeeLeg* leg) nogil:copyFeeLeg31,1229 -cdef TContingentLeg* copyContingentLeg(TContingentLeg* leg) nogil:copyContingentLeg43,1753 -cdef class CurveList:CurveList49,1999 - def __init__(self, list curves not None, double[:] weights=None, trade_date=None):__init__52,2058 - def __getitem__(self, str ticker):__getitem__99,3713 - def items(self):items115,4252 - def weights(self):weights129,4710 - def tickers(self):tickers138,5032 - def trade_date(self):trade_date147,5321 - def trade_date(self, d):trade_date151,5418 - def curves(self):curves155,5506 - def curves(self, list l not None):curves173,6050 - def __reduce__(self):__reduce__201,7075 -cdef class CreditIndex(CurveList):CreditIndex206,7256 - def __init__(self, start_date, maturities, list curves, double[:] weights=None,__init__207,7291 - def __dealloc__(self):__dealloc__225,8182 - def __reduce__(self):__reduce__262,9846 - def __hash__(self):__hash__267,10051 - def pv_vec(self, step_in_date, value_date, YieldCurve yc, double recovery_rate):pv_vec298,11366 - def accrued(self):accrued349,13600 - def pv(self, step_in_date, value_date, maturity, YieldCurve yc not None,pv354,13736 - def theta(self, step_in_date, value_date, maturity, YieldCurve yc not None,theta385,14997 - def duration(self, step_in_date, value_date, maturity, YieldCurve yc not None):duration433,16989 - def maturities(self):maturities482,18677 - def tweak_portfolio(self, double epsilon, maturity, bint inplace=True):tweak_portfolio491,18877 - def survival_matrix(self, TDate[:] schedule):survival_matrix501,19313 -cdef pair[TContingentLeg_ptr,TFeeLeg_ptr] get_legs(TDate maturity,get_legs557,20951 -cdef double pv(vector[shared_ptr[TCurve]]& curves,pv580,21929 +task_server/__main__.py,0 -pyisda/pyisda/version.pyx,28 -def version():version4,71 +task_server/config.py,0 -pyisda/pyisda/utils.py,303 -def getMarkitIRData(date = datetime.date.today() - datetime.timedelta(days = 1),getMarkitIRData18,698 -def rate_helpers(currency="USD", MarkitData=None):rate_helpers39,1913 -def YC(currency="USD", helpers = None, MarkitData=None):YC65,3423 -def build_yc(trade_date, ql_curve=False):build_yc72,3691 +task_server/insert_tranche_quotes.py,138 +def convert(x):convert18,504 +def convert_int(x):convert_int27,696 +def insert_quotes(year=2016, quote_dir=None):insert_quotes40,1065 -pyisda/pyisda/flat_hazard.pyx,176 -def strike_vec(double[:] spreads, YieldCurve yc, trade_date, value_date,strike_vec19,644 -def pv_vec(double[:] spreads, YieldCurve yc, trade_date, value_date,pv_vec114,5161 +task_server/.ropeproject/config.py,90 +def set_prefs(prefs):set_prefs5,45 +def project_opened(project):project_opened120,4706 -pyisda/pyisda/legs.pxd,607 - cdef TContingentLeg* JpmcdsCdsContingentLegMake(JpmcdsCdsContingentLegMake39,870 - cdef TFeeLeg* JpmcdsCdsFeeLegMake(JpmcdsCdsFeeLegMake50,1280 - cdef int JpmcdsContingentLegPV(TContingentLeg *cl, # Contingent legJpmcdsContingentLegPV80,2616 - cdef int JpmcdsFeeLegPV(TFeeLeg *fl,JpmcdsFeeLegPV90,3251 - cdef TCashFlowList* JpmcdsFeeLegFlows(TFeeLeg *fl)JpmcdsFeeLegFlows99,3609 - cdef void JpmcdsFeeLegFree(TFeeLeg *p)JpmcdsFeeLegFree101,3664 - cdef void FeeLegAI(TFeeLeg* fl,FeeLegAI103,3707 -cdef class ContingentLeg:ContingentLeg107,3812 -cdef class FeeLeg:FeeLeg111,3874 +task_server/globeop.py,691 + import pandas as pdpd19,289 +def get_ped(s):get_ped25,388 +def key_fun(s):key_fun36,692 +def run_date(s):run_date47,1001 +def get_ftp(folder):get_ftp55,1193 +def get_gpg():get_gpg62,1331 +def convert_to_csv(f):convert_to_csv74,1696 +def download_data(workdate: datetime.date):download_data83,2027 +def insert_todb(workdate: datetime.date):insert_todb147,4086 +def upload_bond_marks(engine, workdate: datetime.datetime):upload_bond_marks176,5217 +def upload_cds_marks(engine, workdate: datetime.datetime):upload_cds_marks195,5912 +def upload_data(engine, workdate: datetime.datetime):upload_data211,6509 +def back_fill(start_date=pd.datetime(2017, 7, 20)):back_fill216,6644 -pyisda/docs/conf.py,925 -extensions = [extensions33,1068 -templates_path = ['_templates']templates_path42,1290 -source_suffix = '.rst'source_suffix48,1452 -master_doc = 'index'master_doc55,1574 -project = 'PyISDA'project58,1637 -copyright = '2016, Guillaume Horel'copyright59,1656 -author = 'Guillaume Horel'author60,1692 -version = '0.1'version67,1921 -release = '0.1'release69,1987 -language = Nonelanguage76,2258 -exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']exclude_patterns90,2689 -pygments_style = 'sphinx'pygments_style112,3303 -todo_include_todos = Truetodo_include_todos121,3597 -html_theme = 'sphinx_rtd_theme'html_theme129,3808 -html_static_path = ['_static']html_static_path163,4918 -htmlhelp_basename = 'PyISDAdoc'htmlhelp_basename243,7289 -latex_elements = {latex_elements247,7399 -latex_documents = [latex_documents268,7917 -man_pages = [man_pages310,8992 -texinfo_documents = [texinfo_documents325,9391 +task_server/README.md,0 -pyisda/docs/Makefile,450 -SPHINXOPTS =SPHINXOPTS5,92 -SPHINXBUILD = sphinx-buildSPHINXBUILD6,108 -PAPER =PAPER7,137 -BUILDDIR = _buildBUILDDIR8,153 -PAPEROPT_a4 = -D latex_paper_size=a4PAPEROPT_a411,199 -PAPEROPT_letter = -D latex_paper_size=letterPAPEROPT_letter12,240 -ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .ALLSPHINXOPTS13,285 -I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .I18NSPHINXOPTS15,441 +task_server/__init__.py,0 -pyisda/c_layer/cdsbootstrap.h,484 -#define SUCCESS SUCCESS12,171 -#define FAILURE FAILURE13,189 - TDate stepinDate;stepinDate17,226 - TDate cashSettleDate;cashSettleDate18,258 - TCurve *discountCurve;discountCurve19,294 - TCurve *cdsCurve;cdsCurve20,329 - double recoveryRate;recoveryRate21,359 - double spread;spread22,393 - TContingentLeg *cl;cl23,421 - TFeeLeg *fl;fl24,445 -} cds_bootstrap_ctx;cds_bootstrap_ctx25,469 +adj_index_price.py,28 +import pandas as pdpd2,65 -pyisda/c_layer/cdsbootstrap.c,61 -int cdsBootstrapPointFunctioncdsBootstrapPointFunction3,27 +build_default_table.py,27 +import pandas as pdpd1,0 -pyisda/Makefile,0 +external_deriv_marks.py,260 +import pandas as pdpd2,16 +def gs_navs(date: datetime.date = None):gs_navs7,74 +def ms_navs(date: datetime.date = None):ms_navs30,964 +def citi_navs(date: datetime.date = None):citi_navs48,1663 +def baml_navs(date: datetime.date = None):baml_navs76,2676 -pyisda/setup.py,1087 -all_extensions = Extension("*", ["pyisda/*.pyx"],all_extensions6,124 - include_dirs = ['c_layer', numpy.get_include()],include_dirs7,174 - libraries = ["cds", "farmhash"],libraries8,250 - language = 'c++')language9,310 -c_extension = Extension("pyisda.flat_hazard",c_extension11,356 - include_dirs = ['c_layer', numpy.get_include()],include_dirs12,402 - sources = ['pyisda/flat_hazard.pyx', 'c_layer/cdsbootstrap.c'],sources13,475 - libraries = ['cds'],libraries14,563 - language = 'c++')language15,608 -all_extensions = cythonize([c_extension, all_extensions], nthreads = 4,all_extensions17,651 - compiler_directives={'embedsignature':True})compiler_directives18,723 - name = "pyisda",name21,803 - version = '0.1',version22,824 - author = 'Guillaume Horel',author23,845 - ext_modules = all_extensions,ext_modules24,877 - packages = ['pyisda'])packages25,911 +backfill_index.py,29 +import pandas as pdpd4,112 -pyisda/example.py,1776 - today_date = datetime.date(2016, 7, 12)today_date11,298 - yc = build_yc(today_date, True)yc12,342 - step_in_date = today_date + datetime.timedelta(days=1)step_in_date13,378 - value_date = datetime.date(2016, 7, 15) # settle_datevalue_date14,437 - start_date = datetime.date(2016, 6, 20)start_date16,496 - end_date = datetime.date(2021, 6, 20)end_date17,540 - upfront_quote = -0.03063upfront_quote18,582 - spread = spread_from_upfront(today_date, value_date, start_date, step_in_date,spread19,611 - upf = upfront_charge(today_date, value_date, start_date, step_in_date,upf23,898 - coupon_leg = FeeLeg(start_date, end_date, True, 1000000, 0.01)coupon_leg28,1091 - contingent_leg = ContingentLeg(start_date, end_date, 1000000)contingent_leg29,1158 - ig_spread = 0.0070ig_spread31,1225 - spread = array.array('d', [ig_spread])spread32,1248 - recovery = array.array('d', [0.4])recovery33,1291 - upfront = array.array('d', [-0.0164243])upfront34,1330 - sc = SpreadCurve(today_date, yc, start_date, step_in_date, value_date,sc36,1419 - sc_data = sc.inspect()['data']sc_data38,1560 - rate = sc_data[0][1]rate39,1595 - continuous_rate = math.log(1+rate)continuous_rate41,1679 - sc2 = SpreadCurve.from_flat_hazard(today_date, continuous_rate)sc242,1718 - coupon_leg_pv = coupon_leg.pv(today_date, step_in_date,coupon_leg_pv43,1786 - coupon_leg_pv2 = coupon_leg.pv(today_date, step_in_date,coupon_leg_pv245,1906 - contingent_leg_pv = contingent_leg.pv(today_date, step_in_date,contingent_leg_pv48,2072 - contingent_leg_pv2 = contingent_leg.pv(today_date, step_in_date,contingent_leg_pv250,2207 - pv = 1000000 * upfront_charge(today_date, value_date, start_date, step_in_date,pv53,2385 +yieldcurve.py,906 +import pandas as pdpd8,167 +import numpy as npnp20,812 +def load_curves(currency="USD", date=None):load_curves28,1002 +def get_curve(effective_date, currency="USD"):get_curve49,1707 +def getMarkitIRData(effective_date=datetime.date.today(),getMarkitIRData70,2503 +def get_futures_data(date=datetime.date.today()):get_futures_data87,3256 +def get_curve_params(currency):get_curve_params94,3565 +def rate_helpers(currency="USD", MarkitData=None, evaluation_date=None):rate_helpers125,4682 +def get_dates(date, currency="USD"):get_dates169,6716 +def roll_yc(yc, forward_date):roll_yc186,7504 +def YC(helpers=None, currency="USD", MarkitData=None, evaluation_date=None,YC193,7815 +def jpYC(effective_date, currency="USD", MarkitData=None):jpYC215,8685 +def ql_to_jp(ql_yc):ql_to_jp235,9475 +def build_curves(currency="USD"):build_curves246,9928 + import matplotlib.pyplot as pltplt286,11920 -ecb_yieldcurve.py,221 -r = requests.get('http://www.ecb.europa.eu/stats/money/yc/data/fmd/download/yc_latest.zip?')r9,111 -yc = io.BytesIO(r.content)yc10,204 -ycunzip = ZipFile(yc)ycunzip11,231 -zipinfos = ycunzip.infolist()zipinfos12,253 +intex/load_indicative.py,230 +def convertToNone(s):convertToNone16,226 +def insert_new_cusip(conn, line):insert_new_cusip20,297 +def upload_cusip_data(conn, filename):upload_cusip_data65,1690 +def upload_deal_data(conn, filename):upload_deal_data147,5057 -handle_default.py,210 -def affected_indices(company_id):affected_indices6,92 -def create_newindices(recordslist, lastdate, nissuers):create_newindices18,525 -def update_indexmembers(newids, company_id):update_indexmembers40,1428 +intex/__main__.py,0 -bbg_helpers.py,2233 -logger = logging.getLogger(__name__)logger8,115 -BBG_IP = ['192.168.9.61', '192.168.9.65', '192.168.0.10', '192.168.0.12']BBG_IP10,153 -def init_bbg_session(ip_list, port=8194):init_bbg_session13,244 -def append_overrides(request, d):append_overrides36,993 -def event_loop(session, request):event_loop46,1326 -def get_pythonvalue(e):get_pythonvalue59,1809 -def field_array_todf(field):field_array_todf71,2173 -def process_historical_msg(msg):process_historical_msg78,2436 -def process_reference_msg(msg):process_reference_msg84,2688 -def process_intraday_tick_msg(msg):process_intraday_tick_msg101,3390 -def retrieve_data(session, securities, fields=[], overrides={},retrieve_data105,3521 - testdate = pd.datetime(2013, 1, 1)testdate188,6766 - hist_securities = ['CADUSD Curncy', "EURUSD Curncy"]hist_securities189,6805 - hist_fields = ['PX_LAST']hist_fields190,6862 - securities = ['004421BW2 Mtge', '75157EAE2 Mtge', 'XS0295516776 Mtge']securities191,6892 - fields = ['CUR_CPN', 'START_ACC_DT']fields192,6967 - hist_data = retrieve_data(session, securities, hist_fields, start_date=testdate,hist_data194,7054 - frequency="MONTHLY")frequency195,7143 - overrides={'SETTLE_DT': testdate}overrides196,7198 - ref_data = retrieve_data(session, securities, fields, overrides=overrides)ref_data197,7240 - struct_data = retrieve_data(session, securities, ["HIST_CASH_FLOW"])struct_data198,7323 - spx_ndx_monthly = retrieve_data(session, ["SPX Index","NDX Index"],spx_ndx_monthly199,7400 - fields=["PX_LAST"],fields200,7476 - start_date=datetime.date(2012, 1, 1),start_date201,7536 - options={'periodicityAdjustment': 'ACTUAL'},options202,7614 - frequency="MONTHLY")frequency203,7699 - trace_data = retrieve_data(session, "BNCMT 2007-1 A5@TRAC Mtge",trace_data204,7760 - start_date=datetime.datetime(2016, 5, 18, 9),start_date205,7833 - end_date=datetime.datetime(2017, 5, 18, 9))end_date206,7914 +intex/common.py,53 +def sanitize_float(intex_float):sanitize_float4,12 -send_email.py,473 -SCOPES = 'https://www.googleapis.com/auth/gmail.modify'SCOPES15,270 -CLIENT_SECRET_FILE = 'secret.json'CLIENT_SECRET_FILE16,326 -APPLICATION_NAME = 'Swaptions'APPLICATION_NAME17,361 -def get_gmail_service():get_gmail_service19,393 -class EmailMessage(MIMEText):EmailMessage45,1457 - _service = get_gmail_service()_service46,1487 - def msgdict(self):msgdict48,1523 - def send(self):send54,1746 -def main():main62,2055 - message = main()message74,2399 +intex/load_intex_collateral.py,104 +def upload_data(conn, workdate):upload_data44,850 +def intex_data(conn, workdate):intex_data216,7681 -GHquad.c,56 -void GHquad(int n, double* Z, double* w) {GHquad7,167 +intex/intex_scenarios.py,307 +def get_reinv_assets(conn, dealname, workdate):get_reinv_assets31,810 +def get_recovery(conn, dealname, workdate, defaultrecovery=50):get_recovery42,1155 +def get_reinvenddate(conn, dealname, workdate):get_reinvenddate61,1835 +def generate_scenarios(workdate, dealname, conn):generate_scenarios73,2226 -download_emails.py,534 -def ListMessagesWithLabels(service, user_id, label_ids=[]):ListMessagesWithLabels21,445 -def ListHistory(service, user_id, label_id=None, start_history_id=10000):ListHistory52,1817 -def labels_dict(service, user_id):labels_dict89,3376 -class GmailMessage(EmailMessage):GmailMessage106,3956 - _service = get_gmail_service()_service107,3990 - def msgdict(self):msgdict109,4026 - def send(self):send112,4125 - def from_id(cls, msg_id, user_id='me'):from_id122,4474 -def save_emails(update=True):save_emails135,5032 +intex/.ropeproject/config.py,90 +def set_prefs(prefs):set_prefs5,45 +def project_opened(project):project_opened120,4706 -debug_forward_price.py,219 -hy28 = Index.from_name("hy", 28, "5yr")hy283,58 -hy28_forward = ForwardIndex(hy28, datetime.date(2017, 8, 16))hy28_forward4,98 -r = []r6,178 - hy28_forward = ForwardIndex(hy28, excercise_date)hy28_forward10,398 +intex/__init__.py,0 -marks_to_HY.py,5400 -def monthlySpreadDiff(index="IG", tenor="5yr"):monthlySpreadDiff16,435 -def nearestDate(base, dates):nearestDate27,1077 -def interpolate_rates(s, hist_data):interpolate_rates31,1235 -def aux(df):aux36,1410 -df = (pd.read_sql_table('external_marks_mapped',dbengine('dawndb'),df42,1549 -BBG_IP = ['192.168.9.65']BBG_IP46,1694 -bbgstartdate = pd.datetime(2013, 1, 1)bbgstartdate48,1795 -hist_securities = ["US0006M Index", "USSWAP2 Curncy", "USSWAP3 Curncy", "USSWAP4 Curncy", "USSWAP5 Curncy", "USSWAP7 Curncy", "USSWAP10 Curncy"]hist_securities49,1834 -hist_fields = ['PX_LAST']hist_fields50,1979 - hist_data = bbg_helpers.retrieve_data(session, hist_securities, hist_fields, start_date=bbgstartdate)hist_data53,2060 -hist_data1 = pd.concat(hist_data,ignore_index=False, names = ['Rate Index', 'numIndex']).reset_index()hist_data155,2171 -mapping = {"US0006M Index": .5, "USSWAP10 Curncy": 10, "USSWAP2 Curncy": 2, "USSWAP3 Curncy": 3, "USSWAP4 Curncy": 4, "USSWAP5 Curncy": 5, "USSWAP7 Curncy": 7}mapping56,2274 -mapping = pd.Series(mapping, name = 'tenor')mapping57,2434 -mapping = mapping.reset_index()mapping59,2513 -hist_data1 = hist_data1.merge(mapping, on='Rate Index')hist_data160,2545 -hist_data1 = hist_data1[['date','PX_LAST','tenor']].set_index('date')hist_data161,2601 -df1 = dfdf165,2792 -df1 = df1.sort_values('date')df167,2860 -df1 = df1.set_index(['date','identifier','source'])df168,2890 -df1 = df1.groupby(level=['date','identifier','source'])['mark'].mean()df169,2942 -df1 = df1.reset_index()df170,3013 -df1 = df1.set_index(['date'])df171,3037 -mapping = pd.read_sql_query("select distinct date(timestamp) as model_date from priced",dbengine('rmbs_model'), parse_dates = ['model_date']).sort_values('model_date')mapping74,3131 -df2 = df.set_index(['date'])df275,3299 -df2 = df2.groupby(level=['date'])['mark'].mean()df276,3328 -df2 = pd.DataFrame(df2)df279,3450 -df1 = df1.join(df2)df183,3567 -df3=pd.DataFrame()df386,3643 - "where date(timestamp) = %s and model_version = 1"sql_str88,3743 - df3= df3.append(pd.read_sql_query(sql_str,dbengine('rmbs_model'), parse_dates = ['date'], params=(date.to_pydatetime(), )))df391,3954 -df3= df3.rename(columns = {"cusip": "identifier"})df393,4083 -df3 = df3.sort_values('date')df394,4134 -df3 = df3.set_index(['date', 'identifier'])df396,4198 -df1 = df1.reset_index()df199,4309 -df1= df1.rename(columns = {"model_date": "date", "date": "monthend_date"})df1100,4333 -df1 = df1.set_index(['date','identifier'])df1101,4408 -df1 = df1.merge(df3, left_index = True, right_index= True)df1103,4452 -df1 = df1.reset_index().sort_values('monthend_date')df1104,4511 -availratesdate = pd.DataFrame(sorted(pd.unique(hist_data1.index)), columns=['date'])availratesdate105,4564 -df1temp = df1.groupby(['identifier','BDay','moddur']).mean().reset_index()df1temp108,4781 -df1 = pd.merge(df1, df1temp[['identifier', 'BDay', 'moddur','yielddiff']], on= ['identifier', 'BDay', 'moddur'])df1111,5006 -df1 = df1.groupby('identifier').apply(aux)df1114,5220 -df1 = df1.set_index(['monthend_date','identifier','source'])df1118,5385 -SpreadFilter = 1000SpreadFilter122,5490 -SpreadDiffFilter = 250SpreadDiffFilter123,5510 -DurationFilter = 1.5DurationFilter124,5533 -begindate = '2014-01-01'begindate125,5554 -enddate = '2017-01-01'enddate126,5579 -interval = 1interval127,5602 -HYDifference = monthlySpreadDiff(index = 'HY')HYDifference128,5615 -difference = df1[abs(df1['spread'])<SpreadFilter].groupby(level=['identifier','source'])['pv','moddur','spread'].diff(periods = interval)difference129,5662 -difference = difference[abs(difference['spread'])<SpreadDiffFilter]difference130,5800 -difference = difference[abs(difference['moddur'])<DurationFilter]difference131,5868 -avgchange1 = pd.DataFrame(difference.groupby(level=['monthend_date']).mean()['spread'])avgchange1135,6042 -avgchange1 = avgchange1.join(HYDifference, rsuffix = 'HY')avgchange1136,6130 -avgchange1 = avgchange1[begindate:enddate]avgchange1137,6189 -regmodel1 = sm.OLS(avgchange1['spread'],avgchange1['spreadHY']).fit()regmodel1138,6232 -ratio1 = (avgchange1['spreadHY']/avgchange1['spread']).mean()ratio1139,6302 -avgchange2 = pd.DataFrame(difference.groupby(level=['monthend_date','source']).mean()['spread'])avgchange2142,6404 -avgchange2 = avgchange2.unstack(level =1)avgchange2143,6501 -HYDifference = HYDifference.to_frame()HYDifference144,6543 -avgchange2 = avgchange2.merge(HYDifference, left_index = True, right_index= True)avgchange2146,6651 -regmodel2 ={}regmodel2147,6733 -ratio2 = {}ratio2148,6747 -Rsquared2 = {}Rsquared2153,6991 -params2 = {}params2154,7006 -difference1 = difference.reset_index().set_index('monthend_date')difference1161,7278 -difference1 = difference1.merge(HYDifference, left_index = True, right_index= True)difference1165,7563 -regmodel3 = {}regmodel3166,7647 -Rsquared3 = {}Rsquared3167,7662 -params3 = {}params3168,7677 -difference4 = difference1.rename(columns = {('HY'): "HY Spread"})difference4178,8192 -difference4 = difference4.set_index('source', append = True)difference4181,8397 -meanmarkchange= difference4.groupby(level = ['monthend_date', 'source'])['spread'].mean().unstack(level = -1)meanmarkchange182,8458 -StdDevmarkchange = difference4.groupby(level = ['monthend_date', 'source'])['spread'].std().unstack(level = -1)StdDevmarkchange183,8568 +flask-run.py,0 -cds_curve.py,502 -def all_curves_pv(curves, today_date, jp_yc, start_date, step_in_date, value_date, maturities):all_curves_pv11,221 -def calibrate_portfolio(index_type, series, tenors=['3yr', '5yr', '7yr', '10yr'],calibrate_portfolio32,1249 - parser = argparse.ArgumentParser()parser50,1962 - args = parser.parse_args()args54,2204 - conn = dbconn('serenitasdb')conn56,2279 - start_date = Nonestart_date66,2631 - df = calibrate_portfolio(index, series, ['3yr', '5yr', '7yr', '10yr'],df68,2658 +GHquad.h,0 -cds_rebook.py,333 -def get_outstanding_positions(engine):get_outstanding_positions7,148 -def next_redcode(engine, secid):next_redcode19,711 -def rebook(engine, secid, lastdate, already_rebooked):rebook31,1141 -def rebook_everything(engine):rebook_everything49,1961 - engine = create_engine("postgresql://dawn_user@debian/dawndb")engine59,2338 +backtest.py,206 +import pandas as pdpd2,16 +def set_strikes(payer, receiver):set_strikes9,210 +def set_up_strategy(start_date: datetime.date, tenor: 3):set_up_strategy25,582 +def backtest(portf, index):backtest42,1190 -dawn_utils.py,363 -def create_trigger_function(db):create_trigger_function6,100 -def create_triggers(db):create_triggers42,1466 -def load_counterparties(engine):load_counterparties51,1815 -def load_trades(engine, schema=None):load_trades70,3153 -def load_trades_futures(engine, schema=None):load_trades_futures100,4798 -def load_wires(engine, schema=None):load_wires135,6686 +templates/template-2014-07-16.html,0 -parse_emails.py,3053 - level=logging.WARNING,level16,379 - format='%(asctime)s %(message)s')format17,422 -def list_imm_dates(date):list_imm_dates19,477 -def makedf(r, indextype, quote_source):makedf27,657 -def parse_quotedate(fh, date_received):parse_quotedate55,1740 -def parse_refline(line):parse_refline72,2400 -def parse_baml(fh, indextype, series, quotedate, *args):parse_baml84,2855 -def parse_baml_block(fh, indextype):parse_baml_block110,3723 -def parse_ms_block(fh, indextype):parse_ms_block126,4188 -def parse_nomura_block(fh, indextype):parse_nomura_block158,5298 -def parse_sg_block(fh, indextype, expiration_dates):parse_sg_block181,6111 -def parse_gs_block(fh, indextype):parse_gs_block209,7204 -def parse_ms(fh, indextype, *args):parse_ms238,8023 -def parse_nomura(fh, indextype, *args):parse_nomura250,8416 - def aux(line, fh, indextype, option_stack):aux252,8478 -def parse_sg(fh, indextype, expiration_dates):parse_sg268,9087 -def parse_gs(fh, indextype, series, quotedate, ref):parse_gs278,9396 -subject_baml = re.compile("(?:Fwd:){0,2}(?:BAML )?(\w{2})([0-9]{1,2})\s")subject_baml301,10391 -subject_ms = re.compile("[^$]*\$\$ MS CDX OPTIONS: (IG|HY)(\d{2})[^-]*- REF[^\d]*([\d.]+)")subject_ms302,10465 -subject_nomura = re.compile("(?:Fwd:)?CDX (IG|HY)(\d{2}).*- REF:[^\d]*([\d.]+)")subject_nomura303,10557 -subject_gs = re.compile("GS (IG|HY)(\d{2}) 5y.*- Ref [^\d]*([\d.]+)")subject_gs304,10638 -subject_sg = re.compile("SG OPTIONS - CDX (IG|HY) S(\d{2}).* REF[^\d]*([\d.]+)")subject_sg305,10708 -def parse_email(email, date_received):parse_email307,10790 -def write_todb(swaption_stack, index_data):write_todb345,12712 - def gen_sql_str(query, table_name, columns):gen_sql_str346,12756 -def get_email_list(date):get_email_list370,13887 -def pickle_drop_date(date):pickle_drop_date384,14298 - data_dir = os.path.join(os.getenv("DATA_DIR"), "swaptions")data_dir393,14600 - emails = [f for f in os.scandir(data_dir) if f.is_file()]emails394,14664 - swaption_stack = {}swaption_stack395,14726 - index_data = pd.DataFrame()index_data396,14750 - already_uploaded = pickle.load(fh)already_uploaded399,14833 - already_uploaded = {}already_uploaded401,14910 - date_received = datetime.datetime.strptime(date_received, "%Y-%m-%d %H-%M-%S")date_received404,15011 - index_data = index_data.append(fwd_index)index_data417,15594 - swaption_stack = pd.concat(swaption_stack, names=['quotedate', 'index', 'series'])swaption_stack426,15963 - swaption_stack = swaption_stack.reset_index()swaption_stack427,16050 - swaption_stack = swaption_stack.drop_duplicates(['quotedate', 'index', 'series', 'expiry', 'strike'])swaption_stack428,16100 - swaption_stack = swaption_stack.set_index(['quotedate', 'index', 'series', 'expiry'])swaption_stack429,16206 - index_data = index_data.reset_index()index_data430,16296 - index_data = index_data.drop_duplicates(['quotedate', 'index', 'series', 'expiry'])index_data431,16338 +templates/template-2015-03-16.html,0 -populate_risk_numbers.py,404 -basedir = "/home/share/CorpCDOs"basedir5,65 -def get_index_list(basedir):get_index_list6,98 -sqlstr = "INSERT INTO risk_numbers VALUES({0},{1})".format(",".join(["%s"] * 10),sqlstr13,388 -def get_attach_from_name(index_type, series):get_attach_from_name16,559 -def convert(s):convert33,1066 -def populate_risk(basedir, db):populate_risk36,1124 - basedir = "/home/share/CorpCDOs"basedir62,2593 +templates/template-2014-06-13.html,0 + +templates/template-2015-01-14.html,0 -pnl_explain.py,949 +templates/template-2014-05-19.html,0 + +templates/template-2014-08-12.html,0 + +templates/trading_form.tex,0 + +templates/template2-2014-04-16.html,0 + +templates/template-2014-03-17.html,0 + +templates/template-2014-03-12.html,0 + +templates/template-2014-11-13.html,0 + +templates/template-2014-12-11.html,0 + +templates/template-2014-09-15.html,0 + +templates/template-2014-04-16.html,0 + +templates/template-2015-04-20.html,0 + +templates/template-2014-10-17.html,0 + +templates/template-2015-02-12.html,0 + +markit_tranches.py,27 +import pandas as pdpd1,0 + +common.py,99 +def sanitize_float(intex_float):sanitize_float6,50 +def get_redis_queue():get_redis_queue18,445 + +pnl_explain.py,618 +import numpy as npnp1,0 +import pandas as pdpd2,19 def get_daycount(identifier, engine=dbengine("dawndb")):get_daycount7,112 def pnl_explain(identifier, start_date = None, end_date = None,pnl_explain21,578 def pnl_explain_list(id_list, start_date = None, end_date = None, engine = dbengine("dawndb")):pnl_explain_list101,5033 def compute_tranche_factors(df, attach, detach):compute_tranche_factors105,5269 def cds_explain(index, series, tenor, attach = np.nan, detach = np.nan,cds_explain114,5785 def cds_explain_strat(strat, start_date, end_date, engine = dbengine("dawndb")):cds_explain_strat187,9766 - engine = dbengine("dawndb")engine216,11309 - subprime_list = get_list_range(engine, '2015-09-30', '2015-10-31', 'Subprime')subprime_list224,11643 - df_subprime = pnl_explain_list(subprime_list[['identifier', 'strategy']].to_records(index=False),df_subprime225,11726 - df_subprime = pd.concat(df_subprime, names=['identifier', 'strategy', 'date'])df_subprime227,11899 -script_calibrate_tranches.py,605 -n_int = 500n_int4,69 -n_credit = 100n_credit5,81 - recov = np.array([float(e) for e in fh], dtype='double', order='F')recov9,148 - SurvProb = np.array([[float(e) for e in line.split(",")] for line in fh], dtype='double', order='F')SurvProb12,254 -defaultprob = 1 - SurvProbdefaultprob14,360 -p = defaultprobp15,387 -rho = 0.45 * np.ones(n_credit)rho16,403 - Rstoch = np.zeros((n_credit, n_int, SurvProb.shape[1]))Rstoch19,456 - L = np.zeros((n_int, Ngrid, SurvProb.shape[1]))L23,690 - R = np.zeros((n_int, Ngrid, SurvProb.shape[1]))R24,742 - S = 1 - Rstoch[:,:,t]S26,834 +markit_tranche_quotes.py,100 +def get_latest_quote_id(db):get_latest_quote_id36,925 +def convert_float(s):convert_float43,1101 + +test_quotes.py,184 +import pandas as pdpd2,16 +def get_refids(index, series, expiry, value_date=datetime.date.today(),get_refids8,138 +def adjust_stacks(index_type, series, expiry,adjust_stacks24,769 -optimization.py,344 +dawn_utils.py,447 +import pandas as pdpd2,10 +def create_trigger_function(db):create_trigger_function4,31 +def create_triggers(db):create_triggers43,1265 +def load_counterparties(engine):load_counterparties52,1614 +def load_trades(engine, schema=None):load_trades71,2939 +def load_trades_futures(engine, schema=None):load_trades_futures101,4554 +def load_wires(engine, schema=None):load_wires136,6442 +def load_spots(engine, schema=None):load_spots160,7702 + +experiments/exchange_example.py,0 + +experiments/test_timestamptz.py,27 +import pandas as pdpd1,0 + +experiments/test_matrix.py,312 +import numpy as npnp1,0 +import scipy.linalg as splinalgsplinalg2,19 +import dask.array as dada3,51 +def get_num_threads():get_num_threads10,216 +def set_num_threads(n):set_num_threads13,291 +def test():test26,595 +def test2():test230,692 +def test3():test334,815 + def test_dask():test_dask55,1521 + +experiments/test_dask.py,149 +import dask.dataframe as dddd1,0 +import numpy as npnp2,28 +strip_percent = lambda s: float(s.rstrip('%'))/100 if s else np.nanstrip_percent4,48 + +experiments/test_basket.py,28 +import pandas as pdpd2,36 + +experiments/test_trace.py,28 +import pandas as pdpd2,64 + +experiments/test_asyncpg.py,235 +async def dbconn():dbconn10,184 +async def get_singlenames_quotes_async(con, indexname, date):get_singlenames_quotes_async16,394 +async def get_curves(con, currency="USD", date=None):get_curves24,744 +async def main():main29,1028 + +experiments/.ropeproject/config.py,90 +def set_prefs(prefs):set_prefs5,45 +def project_opened(project):project_opened120,4706 + +experiments/test_async.py,157 +async def pomme():pomme3,16 +async def poire():poire8,106 +async def main():main13,196 +async def ping(msg):ping18,275 +async def pong(msg):pong26,416 + +trace_update.py,262 +import pandas as pdpd2,64 +def get_universe():get_universe7,182 +def get_bbg_data(cusips, universe):get_bbg_data12,347 +def insert_data(dfs, conn):insert_data22,835 +def get_cusips():get_cusips37,1428 +def calc_check_digit(number):calc_check_digit44,1624 + +GHquad.c,56 +void GHquad(int n, double* Z, double* w) {GHquad7,167 + +bbg_helpers.py,547 +import pandas as pdpd2,14 +def init_bbg_session(ip_list, port=8194):init_bbg_session14,256 +def append_overrides(request, d):append_overrides38,1006 +def event_loop(session, request):event_loop49,1340 +def get_pythonvalue(e):get_pythonvalue63,1823 +def field_array_todf(field):field_array_todf80,2304 +def process_historical_msg(msg):process_historical_msg92,2569 +def process_reference_msg(msg):process_reference_msg99,2822 +def process_intraday_tick_msg(msg):process_intraday_tick_msg119,3556 +def retrieve_data(retrieve_data124,3688 + +collateral/__main__.py,27 +import pandas as pdpd1,0 + +collateral/common.py,197 +import pandas as pdpd2,15 +def compare_notionals(df, positions, fcm: str):compare_notionals8,108 +def get_dawn_trades(d, engine):get_dawn_trades25,698 +def send_email(d, df):send_email72,2082 + +collateral/citi.py,413 +import pandas as pdpd1,0 +def load_file(d):load_file8,143 +def download_files(count=20):download_files20,478 +def load_pdf(file_path):load_pdf36,944 +def get_col(l, top, bottom, left, right):get_col47,1265 +def parse_num(s):parse_num58,1499 +def get_df(l, col1, col2, col3):get_df66,1631 +def get_total_collateral(d):get_total_collateral76,1892 +def collateral(d, dawn_trades, *args):collateral104,2804 + +collateral/baml_isda.py,207 +import pandas as pdpd5,92 +def download_from_secure_id(download_from_secure_id14,263 +def download_files(d=None, count=20):download_files55,1871 +def collateral(d, dawn_trades, *args):collateral83,2978 + +collateral/wells.py,305 +import pandas as pdpd1,0 +def get_wells_sftp_client():get_wells_sftp_client11,299 +def get_wells_sftp_client2():get_wells_sftp_client217,503 +def download_files2(d=None):download_files227,801 +def download_files(d=None):download_files36,1090 +def collateral(d, positions, engine):collateral54,1782 + +collateral/baml_fcm.py,180 +import pandas as pdpd5,128 +def get_sftp_client():get_sftp_client9,192 +def download_files(d=None):download_files16,452 +def collateral(d, positions, engine):collateral25,724 + +collateral/ms.py,134 +import pandas as pdpd1,0 +def download_files(count=20):download_files5,46 +def collateral(d, dawn_trades, *args):collateral28,778 + +collateral/gs.py,178 +import pandas as pdpd1,0 +def download_files(count=20):download_files5,46 +def load_file(d, pattern):load_file22,553 +def collateral(d, dawn_trades, *args):collateral30,835 + +collateral/sg.py,187 +import pandas as pdpd2,15 +def get_sftp_client():get_sftp_client11,155 +def download_files(download_files17,360 +def collateral(d, engine):collateral63,1802 + def f(g):f116,4228 + +collateral/__init__.py,0 + +optimization.py,229 +import numpy as npnp1,0 +import numpy.linalg as lala2,19 def decr_fun(a, b):decr_fun5,94 def KLfit(P, q, b):KLfit8,175 def interpweights(w, v1, v2):interpweights60,1694 def interpvalues(w, v, neww):interpvalues67,1951 - P = np.array([[5, 4, 3, 2, 1],[3, 3, 4, 3, 3]])P100,2805 - w = np.ones(5)/5w101,2857 - b = np.array([2.5, 3.3])b102,2878 - test = KLfit(P, w, b)test103,2907 -mailing_list.py,854 -root = "/home/share/serenitas/Fund Raising"root12,270 -def get_mailinglist(name):get_mailinglist14,315 - server = smtplib.SMTP('smtp.gmail.com:587')server25,762 - s_text = Template(fh.read())s_text30,950 - s_html = Template(fh.read())s_html33,1060 - attachment_name = 'Serenitas Capital (SCGMF Returns).pdf'attachment_name35,1098 - pdf_attach1 = MIMEApplication(fh.read(), 'pdf')pdf_attach137,1237 - attachment_name = 'Serenitas Credit Gamma Master Fund - Investor Letter 1Q2015.pdf'attachment_name40,1386 - pdf_attach2 = MIMEApplication(fh.read(), 'pdf')pdf_attach242,1557 - mailing_list = get_mailinglist(sys.argv[1])mailing_list45,1706 - msg = MIMEMultipart()msg48,1830 - msg_alternative = MIMEMultipart('alternative')msg_alternative54,2237 - name = " " + namename56,2309 +calibrate_swaption.py,365 +import pandas as pdpd1,0 +def get_data(index, series, date=datetime.date.min):get_data15,299 +def get_data_latest():get_data_latest32,889 +def calib(option, ref, strike, pay_bid, pay_offer, rec_bid, rec_offer):calib51,1526 +def MaybePool(nproc):MaybePool82,2553 +def calibrate(index_type=None, series=None, date=None, nproc=4, latest=False):calibrate86,2622 -client.py,236 -def run():run9,149 - logger = logging.getLogger('intex')logger31,903 - formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')formatter32,943 - sh = logging.StreamHandler(sys.stdout)sh35,1119 +test.xml,397 + <fontspec id="0" size="13" family="Helvetica" color="#000000"/>06,208 + <fontspec id="1" size="10" family="TRMONK+DejaVuSans" color="#000000"/>17,273 + <fontspec id="2" size="10" family="VPOPDX+DejaVuSans" color="#000000"/>28,346 + <fontspec id="3" size="16" family="VPOPDX+DejaVuSans" color="#000000"/>39,419 + <fontspec id="4" size="5" family="TRMONK+DejaVuSans" color="#000000"/>410,492 -position.py,1541 -def get_list(engine, workdate=None, asset_class=None, include_unsettled=True):get_list14,290 -def get_list_range(engine, begin, end, asset_class=None):get_list_range28,1116 -def backpopulate_marks(begin_str='2015-01-15', end_str='2015-07-15'):backpopulate_marks41,1883 -def update_securities(engine, session, workdate):update_securities61,3186 -def init_fx(session, engine, startdate):init_fx80,4136 -def update_fx(conn, session, currencies):update_fx89,4619 -def init_swap_rates(conn, session, tenors=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 30],init_swap_rates107,5279 -def init_swaption_vol(session,init_swaption_vol123,6031 -def split_tenor_expiry(ticker, vol_type='N'):split_tenor_expiry136,6550 -def insert_swaption_vol(data, conn, source, vol_type="N"):insert_swaption_vol146,6865 -def update_swaption_vol(conn, session,update_swaption_vol166,7830 -def update_swap_rates(conn, session,update_swap_rates205,9479 -def populate_cashflow_history(engine, session, workdate=None):populate_cashflow_history218,10109 - serenitas_conn = psycopg2.connect(database="serenitasdb",serenitas_conn263,12506 - user="serenitas_user",user264,12568 - host="debian")host265,12629 - dawn_engine = create_engine('postgresql://dawn_user@debian/dawndb')dawn_engine266,12682 - dawn_conn = dawn_engine.raw_connection()dawn_conn267,12754 - workdate = pd.Timestamp(sys.argv[1])workdate269,12825 - workdate = pd.datetime.today()workdate271,12880 +env.py,0 -load_globeop_report.py,851 -def get_globs(fname, years=['2013', '2014', '2015', '2016', '2017']):get_globs9,148 -def read_valuation_report(f):read_valuation_report21,703 -def valuation_reports():valuation_reports42,1493 -def read_pnl_report(f):read_pnl_report50,1910 -def pnl_reports():pnl_reports58,2257 -def read_cds_report(f, old_report=False):read_cds_report69,2695 -def cds_reports():cds_reports103,4463 -def monthly_pnl_bycusip(df, strats):monthly_pnl_bycusip113,4851 - df_val = pd.read_hdf('globeop.hdf', 'valuation_report')df_val121,5213 - df_pnl = pd.read_hdf('globeop.hdf', 'pnl')df_pnl122,5273 - subprime_strats = ['MTG_GOOD', 'MTG_RW', 'MTG_IO','MTG_THRU', 'MTG_B4PR']subprime_strats124,5410 - clo_strats = ['CLO_BBB', 'CLO_AAA', 'CLO_BB20']clo_strats125,5488 - df_monthly = monthly_pnl_bycusip(df_pnl, subprime_strats)df_monthly130,5637 +markit_red.py,242 +import pandas as pdpd9,148 +def request_payload(payload):request_payload12,170 +def download_report(report):download_report30,749 +def update_redcodes(fname):update_redcodes62,1643 +def update_redindices(fname):update_redindices94,2802 -markit/cds.py,238 -logger = logging.getLogger(__name__)logger10,161 -def convertToNone(v):convertToNone12,201 -def download_cds_data(payload):download_cds_data15,255 -def download_composite_data(payload, historical=False):download_composite_data29,805 +mark_backtest.py,177 +import pandas as pdpd1,0 +def calc_mark_diff(asset_class="Subprime"):calc_mark_diff5,46 + def closest(x):closest35,1353 + def remove_max_min(x):remove_max_min56,2172 -markit/__init__.py,0 +load_refentity.py,395 +import lxml.etree as etreeetree5,79 +def todict(xml, uselist=set()):todict11,191 +def dispatch_parsing(col, uselist):dispatch_parsing30,777 +def insert_refentity(fname):insert_refentity43,1110 +def parse_prospectus(xml):parse_prospectus98,2593 +def insert_refobligation(fname):insert_refobligation102,2681 + def simple_parse(e):simple_parse155,4180 +def get_date(f):get_date187,5316 -markit/loans.py,315 -logger = logging.getLogger(__name__)logger9,129 -def download_facility(workdate, payload):download_facility11,169 -def insert_facility(conn, workdate):insert_facility18,531 -def download_marks(conn, workdate, payload):download_marks39,1422 -def update_facility(conn, workdate, payload):update_facility59,2414 +notebooks/.ipynb_checkpoints/path-checkpoint.py,0 -markit/rates.py,90 -def downloadMarkitIRData(download_date=datetime.date.today(),downloadMarkitIRData14,255 +notebooks/path.py,0 -markit/__main__.py,1330 -parser = argparse.ArgumentParser()parser20,529 -group = parser.add_mutually_exclusive_group(required=True)group21,564 - help="download markit loan data")help23,680 - help="download markit cds data")help25,788 - help="download markit IR data")help27,897 - help="do not re-download data")help29,1012 -args = parser.parse_args()args32,1169 -historical = Truehistorical33,1196 - historical = Falsehistorical35,1240 - workdate = default_date()workdate36,1263 - workdate = args.workdateworkdate38,1299 - log_file = os.path.join(os.environ['LOG_DIR'], 'markit_loans.log')log_file41,1344 - log_file = os.path.join(os.environ['LOG_DIR'], 'markit_cds.log')log_file43,1430 - log_file = os.path.join(os.environ['LOG_DIR'], 'markit_rates.log')log_file45,1516 -logger = logging.getLogger('markit')logger48,1606 -fh = logging.FileHandler(filename=log_file)fh49,1643 -formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')formatter50,1687 - payload = {'LEGALENTITY': 'lmcg',payload56,1868 - payload = {'user': 'GuillaumeHorel',payload72,2418 - serenitasdb = dbconn('serenitasdb')serenitasdb83,2858 - engine = create_engine('postgresql://serenitas_user@debian/serenitasdb')engine87,2989 +load_globeop_report.py,631 +import pandas as pdpd3,33 +def get_globs(fname, years=["2013", "2014", "2015", "2016", "2017"]):get_globs9,139 +def read_valuation_report(f):read_valuation_report26,603 +def valuation_reports():valuation_reports50,1531 +def read_pnl_report(f):read_pnl_report61,1952 +def pnl_reports():pnl_reports71,2376 +def read_cds_report(f):read_cds_report83,2815 + def drop_zero_count(df):drop_zero_count87,2915 +def read_swaption_report(f):read_swaption_report143,4793 + def drop_zero_count(df):drop_zero_count147,4898 +def cds_reports():cds_reports180,5798 +def monthly_pnl_bycusip(df, strats):monthly_pnl_bycusip193,6209 -markit/.ropeproject/config.py,90 -def set_prefs(prefs):set_prefs5,45 -def project_opened(project):project_opened110,4652 +bbg_index_quotes.py,0 -markit/utils.py,38 -def default_date():default_date4,61 +handle_default.py,400 +def get_recovery(company_id: int, seniority: str, conn):get_recovery5,59 +def affected_indices(company_id: int, seniority: str, conn):affected_indices15,351 +def create_newindices(recordslist, recovery, lastdate, conn):create_newindices30,894 +def update_indexmembers(newids, company_id, seniority, conn):update_indexmembers53,1812 +def update_redcodes(index_type, conn):update_redcodes66,2294 -markit/import_quotes.py,807 -logger = logging.getLogger(__name__)logger12,197 -def convert(x):convert14,235 -def get_index_list(database, workdate):get_index_list20,333 -DOC_CLAUSE_MAPPING14 = {'Full Restructuring': 'MM14',DOC_CLAUSE_MAPPING1429,679 -DOC_CLAUSE_MAPPING = {'Full Restructuring': 'MM',DOC_CLAUSE_MAPPING33,852 -def get_markit_bbg_mapping(database, basketid_list, workdate):get_markit_bbg_mapping37,1013 -def get_bbg_tickers(database, basketid_list, workdate):get_bbg_tickers62,2363 -def get_basketids(database, index_list, workdate):get_basketids70,2698 -def get_current_tickers(database, workdate):get_current_tickers77,2953 -def insert_cds(database, workdate):insert_cds82,3186 -def insert_index(engine, workdate=None):insert_index113,4858 -def insert_tranche(engine, workdate=None):insert_tranche150,7026 +markit_tranche_quotes_csv.py,43 +def convert_float(s):convert_float19,597 -exchange.py,164 -def get_account(email_address):get_account5,108 -def get_msgs(account=None, email_address='ghorel@lmcg.com', count=None, path=['GS', 'Swaptions'],get_msgs13,496 +analytics/index.py,1027 +import pandas as pdpd4,46 +def g(index, spread, exercise_date, pv=None):g17,363 +class CreditIndex(CreditDefaultSwap):CreditIndex58,1659 + def __init__(__init__69,1864 + def from_tradeid(cls, trade_id):from_tradeid143,4561 + def hy_equiv(self):hy_equiv167,5369 + def ref(self):ref178,5699 + def ref(self, val):ref185,5843 + def mark(self, **args):mark191,5974 + def value_date(self, d):value_date210,6737 + def factor(self):factor223,7157 + def version(self):version227,7222 + def cumloss(self):cumloss231,7289 +class ForwardIndex:ForwardIndex235,7343 + def __init__(self, index, forward_date, observer=True):__init__247,7576 + def from_name(from_name260,8071 + def forward_annuity(self):forward_annuity273,8380 + def forward_pv(self):forward_pv277,8463 + def forward_spread(self):forward_spread281,8536 + def ref(self):ref285,8623 + def ref(self, val):ref289,8689 + def __hash__(self):__hash__292,8743 + def _update(self, *args):_update295,8850 -calibrate_tranches.py,1441 -n_int = 500n_int10,147 -n_credit = 100n_credit11,159 - indices = yaml.load(fh)indices15,243 -hy21 = indices['hy21']hy2117,377 -dates = [f[9:19] for f in os.listdir(os.path.join(os.environ['DATA_DIR'], "Backtest")) if "survprob" in f]dates19,447 -Rho = np.zeros((len(dates), 3))Rho21,555 - startdate = datetime.datetime.strptime(d, "%Y-%m-%d")startdate23,617 - ts = YC(startdate)ts24,675 - recov = np.array([float(e) for e in fh], dtype='double', order='F')recov26,796 - SurvProb = np.array([[float(e) for e in line.split(",")] for line in fh], dtype='double', order='F')SurvProb30,1010 - defaultprob = 1 - SurvProbdefaultprob32,1120 - issuerweights = np.ones(100)/100issuerweights33,1151 - rho = 0.4rho35,1189 - Ngrid = 101Ngrid36,1203 - K = np.array([0, 0.15, 0.25, 0.35, 1])K38,1220 - Kmod = adjust_attachments(K, hy21["loss"], hy21["factor"])Kmod40,1264 - quotes = pd.read_csv(os.path.join(os.environ['BASE_DIR'], "Scenarios", "Calibration",quotes41,1327 - quotes = quotes["Mid"]/100quotes43,1491 - dK = np.diff(Kmod)dK44,1522 - quotes = np.cumsum(dK * (1-quotes))quotes45,1545 - sched = creditSchedule(startdate, "5Yr", 0.05, ts, enddate=hy21["maturity"])sched46,1585 - acc = cdsAccrued(startdate, 0.05)acc47,1666 - def aux(rho):aux49,1744 - rho = (l+u)/2.rho56,2035 - u = rhou58,2091 - l = rhol60,2133 +analytics/portfolio.py,1379 +import pandas as pdpd4,109 +import numpy as npnp5,129 +def portf_repr(method):portf_repr11,203 + def f(*args):f12,227 + def percent(x):percent16,305 +class Portfolio:Portfolio47,1160 + def __init__(self, trades, trade_ids=None):__init__48,1177 + def __bool__(self):__bool__59,1604 + def add_trade(self, trades, trade_ids):add_trade62,1662 + def __iter__(self):__iter__66,1783 + def __getitem__(self, trade_id):__getitem__70,1858 + def indices(self):indices79,2113 + def swaptions(self):swaptions83,2221 + def tranches(self):tranches87,2333 + def items(self):items90,2432 + def pnl(self):pnl95,2569 + def pnl_list(self):pnl_list99,2650 + def pv(self):pv103,2733 + def pv_list(self):pv_list107,2812 + def reset_pv(self):reset_pv110,2879 + def value_date(self):value_date115,2973 + def value_date(self, d):value_date119,3055 + def mark(self, **kwargs):mark124,3173 + def shock(self, params=["pnl"], **kwargs):shock131,3341 + def ref(self):ref137,3518 + def ref(self, val):ref144,3699 + def spread(self):spread158,4201 + def spread(self, val):spread165,4394 + def delta(self):delta181,4941 + def gamma(self):gamma190,5203 + def dv01(self):dv01194,5318 + def theta(self):theta198,5401 + def hy_equiv(self):hy_equiv202,5486 + def _todf(self):_todf205,5563 -parse_preqin.py,644 -root = "/home/share/serenitas/Fund Raising/Preqin/Investors/"root6,43 -filelist = [f for f in os.listdir(root) if f.endswith('htm')]filelist7,105 -fh2 = open(os.path.join(root, "investors3.csv"), "w")fh28,167 -csvwriter = csv.writer(fh2)csvwriter9,221 -headers=['filename', 'name', 'contact name', 'job title', 'phone', 'email']headers90,3368 -d = {}d92,3472 -sentinel={}sentinel93,3479 - soup = bs4.BeautifulSoup(fh)soup96,3554 - table =soup.find(id=re.compile('FirmContacts'))table104,3784 - table_rows = table.findAll('tr')table_rows105,3844 - fields = row.findAll('td')fields107,3928 +analytics/scenarios.py,863 +import pandas as pdpd2,12 +import numpy as npnp4,58 +def run_swaption_scenarios(run_swaption_scenarios14,361 +def run_index_scenarios(index, date_range, spread_shock, params=["pnl"]):run_index_scenarios59,1747 +def _aux(portf, curr_vols, params, vs):_aux73,2222 +def MaybePool(nproc):MaybePool80,2442 +def run_portfolio_scenarios_module(run_portfolio_scenarios_module84,2511 +def join_dfs(l_df):join_dfs123,3643 +def run_portfolio_scenarios(portf, date_range, params=["pnl"], **kwargs):run_portfolio_scenarios139,4219 +def run_tranche_scenarios(tranche, spread_range, date_range, corr_map=False):run_tranche_scenarios201,6522 +def run_tranche_scenarios_rolldown(tranche, spread_range, date_range, corr_map=False):run_tranche_scenarios_rolldown264,8858 +def run_curve_scenarios(portf, spread_range, date_range, curve_per):run_curve_scenarios370,13356 -collateral_calc.py,524 -DAILY_DIR = Path(os.environ["DAILY_DIR"])DAILY_DIR10,236 -def download_files(d=None):download_files12,279 -def download_emails():download_emails37,1266 -def sg_collateral(d):sg_collateral47,1656 -def ms_collateral(d):ms_collateral70,2853 -def send_email(account, df_ms, df_sg):send_email83,3330 - d = (pd.Timestamp.today() - BDay()).normalize()d102,4000 - df_ms = ms_collateral(d - BDay())df_ms104,4074 - df_sg = sg_collateral(d)df_sg105,4112 - account = get_account('ghorel@lmcg.com')account106,4141 +analytics/exceptions.py,56 +class MissingDataError(Exception):MissingDataError1,0 -calibrate_swaption.py,503 -serenitas_engine = dbengine('serenitasdb')serenitas_engine11,259 -def get_data(index, series, date=datetime.date.min):get_data13,303 -def get_data_latest():get_data_latest24,936 -def calib(option, ref, strike, pay_bid, pay_offer, rec_bid, rec_offer):calib37,1653 -def MaybePool(nproc):MaybePool59,2366 -def calibrate(index_type=None, series=None, date=None, nproc=4, latest=False):calibrate62,2434 - parser = argparse.ArgumentParser()parser86,3596 - args = parser.parse_args()args92,4027 +analytics/option.py,4328 +import bottleneck as bnbn1,0 +import numpy as npnp5,67 +import pandas as pdpd6,86 +import matplotlib.pyplot as pltplt23,688 +def calib(S0, fp, tilt, w, ctx):calib36,1011 +def ATMstrike(index, exercise_date):ATMstrike40,1092 +class BlackSwaption(ForwardIndex):BlackSwaption60,1622 + def __init__(__init__76,1906 + def __setstate__(self, state):__setstate__91,2427 + def from_tradeid(cls, trade_id, index=None):from_tradeid97,2597 + def mark(self, source_list=[], surface_id=None, **kwargs):mark123,3533 + def value_date(self):value_date164,5123 + def value_date(self, d):value_date168,5210 + def exercise_date(self):exercise_date178,5584 + def exercise_date(self, d):exercise_date182,5673 + def strike(self):strike193,6047 + def strike(self, K):strike200,6213 + def atm_strike(self):atm_strike211,6555 + def moneyness(self):moneyness219,6795 + def direction(self):direction225,6964 + def direction(self, d):direction232,7114 + def intrinsic_value(self):intrinsic_value241,7370 + def __hash__(self):__hash__246,7588 + def pv(self):pv252,7744 + def price(self):price277,8554 + def price(self, p):price281,8666 + def tail_prob(self):tail_prob285,8786 + def pv(self, val):pv297,9293 + def handle(x):handle308,9660 + def reset_pv(self):reset_pv321,9955 + def pnl(self):pnl325,10030 + def delta(self):delta335,10368 + def hy_equiv(self):hy_equiv349,10806 + def T(self):T355,10960 + def gamma(self):gamma362,11137 + def theta(self):theta375,11474 + def vega(self):vega383,11647 + def DV01(self):DV01392,11848 + def breakeven(self):breakeven402,12107 + def shock(self, params, *, spread_shock, vol_surface, vol_shock, **kwargs):shock425,12875 + def __repr__(self):__repr__451,14044 + def __str__(self):__str__488,15623 +class Swaption(BlackSwaption):Swaption492,15709 + def __init__(__init__495,15780 + def __hash__(self):__hash__502,16030 + def pv(self):pv507,16116 + def pv(self, val):pv550,17609 + def handle(x):handle556,17767 + def __setpv_black(self, val):__setpv_black573,18161 + def __setprice_black(self, p):__setprice_black585,18570 +def _get_keys(df, models=["black", "precise"]):_get_keys591,18746 +class QuoteSurface:QuoteSurface603,19167 + def __init__(__init__604,19187 + def list(self, source=None):list635,20461 +class VolSurface(QuoteSurface):VolSurface648,20847 + def __init__(__init__649,20879 + def __getitem__(self, surface_id):__getitem__655,21077 + def vol(self, T, moneyness, surface_id):vol687,22263 + def plot(self, surface_id):plot693,22517 +def _compute_vol(option, strike, mid):_compute_vol709,23088 +def _calibrate_model(_calibrate_model719,23337 +def _calibrate(index, quotes, option_type, **kwargs):_calibrate764,24963 +class ModelBasedVolSurface(VolSurface):ModelBasedVolSurface771,25224 + def __init__(__init__772,25264 + def list(self, source=None, option_type=None):list800,26385 + def __getitem__(self, surface_id):__getitem__808,26696 + def index_ref(self, surface_id):index_ref828,27526 + def plot(self, surface_id):plot833,27682 +class BlackSwaptionVolSurface(ModelBasedVolSurface):BlackSwaptionVolSurface848,28197 +class SwaptionVolSurface(ModelBasedVolSurface):SwaptionVolSurface852,28261 +class SABRVolSurface(ModelBasedVolSurface):SABRVolSurface856,28320 +def _forward_annuity(expiry, index):_forward_annuity861,28398 +class ProbSurface(QuoteSurface):ProbSurface873,28841 + def __init__(__init__874,28874 + def __getitem__(self, surface_id):__getitem__881,29145 + def spline(df):spline923,30908 + def tail_prob(self, T, strike, surface_id):tail_prob938,31487 + def quantile_spread(self, T, prob, surface_id):quantile_spread942,31660 + def prob_calib(x, T, surface_id):prob_calib946,31810 + def quantile_plot(self, surface_id):quantile_plot964,32276 + def plot(self, surface_id):plot981,32853 +class BivariateLinearFunction:BivariateLinearFunction997,33435 + def __init__(self, T, f):__init__1000,33525 + def __call__(self, x, y):__call__1005,33644 +def calib_sabr(x, option, strikes, pv, beta):calib_sabr1017,34000 +def _calibrate_sabr(index, quotes, option_type, beta):_calibrate_sabr1029,34329 -backfill_index.py,335 -serenitasdb = dbconn('serenitasdb')serenitasdb3,76 -series=[18]series7,171 -tenor = ['5yr', '7yr', '10yr']tenor9,222 -index_type ='IG'index_type10,253 - index = "{0}{1}".format(index_type.lower(), s)index14,308 - df = pd.read_excel('/home/share/CorpCDOs/index historical.xlsx', "{0} {1}".format(index, t))df15,363 +analytics/black.py,270 +def d1(F, K, sigma, T):d17,115 +def d2(F, K, sigma, T):d211,211 +def d12(F, K, sigma, T):d1216,322 +def cnd_erf(d):cnd_erf26,533 +def black(F, K, T, sigma, payer=True):black33,753 +def Nx(F, K, sigma, T):Nx42,1044 +def bachelier(F, K, T, sigma):bachelier46,1148 -flask-run.py,57 - mod = importlib.import_module(sys.argv[1])mod8,164 +analytics/credit_default_swap.py,1674 +import numpy as npnp4,41 +import pandas as pdpd5,60 +class CreditDefaultSwap:CreditDefaultSwap20,492 + def __init__(__init__53,1169 + def __hash__(self):__hash__95,2520 + def _getslots(self):_getslots98,2616 + def __getstate__(self):__getstate__105,2863 + def __setstate__(self, state):__setstate__108,2955 + def start_date(self):start_date114,3121 + def end_date(self):end_date118,3194 + def start_date(self, d):start_date122,3272 + def end_date(self, d):end_date128,3483 + def spread(self):spread134,3687 + def direction(self):direction141,3837 + def direction(self, d):direction148,3986 + def _update(self):_update156,4258 + def spread(self, s):spread190,5268 + def flat_hazard(self):flat_hazard198,5482 + def pv(self):pv204,5645 + def pv(self, val):pv208,5734 + def accrued(self):accrued214,5952 + def days_accrued(self):days_accrued218,6076 + def clean_pv(self):clean_pv222,6159 + def price(self):price226,6259 + def price(self, val):price230,6326 + def DV01(self):DV01269,7693 + def theta(self):theta277,7888 + def IRDV01(self):IRDV01288,8336 + def rec_risk(self):rec_risk307,8947 + def jump_to_default(self):jump_to_default320,9310 + def risky_annuity(self):risky_annuity324,9425 + def value_date(self):value_date328,9520 + def value_date(self, d):value_date335,9721 + def reset_pv(self):reset_pv348,10234 + def pnl(self):pnl353,10366 + def notify(self):notify364,10751 + def observe(self, obj):observe368,10835 + def shock(self, params, *, spread_shock, **kwargs):shock371,10896 + def __repr__(self):__repr__382,11380 -rmbs/CRT_data.py,99 -def get_CRT_notional():get_CRT_notional10,159 -def calc_CRT_notional():calc_CRT_notional36,1221 +analytics/tranche_functions.py,1760 +import numpy as npnp1,0 +import pandas as pdpd13,332 +def wrapped_ndpointer(*args, **kwargs):wrapped_ndpointer18,398 + def from_param(cls, obj):from_param21,477 +def GHquad(n):GHquad132,4338 +def stochasticrecov(R, Rtilde, Z, w, rho, porig, pmod):stochasticrecov137,4423 +def fitprob(Z, w, rho, p0):fitprob153,4771 +def shockprob(p, rho, Z, give_log):shockprob161,4962 +def shockseverity(S, rho, Z, p):shockseverity165,5087 +def BCloss_recov_dist(BCloss_recov_dist169,5209 +def BCloss_recov_trunc(BCloss_recov_trunc193,5794 +def lossdistrib_joint(p, pp, w, S, Ngrid=101, defaultflag=False):lossdistrib_joint218,6406 +def lossdistrib_joint_Z(p, pp, w, S, rho, Ngrid=101, defaultflag=False, nZ=500):lossdistrib_joint_Z266,7598 +def joint_default_averagerecov_distrib(p, S, Ngrid=101):joint_default_averagerecov_distrib334,9247 +def adjust_attachments(K, losstodate, factor):adjust_attachments367,10129 +def trancheloss(L, K1, K2):trancheloss375,10334 +def trancherecov(R, K1, K2):trancherecov379,10421 +def tranche_cl(L, R, cs, K1, K2, scaled=False):tranche_cl383,10517 +def tranche_cl_trunc(EL, ER, cs, K1, K2, scaled=False):tranche_cl_trunc401,11063 +def tranche_pl(L, cs, K1, K2, scaled=False):tranche_pl414,11435 +def tranche_pl_trunc(EL, cs, K1, K2, scaled=False):tranche_pl_trunc428,11826 +def tranche_pv(L, R, cs, K1, K2):tranche_pv440,12118 +def credit_schedule(tradedate, tenor, coupon, yc, enddate=None):credit_schedule444,12222 +def cds_accrued(tradedate, coupon):cds_accrued472,13172 +def dist_transform(q):dist_transform489,13704 +def dist_transform2(q):dist_transform2505,14125 +def compute_pv(q, strike):compute_pv520,14528 +def average_recov(p, R, Ngrid):average_recov527,14724 + import numpy as npnp555,15730 -rmbs/marketing.py,118 -def ver_one():ver_one6,87 -def plot_strat():plot_strat29,1253 -def wavg(group, avg_name, weight_name):wavg54,2014 +analytics/sabr.py,269 +import numpy as npnp3,30 +def sabr_lognormal(alpha, rho, nu, F, K, T):sabr_lognormal12,201 +def sabr_normal(alpha, rho, nu, F, K, T):sabr_normal29,710 +def sabr(alpha, beta, rho, nu, F, K, T):sabr63,1656 + def calib(x, option, strikes, pv, beta):calib140,4114 -load_refentity.py,529 -parser = etree.XMLParser(remove_blank_text=True)parser6,100 -def todict(xml, uselist=set()):todict9,183 -def dispatch_parsing(col, uselist):dispatch_parsing27,768 -def insert_refentity(fname):insert_refentity36,1012 -def parse_prospectus(xml):parse_prospectus62,2292 -def insert_refobligation(fname):insert_refobligation65,2379 -def get_date(f):get_date105,4687 - base_dir = Path('/home/serenitas/CorpCDOs/Tranche_data/RED_reports/Deltas')base_dir113,4921 - f = base_dir / download_report(report)[0]f115,5061 +analytics/tranche_basket.py,4566 +import matplotlib.pyplot as pltplt29,815 +import pandas as pdpd30,847 +import numpy as npnp31,867 +class Skew:Skew37,943 + def __init__(self, el: float, skew: CubicSpline):__init__40,977 + def __iter__(self):__iter__44,1082 + def __call__(self, k):__call__48,1157 + def from_desc(from_desc52,1249 + def plot(self, moneyness_space=True):plot101,3248 +class DualCorrTranche:DualCorrTranche119,3879 + def __init__(__init__123,3998 + def maturity(self):maturity174,5753 + def maturity(self, m):maturity178,5840 + def _default_prob(self, epsilon=0.0):_default_prob182,5986 + def __hash__(self):__hash__190,6208 + def aux(v):aux191,6232 + def from_tradeid(cls, trade_id):from_tradeid204,6593 + def value_date(self):value_date238,7683 + def value_date(self, d: pd.Timestamp):value_date242,7771 + def tranche_legs(self, K, rho, epsilon=0.0):tranche_legs260,8437 + def index_pv(self, epsilon=0.0, discounted=True):index_pv296,9783 + def direction(self):direction313,10440 + def direction(self, d):direction320,10589 + def pv(self):pv329,10875 + def clean_pv(self):clean_pv342,11307 + def _pv(self, epsilon=0.0):_pv345,11387 + def spread(self):spread363,11913 + def upfront(self):upfront368,12013 + def price(self):price374,12178 + def upfront(self, upf):upfront379,12299 + def aux(rho):aux380,12327 + def reset_pv(self):reset_pv387,12507 + def singlename_spreads(self):singlename_spreads391,12623 + def pnl(self):pnl414,13373 + def __repr__(self):__repr__426,13787 + def shock(self, params=["pnl"], *, spread_shock, corr_shock, **kwargs):shock453,14877 + def mark(self, **args):mark474,15748 + def jump_to_default(self, skew):jump_to_default528,17715 + def tranche_factor(self):tranche_factor565,19204 + def duration(self):duration573,19393 + def hy_equiv(self):hy_equiv577,19511 + def delta(self):delta589,19837 + def theta(self, method="ATM", skew=None):theta598,20099 + def aux(x, K2, shortened):aux599,20145 + def find_upper_bound(k, shortened):find_upper_bound609,20469 + def expected_loss(self, discounted=True, shortened=0):expected_loss642,21616 + def expected_loss_trunc(self, K, rho=None, shortened=0):expected_loss_trunc657,22163 + def gamma(self):gamma679,22802 + def _greek_calc(self):_greek_calc694,23303 +class TrancheBasket(BasketIndex):TrancheBasket706,23699 + def __init__(__init__709,23807 + def _get_tranche_quotes(self, value_date):_get_tranche_quotes737,24857 + def value_date(self, d: pd.Timestamp):value_date786,26975 + def skew(self) -> Skew:skew799,27543 + def tranche_factors(self):tranche_factors802,27626 + def _get_quotes(self, spread=None):_get_quotes805,27726 + def default_prob(self):default_prob831,28604 + def tranche_legs(self, K, rho, complement=False, shortened=0, zero_recovery=False):tranche_legs837,28834 + def jump_to_default(self, zero_recovery=False):jump_to_default869,30140 + def tranche_pvs(tranche_pvs911,31934 + def index_pv(self, discounted=True, shortened=0, zero_recovery=False):index_pv938,32802 + def expected_loss(self, discounted=True, shortened=0):expected_loss962,33732 + def expected_loss_trunc(self, K, rho=None, shortened=0):expected_loss_trunc976,34205 + def probability_trunc(self, K, rho=None, shortened=0):probability_trunc990,34774 + def tranche_durations(self, complement=False, zero_recovery=False):tranche_durations1007,35331 + def tranche_EL(self, complement=False, zero_recovery=False):tranche_EL1016,35693 + def tranche_spreads(self, complement=False, zero_recovery=False):tranche_spreads1024,35999 + def _row_names(self):_row_names1030,36337 + def tranche_thetas(tranche_thetas1035,36529 + def tranche_fwd_deltas(self, complement=False, shortened=4, method="ATM"):tranche_fwd_deltas1050,37149 + def tranche_deltas(self, complement=False, zero_recovery=False):tranche_deltas1065,37724 + def tranche_corr01(self, eps=0.01, complement=False, zero_recovery=False):tranche_corr011085,38670 + def build_skew(self, skew_type="bottomup"):build_skew1100,39160 + def aux(rho, obj, K, quote, spread, complement):aux1104,39303 + def map_skew(self, index2, method="ATM", shortened=0):map_skew1151,40880 + def aux(x, index1, el1, index2, el2, K2, shortened):aux1152,40939 + def aux2(x, index1, index2, K2, shortened):aux21165,41424 + def find_upper_bound(*args):find_upper_bound1174,41788 -markit_tranche_quotes.py,726 -params = {"username": "serenitasreports",params8,88 -r = requests.get("https://quotes.markit.com/reports/runReport",r14,299 - params=params)params15,363 -f = io.StringIO(r.text)f17,396 -index_mapping = {'ITRAXX-Europe': 'EU',index_mapping21,478 -def get_latest_quote_id(db):get_latest_quote_id31,982 -def convert_float(s):convert_float37,1157 -serenitasdb = dbconn('serenitasdb')serenitasdb40,1215 -runningdict1 = {0: 500, 3:100, 7:100, 15: 25}runningdict142,1252 -runningdict2 = {0: 500, 3:500, 7:500, 10:100, 15:100, 30:100}runningdict243,1298 -markit_id = get_latest_quote_id(serenitasdb)markit_id44,1360 -headers = [h.lower() for h in next(f).split(",")]headers46,1406 -count = 0count47,1456 +analytics/basket_index.py,1503 +import numpy as npnp12,390 +import pandas as pdpd13,409 +def make_index(t, d, args):make_index21,569 +class BasketIndex(CreditIndex):BasketIndex28,721 + def __init__(__init__36,894 + def __reduce__(self):__reduce__109,3672 + def __hash__(self):__hash__114,3831 + def aux(v):aux115,3855 + def _update_factor(self, d):_update_factor128,4243 + def factor(self):factor137,4531 + def cumloss(self):cumloss141,4596 + def version(self):version145,4663 + def _get_quotes(self, *args):_get_quotes148,4716 + def value_date(self, d: pd.Timestamp):value_date161,5197 + def recovery_rates(self):recovery_rates173,5646 + def pv(self, maturity=None, epsilon=0.0, coupon=None):pv178,5850 + def pv_vec(self):pv_vec204,6690 + def coupon_leg(self, maturity=None):coupon_leg209,6829 + def spread(self, maturity=None):spread212,6934 + def protection_leg(self, maturity=None):protection_leg215,7049 + def duration(self, maturity=None):duration230,7599 + def theta(self, maturity=None, coupon=None, theta_date=None):theta245,8125 + def coupon(self, maturity=None, assume_flat=True):coupon286,9544 + def tweak(self, *args):tweak298,10004 + def _snacpv(self, spread, coupon, recov, maturity):_snacpv338,11384 + def _snacspread(self, coupon, recov, maturity):_snacspread352,11737 +class MarkitBasketIndex(BasketIndex):MarkitBasketIndex367,12103 + def __init__(__init__368,12141 + def _get_quotes(self):_get_quotes386,12765 -xmltotab.py,213 -ns = '{urn:schemas-microsoft-com:office:spreadsheet}'ns4,35 -doc = etree.parse('/home/share/guillaume/grid1_1cz1rlvt.xml')doc6,90 -tree = doc.getroot()tree7,152 - csvwriter = csv.writer(fh)csvwriter10,210 +analytics/index_data.py,812 +import numpy as npnp3,74 +import pandas as pdpd12,295 +def insert_quotes():insert_quotes15,317 +def get_index_quotes(get_index_quotes57,1985 + def make_str(key, val):make_str75,2430 + def make_params(args):make_params92,2983 +def index_returns(index_returns118,3751 +def get_singlenames_quotes(indexname, date, tenors):get_singlenames_quotes172,5743 +def build_curve(r, tenors):build_curve179,5940 +def build_curves(quotes, args):build_curves208,6840 +def build_curves_dist(quotes, args, workers=4):build_curves_dist212,6942 +def _get_singlenames_curves(index_type, series, trade_date, tenors):_get_singlenames_curves221,7249 +def get_singlenames_curves(get_singlenames_curves229,7513 +def get_tranche_quotes(index_type, series, tenor, date=datetime.date.today()):get_tranche_quotes240,7882 -task_runner.py,75 -def run():run9,172 - logger = logging.getLogger('intex')logger32,934 +analytics/curve_trades.py,1616 +import pandas as pdpd15,516 +import statsmodels.formula.api as smfsmf17,548 +import numpy as npnp18,586 +import matplotlib.pyplot as pltplt19,605 +def curve_spread_diff(curve_spread_diff22,639 +def spreads_diff_table(spreads_diff):spreads_diff_table43,1359 + def current(s):current44,1397 + def zscore(s):zscore47,1443 +def theta_matrix_by_series(index="IG", rolling=6):theta_matrix_by_series55,1665 +def ratio_within_series(index="IG", rolling=6, param="duration"):ratio_within_series69,2210 +def on_the_run_theta(index="IG", rolling=6):on_the_run_theta83,2746 +def curve_returns(index="IG", rolling=6, years=3):curve_returns93,3107 +def curve_returns_stats(strategies_return):curve_returns_stats120,3991 + def sharpe(df, period="daily"):sharpe129,4207 +def cross_series_curve(index="IG", rolling=6):cross_series_curve144,4766 +def forward_loss(index="IG"):forward_loss165,5568 +def curve_model(tenor_1="5yr", tenor_2="10yr"):curve_model190,6492 +def curve_model_results(df, model):curve_model_results212,7129 +def spread_fin_crisis(index="IG"):spread_fin_crisis240,8052 +def forward_spread(forward_spread266,8943 +def spot_forward(index="IG", series=None, tenors=["3yr", "5yr", "7yr", "10yr"]):spot_forward283,9481 +def curve_pos(value_date, index_type="IG"):curve_pos312,10445 +def curve_shape(value_date, index="IG", percentile=0.95, spread=None):curve_shape345,11342 +def plot_curve_shape(date):plot_curve_shape379,12635 +def pos_pnl_abs(portf, value_date, index="IG", rolling=6, years=3):pos_pnl_abs401,13293 +def curve_scen_table(portf, shock=10):curve_scen_table441,14647 + +analytics/.ropeproject/config.py,90 +def set_prefs(prefs):set_prefs5,45 +def project_opened(project):project_opened120,4706 + +analytics/ir_swaption.py,407 +class IRSwaption:IRSwaption12,410 + def __init__(__init__15,476 + def direction(self):direction39,1214 + def direction(self, d):direction46,1364 + def pv(self):pv55,1620 + def sigma(self):sigma59,1705 + def sigma(self, s):sigma63,1778 + def from_tradeid(trade_id):from_tradeid66,1833 + def value_date(self):value_date85,2521 + def value_date(self, d):value_date89,2636 + +analytics/cms_spread.py,1335 +import matplotlib.pyplot as pltplt3,30 +import numpy as npnp4,62 +import pandas as pdpd5,81 +def h_call(z, K, S1, S2, mu_x, mu_y, sigma_x, sigma_y, rho):h_call65,1736 +def h_put(z, K, S1, S2, mu_x, mu_y, sigma_x, sigma_y, rho):h_put95,2444 +def _h1(n, args):_h1111,2935 +def get_fixings(conn, tenor1, tenor2, fixing_date=None):get_fixings139,3547 +def build_spread_index(tenor1, tenor2):build_spread_index166,4454 +def get_swaption_vol_data(get_swaption_vol_data174,4755 +def get_swaption_vol_surface(date, vol_type):get_swaption_vol_surface196,5473 +def get_swaption_vol_matrix(date, data, vol_type=VolatilityType.ShiftedLognormal):get_swaption_vol_matrix202,5739 +def quantlib_model(quantlib_model224,6376 +def plot_surf(surf, tenors):plot_surf269,7924 +def globeop_model(globeop_model276,8104 +def get_cms_coupons(trade_date, notional, option_tenor, spread_index, fixing_days=2):get_cms_coupons297,9151 +def get_params(cms_beta, cms_gamma, atm_vol):get_params325,10095 +class CmsSpread:CmsSpread346,10924 + def __init__(__init__347,10941 + def from_tradeid(trade_id):from_tradeid414,13269 + def corr(self):corr447,14277 + def corr(self, val):corr451,14347 + def value_date(self):value_date455,14418 + def value_date(self, d: pd.Timestamp):value_date459,14500 + def pv(self):pv470,14940 + +analytics/__init__.py,171 +import pandas as pdpd21,491 +def on_the_run(index, value_date=datetime.date.today()):on_the_run25,529 +def init_ontr(value_date=datetime.date.today()):init_ontr34,791 + +analytics/utils.py,737 +import numpy as npnp2,16 +import pandas as pdpd3,35 +def GHquad(n):GHquad40,952 +def next_twentieth(d):next_twentieth46,1080 +def third_wednesday(d):third_wednesday56,1285 +def next_third_wed(d):next_third_wed63,1491 +def roll_date(d, tenor, nd_array=False):roll_date71,1644 + def kwargs(t):kwargs75,1774 +def build_table(rows, format_strings, row_format):build_table121,3455 + def apply_format(row, format_string):apply_format122,3506 +def memoize(f=None, *, hasher=lambda args: (hash(args),)):memoize141,4064 + def cached_f(*args, **kwargs):cached_f146,4203 +def to_TDate(arr: np.ndarray):to_TDate159,4496 +def get_external_nav(engine, trade_id, value_date=None, trade_type="swaption"):get_external_nav164,4620 + +.credentials/guillaume.horel@serenitascapital.com.json,2342 +{"access_token": "ya29.Gl2ABp1nxBLEB-rKr6neCpHhDJvbxwXaYJ608mfORpdQmcPmtVhanAV5ezSh15c8AgRb7vNg0access_token1,0 +{"access_token": "ya29.Gl2ABp1nxBLEB-rKr6neCpHhDJvbxwXaYJ608mfORpdQmcPmtVhanAV5ezSh15c8AgRb7vNg0client_id1,0 +{"access_token": "ya29.Gl2ABp1nxBLEB-rKr6neCpHhDJvbxwXaYJ608mfORpdQmcPmtVhanAV5ezSh15c8AgRb7vNg0client_secret1,0 +{"access_token": "ya29.Gl2ABp1nxBLEB-rKr6neCpHhDJvbxwXaYJ608mfORpdQmcPmtVhanAV5ezSh15c8AgRb7vNg0refresh_token1,0 +{"access_token": "ya29.Gl2ABp1nxBLEB-rKr6neCpHhDJvbxwXaYJ608mfORpdQmcPmtVhanAV5ezSh15c8AgRb7vNg0token_expiry1,0 +{"access_token": "ya29.Gl2ABp1nxBLEB-rKr6neCpHhDJvbxwXaYJ608mfORpdQmcPmtVhanAV5ezSh15c8AgRb7vNg0token_uri1,0 +{"access_token": "ya29.Gl2ABp1nxBLEB-rKr6neCpHhDJvbxwXaYJ608mfORpdQmcPmtVhanAV5ezSh15c8AgRb7vNg0user_agent1,0 +{"access_token": "ya29.Gl2ABp1nxBLEB-rKr6neCpHhDJvbxwXaYJ608mfORpdQmcPmtVhanAV5ezSh15c8AgRb7vNg0revoke_uri1,0 +{"access_token": "ya29.Gl2ABp1nxBLEB-rKr6neCpHhDJvbxwXaYJ608mfORpdQmcPmtVhanAV5ezSh15c8AgRb7vNg0id_token1,0 +{"access_token": "ya29.Gl2ABp1nxBLEB-rKr6neCpHhDJvbxwXaYJ608mfORpdQmcPmtVhanAV5ezSh15c8AgRb7vNg0id_token_jwt1,0 +{"access_token": "ya29.Gl2ABp1nxBLEB-rKr6neCpHhDJvbxwXaYJ608mfORpdQmcPmtVhanAV5ezSh15c8AgRb7vNg0access_token1,0 +{"access_token": "ya29.Gl2ABp1nxBLEB-rKr6neCpHhDJvbxwXaYJ608mfORpdQmcPmtVhanAV5ezSh15c8AgRb7vNg0expires_in1,0 +{"access_token": "ya29.Gl2ABp1nxBLEB-rKr6neCpHhDJvbxwXaYJ608mfORpdQmcPmtVhanAV5ezSh15c8AgRb7vNg0scope1,0 +{"access_token": "ya29.Gl2ABp1nxBLEB-rKr6neCpHhDJvbxwXaYJ608mfORpdQmcPmtVhanAV5ezSh15c8AgRb7vNg0token_type1,0 +{"access_token": "ya29.Gl2ABp1nxBLEB-rKr6neCpHhDJvbxwXaYJ608mfORpdQmcPmtVhanAV5ezSh15c8AgRb7vNg0token_response1,0 +{"access_token": "ya29.Gl2ABp1nxBLEB-rKr6neCpHhDJvbxwXaYJ608mfORpdQmcPmtVhanAV5ezSh15c8AgRb7vNg001,0 +{"access_token": "ya29.Gl2ABp1nxBLEB-rKr6neCpHhDJvbxwXaYJ608mfORpdQmcPmtVhanAV5ezSh15c8AgRb7vNg0scopes1,0 +{"access_token": "ya29.Gl2ABp1nxBLEB-rKr6neCpHhDJvbxwXaYJ608mfORpdQmcPmtVhanAV5ezSh15c8AgRb7vNg0token_info_uri1,0 +{"access_token": "ya29.Gl2ABp1nxBLEB-rKr6neCpHhDJvbxwXaYJ608mfORpdQmcPmtVhanAV5ezSh15c8AgRb7vNg0invalid1,0 +{"access_token": "ya29.Gl2ABp1nxBLEB-rKr6neCpHhDJvbxwXaYJ608mfORpdQmcPmtVhanAV5ezSh15c8AgRb7vNg0_class1,0 +{"access_token": "ya29.Gl2ABp1nxBLEB-rKr6neCpHhDJvbxwXaYJ608mfORpdQmcPmtVhanAV5ezSh15c8AgRb7vNg0_module1,0 + +.credentials/ghorel@lmcg.com.json,94 + "password": "LMCG2019ggh",password2,2 + "username": "LEEMUNDER\\ghorel"username3,33 + +debug_forward_price.py,0 + +bespoke_utils.py,611 +import pandas as pdpd5,160 +def insert_bbg_tickers(conn: connection, tickers: List[str]) -> Dict[str, Tuple[str, str]]:insert_bbg_tickers8,182 +def insert_bbg_markit_mapping(conn: connection, d: Dict[str, Tuple[str, str]], df: pd.DataFrame)insert_bbg_markit_mapping48,1795 +def backpopulate_short_codes(conn: connection):backpopulate_short_codes60,2385 +def get_bbg_ids(conn: connection, df: pd.DataFrame,get_bbg_ids80,3332 +def get_basketid(conn: connection, name: str) -> Tuple[int, int]:get_basketid94,4090 +def add_basket_constituents(conn: connection, basketid: int,add_basket_constituents106,4558 + +download_markit_quotes.py,74 +from selenium.webdriver.support import expected_conditions as ECEC6,247 + +process_queue.py,976 +import task_server.config as configconfig9,110 +def get_effective_date(d, swaption_type):get_effective_date291,6943 +def get_trades(q, trade_type="bond", fund="SERCGMAST"):get_trades299,7214 +def rename_keys(d, mapping):rename_keys319,7916 +def build_termination(build_termination326,8098 +def build_line(obj, trade_type="bond"):build_line452,12102 +def get_bbg_data(get_bbg_data632,19360 +def bond_trade_process(conn, session, trade):bond_trade_process743,22752 +def send_email(trade):send_email765,23637 +def is_tranche_trade(trade):is_tranche_trade774,23867 +def cds_trade_process(conn, session, trade):cds_trade_process778,23963 +def generate_csv(l, trade_type="bond", fund="SERCGMAST"):generate_csv823,25362 +def get_filepath(get_filepath837,25758 +def upload_file(file_path: pathlib.Path) -> None:upload_file864,26493 +def write_buffer(write_buffer875,26800 +def email_subject(trade):email_subject886,27035 +def print_trade(trade):print_trade895,27240 + +bbg_newids.py,77 +import pandas as pdpd3,116 +import numpy as npnp4,136 +def f(s):f28,1065 + +futures.py,126 +def nextIMMDates(startdate, length = 8):nextIMMDates14,270 +def QLnextIMMCodes(startdate, length = 8):QLnextIMMCodes33,932 + +task_runner.py,22 +def run():run10,179 tasks.py,356 def build_portfolios(workdate, dealname, reinvflag):build_portfolios8,124 @@ -1065,1381 +1164,886 @@ class Rpc(object):Rpc22,818 def __call__(self):__call__30,1025 def from_json(cls, s):from_json34,1107 -graphics.py,227 -def shiftedColorMap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'):shiftedColorMap5,78 -def plot_time_color_map(df, spread_shock, attr="pnl", path=".", color_map=cm.RdYlGn, index='IG'):plot_time_color_map57,1854 +test_dispertion.py,0 -adj_index_price.py,639 -index='HY'index4,86 -series = [9]series6,138 -engine = create_engine('postgresql://serenitas_user@debian/serenitasdb')engine9,206 -metadata = MetaData(bind=engine)metadata10,279 -index_quotes= Table('index_quotes', metadata, autoload=True)index_quotes11,312 - "where index=%s and series=%s", engine, params = (index, s),factors15,492 - "where index=%s and series=%s and tenor=%s",df21,909 - r = factors.ix[i].indexfactor/factors.ix[i+1].indexfactorr28,1248 - stmt = index_quotes.update().where((index_quotes.c.date==bindparam('b_date')) &stmt34,1562 +test_igoption.py,0 -intex/intex_scenarios.py,1343 -logger = logging.getLogger(__name__)logger16,196 -pattern1 = re.compile("REINVEST\[\w+::REINV_TBA(\d)\]\[DEAL,(\d+)\]=.*$")pattern118,234 -pattern2 = re.compile("(STANDARD_VAR\[)\w+(::#REINV_END,\d+\]=)(\d.*$)")pattern220,325 -pattern3 = re.compile("STANDARD_VAR\[\w+::#PRICE100_TBA(\d),(\d+)\]=")pattern322,414 -pattern5 = re.compile("STANDARD_VAR\[\w+::#REINVPCT_TBA(\d),(\d+)\]=")pattern523,485 -pattern7 = re.compile("KINGS3")pattern724,556 -pattern8 = re.compile("(#COLLATREINV_REINV_PCT_EXT\[)\w+(::\*\]\[DEAL,\d+\])=100")pattern825,588 -pattern9 = re.compile("(?P<a>SEVERITY\[\w+,\d+\]=)mkt\(70\)")pattern926,671 -global_reinvfloatpercentage = 84global_reinvfloatpercentage29,785 -global_reinvfixedpercentage = 16global_reinvfixedpercentage30,818 -def get_reinv_assets(conn, dealname, workdate):get_reinv_assets32,852 -def get_recovery(conn, dealname, workdate, defaultrecovery=50):get_recovery42,1205 -def get_reinvenddate(conn, dealname, workdate):get_reinvenddate58,1868 -def generate_scenarios(workdate, dealname, conn):generate_scenarios69,2258 - workdate = sys.argv[1]workdate231,10580 - workdate = str(datetime.date.today())workdate233,10621 - dealnames = sys.argv[2:]dealnames235,10693 - dealnames = [d.split(".")[0] for d indealnames237,10736 - ET = dbconn('etdb')ET241,10981 +risk/tranches.py,177 +def get_tranche_portfolio(date, conn, by_strat=False, fund="SERCGMAST"):get_tranche_portfolio7,104 +def insert_tranche_portfolio(portf, conn):insert_tranche_portfolio52,1644 -intex/__init__.py,0 +risk/swaptions.py,172 +def get_swaption_portfolio(date, conn, **kwargs):get_swaption_portfolio9,139 +def insert_swaption_portfolio(portf, conn, overwrite=True):insert_swaption_portfolio30,886 -intex/load_indicative.py,649 -logger = logging.getLogger(__name__)logger12,202 -def convertToNone(s):convertToNone14,240 -def insert_new_cusip(conn, line):insert_new_cusip17,310 -def upload_cusip_data(conn, filename):upload_cusip_data38,1327 -def upload_deal_data(conn, filename):upload_deal_data100,4288 - workdate = sys.argv[1]workdate183,8568 - workdate = str(datetime.date.today())workdate185,8609 - files = [os.path.join(os.environ['DATA_DIR'], "Indicative_" + workdate, f) for f infiles186,8655 - cusip_files = [f for f in files if "TrInfo" in f]cusip_files188,8832 - deal_files = [f for f in files if "TrInfo" not in f]deal_files189,8886 +risk/bonds.py,518 +import pandas as pdpd1,0 +import numpy as npnp2,20 +class AssetClass(Enum):AssetClass10,129 +def get_df(date, engine, *, zero_factor=False):get_df17,228 +def subprime_risk(pos_date, conn, engine, model_date=None):subprime_risk85,2935 +def insert_subprime_risk(df, conn):insert_subprime_risk158,5440 +def get_portfolio(date, conn, asset_class: AssetClass, fund="SERCGMAST"):get_portfolio206,6510 +def crt_risk(date, dawn_conn, engine):crt_risk224,7192 +def clo_risk(date, dawn_conn, et_conn):clo_risk247,7886 -intex/__main__.py,150 -logger = logging.getLogger('intex')logger6,110 - workdate = sys.argv[1]workdate10,212 - workdate = str(datetime.date.today())workdate12,245 +risk/__main__.py,28 +import pandas as pdpd2,16 -intex/.ropeproject/config.py,90 -def set_prefs(prefs):set_prefs5,45 -def project_opened(project):project_opened110,4652 +risk/indices.py,215 +import pandas as pdpd2,16 +def get_index_portfolio(get_index_portfolio11,266 +def VaR(VaR44,1089 +def insert_curve_risk(d: datetime.date, conn: connection, strategies=("SER_IGCURVE",)):insert_curve_risk90,2698 -intex/load_intex_collateral.py,249 -logger = logging.getLogger(__name__)logger12,237 -fields = ['Asset Name', 'Issuer', 'Contributed Balance', 'Asset Maturity Date',fields14,275 -def upload_data(conn, workdate):upload_data22,809 -def intex_data(conn, workdate):intex_data142,7121 +risk/__init__.py,0 -intex/common.py,53 -def sanitize_float(intex_float):sanitize_float3,11 +dtcc_sdr.py,698 +import pandas as pdpd3,26 +def download_credit_slices(d: datetime.date) -> None:download_credit_slices15,288 +def download_cumulative_credit(d: datetime.date) -> None:download_cumulative_credit25,667 +def load_data():load_data34,997 +def apply_corrections(conn: connection, df):apply_corrections69,2031 +def process_option_data(conn: connection, df):process_option_data81,2381 +def process_tranche_data(df):process_tranche_data127,4051 +def map_tranche(df):map_tranche134,4271 +def insert_correction(conn: connection, dissemination_id: int, **kwargs) -> None:insert_correction187,6305 +def get_correction(conn: connection, dissemination_id: int) -> Dict[str, Any]:get_correction196,6571 -analytics/__init__.py,0 +optim_alloc.py,404 +import numpy as npnp2,13 +from matplotlib import pyplot as pltplt4,44 +def cor2cov(Rho, vol):cor2cov7,106 +def rho(sigma, delta, volF):rho10,175 +def resid_vol(rho, delta, volF):resid_vol14,329 +def var(rho, delta, volF):var18,462 +def compute_allocation(rho_clo = 0.9, rho_cso=0.6, rho_subprime=0.2,compute_allocation22,596 +def plot_allocation(W, fund_return, fund_vol):plot_allocation60,2146 -analytics/db.py,47 -_engine = dbengine('serenitasdb')_engine2,32 +.ipynb_checkpoints/backfill_cds-checkpoint.py,31 +def convert(x):convert10,156 -analytics/option.py,4190 -def calib(S0, fp, exercise_date, exercise_date_settle,calib36,938 -def memoize(f):memoize44,1269 - def cached_f(*args, **kwargs):cached_f46,1299 -def ATMstrike(index, exercise_date):ATMstrike57,1582 -class BlackSwaption(ForwardIndex):BlackSwaption76,2105 - __slots__ = ['_forward_yc', '_T', '_G', '_strike', 'option_type',__slots__78,2165 - def __init__(self, index, exercise_date, strike, option_type="payer",__init__81,2304 - def __setstate__(self, state):__setstate__94,2793 - def from_tradeid(cls, trade_id, index=None):from_tradeid100,2963 - def exercise_date(self):exercise_date117,3770 - def exercise_date(self, d):exercise_date121,3859 - def strike(self):strike132,4311 - def strike(self, K):strike139,4477 - def atm_strike(self):atm_strike150,4914 - def moneyness(self):moneyness158,5154 - def direction(self):direction163,5333 - def direction(self, d):direction170,5482 - def intrinsic_value(self):intrinsic_value179,5738 - def __hash__(self):__hash__184,5956 - def pv(self):pv189,6144 - def tail_prob(self):tail_prob203,6690 - def pv(self, val):pv216,7239 - def handle(x):handle226,7616 - def reset_pv(self):reset_pv238,7910 - def pnl(self):pnl242,7985 - def delta(self):delta252,8321 - def T(self):T267,8803 - def gamma(self):gamma274,8978 - def theta(self):theta287,9315 - def vega(self):vega295,9486 - def DV01(self):DV01304,9687 - def breakeven(self):breakeven314,9946 - def __repr__(self):__repr__329,10544 - def __str__(self):__str__357,12167 -class Swaption(BlackSwaption):Swaption360,12252 - __slots__ = ["_cache", "_Z", "_w"]__slots__361,12283 - def __init__(self, index, exercise_date, strike, option_type="payer",__init__362,12322 - def __hash__(self):__hash__368,12575 - def pv(self):pv373,12661 - def pv(self, val):pv407,14255 - def handle(x):handle411,14353 - def __setpv_black(self, val):__setpv_black427,14746 - pv_black = property(None, __setpv_black)pv_black437,15127 -def _get_keys(df, models=["black", "precise"]):_get_keys439,15173 -class QuoteSurface():QuoteSurface450,15641 - def __init__(self, index_type, series, tenor='5yr', trade_date=datetime.date.today()):__init__451,15663 - def list(self, source=None):list473,16855 -class VolSurface(QuoteSurface):VolSurface483,17272 - def __init__(self, index_type, series, tenor='5yr', trade_date=datetime.date.today()):__init__484,17304 - def __getitem__(self, surface_id):__getitem__488,17488 - def vol(self, T, moneyness, surface_id):vol502,18293 - def plot(self, surface_id):plot506,18448 -def _compute_vol(option, strike, mid):_compute_vol521,18985 -def _calibrate(index, quotes, option_model, option_type):_calibrate530,19233 -class ModelBasedVolSurface(VolSurface):ModelBasedVolSurface548,19951 - def __init__(self, index_type, series, tenor='5yr', trade_date=datetime.date.today()):__init__549,19991 - def list(self, source=None, option_type=None):list561,20645 - def __getitem__(self, surface_id):__getitem__570,20992 - def plot(self, surface_id):plot586,21798 -class BlackSwaptionVolSurface(ModelBasedVolSurface):BlackSwaptionVolSurface599,22337 -class SwaptionVolSurface(ModelBasedVolSurface):SwaptionVolSurface602,22400 -def _forward_annuity(expiry, index):_forward_annuity606,22481 -class ProbSurface(QuoteSurface):ProbSurface616,22934 - def __init__(self, index_type, series, tenor='5yr', trade_date=datetime.date.today()):__init__618,22968 - def __getitem__(self, surface_id):__getitem__623,23229 - def tail_prob(self, T, strike, surface_id):tail_prob658,25280 - def plot(self, surface_id):plot662,25443 -class MyInterp:MyInterp678,26047 - def __init__(self, T, f):__init__679,26063 - def __call__(self, x, y):__call__684,26170 -def calib_sabr(x, option, strikes, pv, beta):calib_sabr693,26486 -class SABRVolSurface(VolSurface):SABRVolSurface704,26814 - def __init__(self, index_type, series, tenor='5yr',__init__705,26848 - def list(self, source=None, option_type=None):list714,27226 - def __getitem__(self, surface_id):__getitem__723,27544 +position.py,1020 +import numpy as npnp3,80 +import pandas as pdpd4,99 +def get_list(get_list14,275 +def get_list_range(engine, begin, end, asset_class=None):get_list_range44,1207 +def backpopulate_marks(begin_str="2015-01-15", end_str="2015-07-15"):backpopulate_marks65,1956 +def update_securities(engine, session, workdate):update_securities93,3340 +def init_fx(session, engine, startdate):init_fx120,4354 +def update_fx(conn, session, currencies):update_fx131,4814 +def init_swap_rates(init_swap_rates150,5474 +def init_swaption_vol(init_swaption_vol173,6206 +def split_tenor_expiry(ticker, vol_type="N"):split_tenor_expiry188,6636 +def insert_swaption_vol(data, conn, source, vol_type="N"):insert_swaption_vol199,6952 +def update_swaption_vol(update_swaption_vol224,7946 +def update_swap_rates(update_swap_rates269,9558 +def update_cash_rates(conn, session, start_date=None):update_cash_rates286,10181 +def populate_cashflow_history(engine, session, workdate=None, fund="SERCGMAST"):populate_cashflow_history312,11097 -analytics/portfolio.py,1022 -serenitasdb = dbengine('serenitasdb')serenitasdb8,174 -def portf_repr(method):portf_repr10,213 - def f(*args):f11,237 -class Portfolio:Portfolio31,1073 - def __init__(self, trades):__init__32,1090 - def pnl(self):pnl47,1791 - def pnl_list(self):pnl_list51,1872 - def pv(self):pv55,1955 - def pv_list(self):pv_list59,2034 - def reset_pv(self):reset_pv62,2101 - def trade_date(self):trade_date67,2195 - def trade_date(self, d):trade_date71,2277 - def mark(self, source_list=[], option_type=None, model="black", surface_id=None):mark80,2570 - def ref(self):ref106,3886 - def ref(self, val):ref113,4067 - def spread(self):spread127,4565 - def spread(self, val):spread134,4758 - def delta(self):delta148,5271 - def gamma(self):gamma155,5512 - def dv01(self):dv01159,5627 - def theta(self):theta163,5710 - def _todf(self):_todf166,5781 - __repr__ = portf_repr('string')__repr__185,6696 - _repr_html_ = portf_repr('html')_repr_html_187,6733 +cds_curve.py,122 +import pandas as pdpd5,142 +def all_curves_pv(all_curves_pv10,193 +def calibrate_portfolio(calibrate_portfolio35,1141 -analytics/black.py,268 -def d1(F, K, sigma, T):d16,114 -def d2(F, K, sigma, T):d29,207 -def d12(F, K, sigma, T):d1213,316 -def cnd_erf(d):cnd_erf22,524 -def black(F, K, T, sigma, payer=True):black27,684 -def Nx(F, K, sigma, T):Nx35,968 -def bachelier(F, K, T, sigma):bachelier38,1065 +murano.py,187 +import pandas as pdpd1,0 +def generate_table(df):generate_table64,2976 +def list_placeholders(df):list_placeholders99,4294 +def nat_to_null(d, _NULL=AsIs('NULL'),nat_to_null118,4962 -analytics/sabr.py,899 -def sabr_lognormal(alpha, rho, nu, F, K, T):sabr_lognormal7,178 -def sabr_normal(alpha, rho, nu, F, K, T):sabr_normal19,653 -def sabr(alpha, beta, rho, nu, F, K, T):sabr37,1399 - underlying = Index.from_name("IG", 28, "5yr")underlying64,2521 - exercise_date = datetime.date(2017, 9, 20)exercise_date66,2602 - option = BlackSwaption(underlying, exercise_date, 70)option67,2650 - strikes = np.array([50, 55, 57.5, 60, 62.5, 65, 67.5, 70, 75, 80, 85])strikes69,2711 - pvs = np.array([44.1, 25.6, 18.9, 14, 10.5, 8.1, 6.4, 5, 3.3, 2.2, 1.5]) * 1e-4pvs70,2787 - strikes = np.array([50, 55, 57.5, 60, 62.5, 65, 67.5, 70, 75, 80, 85, 90, 95, 100])strikes72,2874 - pvs = np.array([53.65, 37.75, 31.55, 26.45, 22.25, 18.85, 16.15, 13.95, 10.55,pvs73,2963 - def calib(x, option, strikes, pv, beta):calib76,3108 - prog = least_squares(calib, (0.3, 0.5, 0.3),prog87,3469 +script_calibrate_tranches.py,26 +import numpy as npnp1,0 -analytics/.ropeproject/config.py,90 -def set_prefs(prefs):set_prefs5,45 -def project_opened(project):project_opened110,4652 +dates.py,380 +import pandas as pdpd2,16 + from dateutil.parser import parse as isoparseisoparse9,157 +def imm_dates(start_date, end_date):imm_dates19,538 +def previous_twentieth(d):previous_twentieth30,886 +def imm_date(d):imm_date40,1100 +def days_accrued(tradedate):days_accrued49,1306 +def isleapyear(date):isleapyear62,1766 +def yearfrac(date1, date2, daycount):yearfrac66,1873 -analytics/tranche_functions.py,1895 -def wrapped_ndpointer(*args, **kwargs):wrapped_ndpointer11,367 - def from_param(cls, obj):from_param13,445 -libloss = np.ctypeslib.load_library("lossdistrib", os.path.join(libloss19,640 -def GHquad(n):GHquad112,4022 -def stochasticrecov(R, Rtilde, Z, w, rho, porig, pmod):stochasticrecov116,4102 -def fitprob(Z, w, rho, p0):fitprob122,4398 -def BCloss_recov_dist(defaultprob, issuerweights, recov, rho, Z, w, Ngrid=101, defaultflag=False):BCloss_recov_dist127,4574 -def BCloss_recov_trunc(defaultprob, issuerweights, recov, rho, K, Z, w, Ngrid=101, defaultflag=False):BCloss_recov_trunc137,5131 -def lossdistrib_joint(p, pp, w, S, Ngrid=101, defaultflag=False):lossdistrib_joint149,5772 -def lossdistrib_joint_Z(p, pp, w, S, rho, Ngrid=101, defaultflag=False, nZ=500):lossdistrib_joint_Z189,6954 -def joint_default_averagerecov_distrib(p, S, Ngrid=101):joint_default_averagerecov_distrib246,8597 -def adjust_attachments(K, losstodate, factor):adjust_attachments277,9510 -def trancheloss(L, K1, K2):trancheloss284,9710 -def trancherecov(R, K1, K2):trancherecov287,9796 -def tranche_cl(L, R, cs, K1, K2, scaled=False):tranche_cl290,9891 -def tranche_pl(L, cs, K1, K2, scaled=False):tranche_pl303,10390 -def tranche_pv(L, R, cs, K1, K2):tranche_pv315,10771 -def credit_schedule(tradedate, tenor, coupon, yc, enddate=None):credit_schedule318,10874 -def cds_accrued(tradedate, coupon):cds_accrued336,11677 -def dist_transform(q):dist_transform347,12087 -def dist_transform2(q):dist_transform2362,12501 -def compute_pv(q, strike):compute_pv376,12902 -def average_recov(p, R, Ngrid):average_recov383,13104 - n_issuers = 100n_issuers411,14110 - p = np.random.rand(n_issuers)p412,14130 - R = np.random.rand(n_issuers)R413,14164 - Rbar = joint_default_averagerecov_distrib(p, 1-R, 1001)Rbar414,14198 - Rbar_slow = average_recov(p, R, 1001)Rbar_slow415,14258 +thetas-durations.py,209 +import numpy as npnp2,16 +import pandas as pdpd3,35 +def get_legs(index, series, tenors):get_legs23,604 +def index_pv(fl, cl, value_date, step_in_date, cash_settle_date, yc, sc, recovery):index_pv52,1678 -analytics/index_data.py,926 -def insert_quotes():insert_quotes15,350 -def get_index_quotes(index=None, series=None, tenor=None, from_date=None, years=3):get_index_quotes48,2099 - def make_str(key, val):make_str56,2443 - def make_params(args):make_params72,2977 -def index_returns(df=None, index=None, series=None, tenor=None, from_date=None, years=3, per=1):index_returns89,3673 -def get_singlenames_quotes(indexname, date):get_singlenames_quotes129,5434 -def build_curve(r, tenors, currency="USD"):build_curve135,5652 -def build_curves(quotes, args):build_curves149,6222 -def build_curves_dist(quotes, args, workers=4):build_curves_dist152,6323 -def _get_singlenames_curves(index_type, series, trade_date):_get_singlenames_curves160,6629 -def get_singlenames_curves(index_type, series, trade_date):get_singlenames_curves168,7003 -def get_tranche_quotes(index_type, series, tenor, date=datetime.date.today()):get_tranche_quotes175,7329 +markit/import_quotes.py,689 +import numpy as npnp4,42 +import pandas as pdpd5,61 +def convert(x):convert15,236 +def get_index_list(database, workdate):get_index_list22,335 +def get_markit_bbg_mapping(database, basketid_list, workdate):get_markit_bbg_mapping48,1007 +def get_bbg_tickers(database, basketid_list, workdate):get_bbg_tickers77,2202 +def get_basketids(database, index_list, workdate):get_basketids89,2625 +def get_current_tickers(database, workdate):get_current_tickers97,2881 +def insert_cds(database, workdate):insert_cds103,3115 +def get_date(f):get_date159,5266 +def insert_index(engine, workdate=None):insert_index168,5470 +def insert_tranche(engine, workdate=None):insert_tranche235,7845 -analytics/tranche_basket.py,1697 -class TrancheBasket(BasketIndex):TrancheBasket18,633 - def __init__(self, index_type: str, series: int, tenor: str, *,__init__19,667 - def tranche_factors(self):tranche_factors66,3027 - def _get_quotes(self, spread=None):_get_quotes69,3127 - def _snacpv(self, spread, coupon, recov):_snacpv82,3747 - def default_prob(self):default_prob88,4035 - def tranche_legs(self, K, rho, complement=False, shortened=0):tranche_legs92,4243 - def tranche_pvs(self, protection=False, complement=False, shortened=0):tranche_pvs115,5337 - def index_pv(self, discounted=True, shortened=0):index_pv135,6036 - def expected_loss(self, discounted=True, shortened=0):expected_loss157,6935 - def expected_loss_trunc(self, K, rho=None, shortened=0):expected_loss_trunc171,7406 - def probability_trunc(self, K, rho=None, shortened=0):probability_trunc188,8112 - def recovery_rates(self):recovery_rates202,8651 - def tranche_durations(self, complement=False):tranche_durations205,8750 - def _row_names(self):_row_names214,9120 - def tranche_thetas(self, complement=False, shortened=4, method='ATM'):tranche_thetas219,9312 - def tranche_fwd_deltas(self, complement=False, shortened=4, method='ATM'):tranche_fwd_deltas228,9795 - def tranche_deltas(self, complement=False):tranche_deltas239,10208 - def build_skew(self, skew_type="bottomup"):build_skew261,11131 - def aux(rho, obj, K, quote, spread, complement):aux265,11275 - def map_skew(self, index2, method="ATM", shortened=0):map_skew298,12825 - def aux(x, index1, el1, index2, el2, K2, shortened):aux299,12884 - def aux2(x, index1, index2, K2, shortened):aux2308,13292 +markit/__main__.py,96 +import numpy as npnp3,31 +import pandas as pdpd4,50 +def default_date():default_date33,1091 -analytics/scenarios.py,403 -def run_swaption_scenarios(swaption, date_range, spread_shock, vol_shock,run_swaption_scenarios11,264 -def run_index_scenarios(index, date_range, spread_shock, params=['pnl']):run_index_scenarios43,1387 -def _aux(portf, curr_vols, params, vs):_aux56,1849 -def MaybePool(nproc):MaybePool62,2068 -def run_portfolio_scenarios(portf, date_range, spread_shock, vol_shock,run_portfolio_scenarios65,2136 +markit/rates.py,180 +import pandas as pdpd6,81 +import xml.etree.ElementTree as ETET10,182 +def downloadMarkitIRData(download_date=datetime.date.today(), currency="USD"):downloadMarkitIRData16,295 -analytics/cms_spread.py,907 -def CMS_spread(T_alpha, X, beta, gamma):CMS_spread32,1322 -def f(v, X, S_alpha_beta, S_alpha_gamma, mu_beta, mu_gamma, T_alpha, rho):f36,1416 -def h(v, X, S_alpha_beta, mu_beta, sigma_alpha_beta, T_alpha):h47,2017 -def get_fixings(conn, tenor1, tenor2, fixing_date=None):get_fixings52,2239 -def build_spread_index(tenor1, tenor2):build_spread_index74,3113 -def get_swaption_vol_data(source="ICPL", vol_type=VolatilityType.ShiftedLognormal,get_swaption_vol_data81,3413 -def get_swaption_vol_surface(date, vol_type):get_swaption_vol_surface100,4097 -def get_swaption_vol_matrix(date, data, vol_type=VolatilityType.ShiftedLognormal):get_swaption_vol_matrix105,4356 -def quantlib_model(date, spread_index, yc, cap, rho, maturity, mean_rev=0.,quantlib_model124,5226 -def plot_surf(surf, tenors):plot_surf146,6310 -def globeop_model(date, spread_index, yc, strike, rho, maturity,globeop_model152,6489 +markit/loans.py,265 +def download_facility(workdate, payload):download_facility12,170 +def insert_facility(conn, workdate):insert_facility24,566 +def download_marks(conn, workdate, payload):download_marks50,1489 +def update_facility(conn, workdate, payload):update_facility81,2669 -analytics/index.py,2689 -def g(index, spread, exercise_date, forward_yc=None, pv=None):g24,688 -class Index(object):Index52,1980 - __slots__ = ['fixed_rate', 'notional', '_start_date', '_end_date',__slots__54,2055 - def __init__(self, start_date, end_date, recovery, fixed_rate,__init__62,2598 - def __hash__(self):__hash__97,4009 - def __getstate__(self):__getstate__100,4108 - def __setstate__(self, state):__setstate__103,4203 - def start_date(self):start_date109,4369 - def end_date(self):end_date113,4442 - def start_date(self, d):start_date117,4520 - def end_date(self, d):end_date123,4729 - def spread(self):spread129,4931 - def direction(self):direction135,5080 - def direction(self, d):direction142,5232 - def _update(self):_update150,5476 - def spread(self, s):spread167,6392 - def flat_hazard(self):flat_hazard175,6606 - def pv(self):pv181,6770 - def pv(self, val):pv185,6878 - def accrued(self):accrued191,7112 - def days_accrued(self):days_accrued196,7266 - def clean_pv(self):clean_pv200,7349 - def price(self):price204,7468 - def price(self, val):price208,7535 - def ref(self):ref230,8626 - def ref(self, val):ref237,8770 - def DV01(self):DV01244,8915 - def theta(self):theta252,9110 - def IRDV01(self):IRDV01263,9558 - def rec_risk(self):rec_risk282,10163 - def jump_to_default(self):jump_to_default295,10543 - def risky_annuity(self):risky_annuity300,10703 - def trade_date(self):trade_date304,10798 - def trade_date(self, d):trade_date311,10999 - def reset_pv(self):reset_pv327,11687 - def pnl(self):pnl332,11828 - def notify(self):notify342,12271 - def observe(self, obj):observe346,12355 - def mark(self):mark349,12416 - def factor(self):factor364,13074 - def version(self):version372,13270 - def from_name(cls, index=None, series=None, tenor=None, trade_date=datetime.date.today(),from_name380,13475 - def from_tradeid(cls, trade_id):from_tradeid435,16138 - def __repr__(self):__repr__464,17433 -class ForwardIndex(object):ForwardIndex509,19983 - __slots__ = ['index', 'forward_date', 'exercise_date_settle', 'df',__slots__510,20011 - def __init__(self, index, forward_date, observer=True):__init__513,20186 - def from_name(cls, index_type, series, tenor, forward_date,from_name526,20680 - def forward_annuity(self):forward_annuity532,20948 - def forward_pv(self):forward_pv536,21031 - def forward_spread(self):forward_spread540,21104 - def ref(self):ref544,21191 - def ref(self, val):ref548,21257 - def __hash__(self):__hash__551,21311 - def _update(self, *args):_update554,21435 +markit/.ropeproject/config.py,90 +def set_prefs(prefs):set_prefs5,45 +def project_opened(project):project_opened120,4706 -analytics/utils.py,471 -tenor_t = CategoricalDtype(['3yr', '5yr', '7yr', '10yr'], ordered=True)tenor_t10,289 -def GHquad(n):GHquad12,362 -def previous_twentieth(d):previous_twentieth17,485 -def next_twentieth(d):next_twentieth26,689 -def third_wednesday(d):third_wednesday35,894 -def next_third_wed(d):next_third_wed41,1099 -def roll_date(d, tenor, nd_array=False):roll_date48,1251 - def kwargs(t):kwargs51,1380 -def build_table(rows, format_strings, row_format):build_table94,3058 +markit/cds.py,216 +import pandas as pdpd9,140 +def convertToNone(v):convertToNone14,205 +def download_cds_data(payload):download_cds_data18,261 +def download_composite_data(payload, historical=False):download_composite_data40,912 -analytics/basket_index.py,1693 -def make_index(t, d, args):make_index16,452 -class BasketIndex(CreditIndex):BasketIndex22,603 - def __init__(self, index_type: str, series: int, tenors: List[str], *,__init__30,776 - def __reduce__(self):__reduce__64,2796 - def __hash__(self):__hash__69,2951 - def aux(v):aux70,2975 - def _query_version(self, i):_query_version80,3319 - def factor(self):factor86,3488 - def cumloss(self):cumloss90,3563 - def version(self):version94,3639 - def _get_quotes(self):_get_quotes97,3701 - trade_date = property(CreditIndex.trade_date.__get__)trade_date100,3742 - def trade_date(self, d: pd.Timestamp):trade_date103,3824 - def pv(self, maturity=None, epsilon=0., coupon=None):pv110,4119 - def coupon_leg(self, maturity=None):coupon_leg131,5038 - def protection_leg(self, maturity=None):protection_leg134,5143 - def spread(self, maturity=None, coupon=None):spread137,5234 - def duration(self, maturity=None):duration143,5510 - def theta(self, maturity=None, coupon=None):theta154,5988 - def coupon(self, maturity=None):coupon183,7332 - def tweak(self, *args):tweak189,7526 -class MarkitBasketIndex(BasketIndex):MarkitBasketIndex216,8549 - def __init__(self, index_type: str, series: int, tenors: List[str], *,__init__217,8587 - def _get_quotes(self):_get_quotes230,9434 - ig28 = BasketIndex("IG", 28, ["3yr", "5yr", "7yr", "10yr"])ig28234,9543 - settings = Settings()settings237,9727 - cds_schedule = Schedule.from_rule(settings.evaluation_date, Date.from_datetime(ig28.maturities[-1]),cds_schedule239,9754 - sp = ig28.survival_matrix(cds_schedule.to_npdates().view('int') + 134774)sp241,9962 +markit/README.md,0 -.ropeproject/config.py,90 -def set_prefs(prefs):set_prefs5,45 -def project_opened(project):project_opened110,4652 +markit/__init__.py,0 -templates/template-2014-05-19.html,0 +swaption_quotes.py,101 +import pandas as pdpd2,16 +def get_refids(get_refids8,138 +def adjust_stacks(adjust_stacks32,723 -templates/template-2014-03-17.html,0 +ecb_yieldcurve.py,0 -templates/template-2015-01-14.html,0 +load_cf.py,884 +import pandas as pdpd3,27 +import numpy as npnp5,101 +import rpy2.robjects as roro26,592 +def sanitize_float(string):sanitize_float30,636 +def processzipfiles(tradedate=datetime.date.today()):processzipfiles41,889 +def get_configfile(dealname, tradedate):get_configfile69,2057 +def get_dist(date):get_dist85,2483 +def get_dealdata(dealname, tradedate):get_dealdata96,2772 +def get_cusipdata(cusip, tradedate):get_cusipdata109,3241 +def get_dealschedule(dealdata, freq="1Mo", adj=Unadjusted):get_dealschedule115,3446 +def dealname_from_cusip(conn, cusips):dealname_from_cusip132,3968 +def discounts(tradedate):discounts139,4154 +def getdealcf(dealnames, zipfiles, tradedate=datetime.date.today()):getdealcf153,4716 +def getcusipcf(params, cfdata, tradedate):getcusipcf205,6912 +def compute_delta(dist, dealweight, cusip_pv, tradedate, K1=0, K2=1):compute_delta258,9042 -templates/template-2014-07-16.html,0 +globeop_reports.py,612 +import pandas as pdpd8,295 +import numpy as npnp9,315 +def get_monthly_pnl(group_by=["identifier"]):get_monthly_pnl13,352 +def get_portfolio(report_date=None):get_portfolio34,1003 +def trade_performance():trade_performance56,1672 +def get_net_navs():get_net_navs100,3322 +def shift_cash(date, amount, df, strat):shift_cash119,3981 +def calc_trade_performance_stats():calc_trade_performance_stats126,4229 +def hist_pos(asset_class="rmbs", dm=False):hist_pos147,4981 +def rmbs_pos(date, model_date=None, dm=False):rmbs_pos167,5643 +def crt_pos(date):crt_pos246,8526 +def clo_pos(date):clo_pos252,8626 -templates/template-2014-11-13.html,0 +risk_insight/templates/indices.html,246 + <div id="graph" class="graph">graph7,131 + <div id="select-box">select-box9,177 + <select id="index">index10,203 + <select id="series">series16,399 + <select id="tenor">tenor21,535 + <select id="what">what29,760 -templates/template-2015-02-12.html,0 +risk_insight/templates/tranches.html,268 + <div id="graph1" class="graph"></div>graph17,131 + <div id="graph2" class="graph"></div>graph28,173 + <select id="index">index10,245 + <select id="series">series16,439 + <select id="tenor">tenor21,576 + <select id="greek">greek29,823 -templates/template-2014-03-12.html,0 +risk_insight/templates/index.html,0 -templates/template-2014-10-17.html,0 +risk_insight/views.py,353 +def get_attach_from_name(index_type, series):get_attach_from_name11,165 +def get_db():get_db29,704 +def close_connection(exception):close_connection39,945 +def get_risk_numbers():get_risk_numbers46,1091 +def get_indices_quotes():get_indices_quotes71,2043 +def tranches():tranches109,3208 +def indices():indices118,3479 +def main():main123,3601 -templates/template-2015-03-16.html,0 +risk_insight/.ropeproject/config.py,90 +def set_prefs(prefs):set_prefs5,45 +def project_opened(project):project_opened120,4706 -templates/template-2014-08-12.html,0 +risk_insight/static/insight.css,86 +.graph{.graph6,74 +#select-box{#select-box14,193 +.select-box2{.select-box219,255 -templates/template-2014-06-13.html,0 +risk_insight/__init__.py,0 -templates/template-2014-12-11.html,0 +thetas_durations.py,209 +import numpy as npnp2,16 +import pandas as pdpd3,35 +def get_legs(index, series, tenors):get_legs23,604 +def index_pv(fl, cl, value_date, step_in_date, cash_settle_date, yc, sc, recovery):index_pv52,1678 -templates/trading_form.tex,0 +parse_preqin.py,0 -templates/template2-2014-04-16.html,0 +exchange.py,275 +def get_account(email_address):get_account6,118 +class ExchangeMessage:ExchangeMessage19,527 + def get_msgs(self, count=None, path=["GS", "Swaptions"], **filters):get_msgs22,597 + def send_email(self, subject, body, to_recipients, cc_recipients):send_email34,1017 -templates/template-2014-09-15.html,0 +gmail_helpers.py,629 +def get_gmail_service():get_gmail_service19,424 +def ListMessagesWithLabels(service, user_id, label_ids=[]):ListMessagesWithLabels57,1602 +def ListHistory(service, user_id, label_id=None, start_history_id=10000):ListHistory94,2902 +def labels_dict(service, user_id):labels_dict137,4292 +class GmailMessage(EmailMessage):GmailMessage155,4873 + def __init__(self):__init__159,4947 + def msgdict(self):msgdict166,5206 + def send(self):send169,5305 + def list_msg_ids(cls, label, start_history_id=None):list_msg_ids182,5688 + def from_id(cls, msg_id, user_id="me"):from_id196,6136 +def main():main214,6765 -templates/template-2015-04-20.html,0 +utils/db.py,664 +import numpy as npnp10,337 +class InfDateAdapter:InfDateAdapter14,372 + def __init__(self, wrapped):__init__15,394 + def getquoted(self):getquoted18,459 +def nan_to_null(f, _NULL=AsIs("NULL"), _Float=psycopg2.extensions.Float):nan_to_null27,749 +def dbconn(dbname, cursor_factory=NamedTupleCursor):dbconn38,1027 +def dbengine(dbname, cursor_factory=NamedTupleCursor):dbengine53,1426 +def with_connection(dbname):with_connection80,2315 + def decorator(f):decorator81,2344 + def with_connection_(*args, **kwargs):with_connection_84,2397 +def query_db(conn, sqlstr, params=None, one=True):query_db99,2754 +def close_db():close_db121,3229 -templates/template-2014-04-16.html,0 +utils/__init__.py,312 +class SerenitasFileHandler(logging.FileHandler):SerenitasFileHandler6,51 + def __init__(self, log_file):__init__13,272 +class SerenitasRotatingFileHandler(logging.handlers.RotatingFileHandler):SerenitasRotatingFileHandler18,447 + def __init__(self, log_file, maxBytes=0, backupCount=0):__init__21,587 -exploration/beta_trade.py,690 -def calc_returns(index_list=['HY', 'IG'], save_feather=False):calc_returns19,389 -def calc_betas(returns=None, spans=[5, 20], index_list=['HY', 'IG']):calc_betas30,917 -def plot_betas(betas=None):plot_betas40,1313 -def calc_realized_vol(returns=None):calc_realized_vol50,1577 -def spreads_ratio(series=list(range(22, 29)), index=['IG', 'HY'], tenor='5yr'):spreads_ratio73,2462 -def loglik(beta, returns):loglik79,2727 - returns = calc_returns()returns86,2906 - betas = calc_betas(returns)betas87,2935 - vol = calc_realized_vol(returns)vol89,2989 - ratios = spreads_ratio()ratios90,3026 - prog = minimize_scalar(loglik, bracket=(3, 5), args=(returns,))prog91,3055 +swaption_pnl.py,111 +import pandas as pdpd2,16 +def get_index_pv(get_index_pv11,284 +def get_swaption_pv(get_swaption_pv47,1381 -exploration/tranches.py,326 -engine = dbengine('serenitasdb')engine17,571 -def rv_calc1():rv_calc119,606 -def dispersion():dispersion71,2854 -def scenarios(tranche, shock_range=None, roll_corr=False):scenarios99,4320 -def run_scen(trade_date = pd.Timestamp.today().normalize()- pd.offsets.BDay()):run_scen148,6960 -def plot_pnl():plot_pnl198,9083 +pyisda/Makefile,100 +build:build1,0 +clean:clean4,45 +install:install8,169 +docs: builddocs11,194 +test:test14,226 -exploration/sell_atm_vol.py,357 -option_delta = Index.from_name('ig', 28, '5yr')option_delta6,145 -payer = BlackSwaption(option_delta, datetime.date(2017, 5, 17), 67.5, direction='Short')payer9,254 -receiver = BlackSwaption(option_delta, datetime.date(2017, 8, 16), 62.5, 'receiver')receiver10,343 -portfolio = Portfolio([payer, receiver, option_delta])portfolio24,668 -r = []r27,804 +pyisda/c_layer/cdsbootstrap.c,61 +int cdsBootstrapPointFunctioncdsBootstrapPointFunction3,27 -exploration/test_cms.py,652 -cap = 0.00758cap7,194 -corr = 0.8corr8,208 -r = []r9,219 -maturity = pd.Timestamp("2020-01-19")maturity10,226 -today = pd.Timestamp.today()today11,264 - cms_spread_coupon_ln = quantlib_model(d, cms30y2y, yc, cap, corr, maturity)cms_spread_coupon_ln17,500 - rate1 = cms_spread_coupon_ln.raterate118,580 - cms_spread_coupon_n = quantlib_model(d, cms30y2y, yc, cap, corr, maturity,cms_spread_coupon_n19,618 - rate2 = cms_spread_coupon_n.raterate221,759 - rate3 = globeop_model(d, cms30y2y, yc, cap, corr - 0.075, maturity)rate322,796 -df = pd.DataFrame(r, columns=['date', 'QL_ln', 'QL_n', 'Globeop']).set_index('date')df24,907 +pyisda/c_layer/survival_curve.hpp,1078 +struct CurveName {CurveName3,19 + enum class __attribute__ ((__packed__)) Seniority {Seniority4,38 + Senior,Senior5,94 + SubordinatedSubordinated6,110 + enum class __attribute__ ((__packed__)) DocClause {DocClause9,139 + XR14,XR1410,195 + MR14,MR1411,209 + MM14,MM1412,223 + CR14CR1413,237 + void serialize(unsigned char* buf) {serialize15,257 + std::string full_ticker() {full_ticker23,523 + void serialize(unsigned char* buf, size_t num) {serialize29,698 + CurveName(std::string& ticker, Seniority seniority, DocClause doc_clause) :CurveName37,982 + CurveName(const unsigned char* buf) {CurveName42,1152 + CurveName() {};CurveName50,1416 + size_t size() {size52,1437 + bool operator<(const CurveName &other) const {operator <56,1541 + std::string str_seniority() const {str_seniority63,1836 + std::string str_doc_clause() const {str_doc_clause72,2057 + std::string ticker;ticker85,2373 + Seniority seniority;seniority86,2397 + DocClause doc_clause;doc_clause87,2422 -exploration/curve_trades.py,1273 -_engine = dbengine('serenitasdb')_engine15,461 -def on_the_run(index):on_the_run17,496 -def curve_spread_diff(index='IG', rolling=6):curve_spread_diff23,689 -def spreads_diff_table(spreads_diff):spreads_diff_table35,1217 - def current(s):current36,1255 - def zscore(s):zscore38,1300 -def theta_matrix_by_series(index='IG', rolling=6):theta_matrix_by_series44,1517 -def ratio_within_series(index='IG', rolling=6, param='duration'):ratio_within_series53,1999 -def curve_3_5_10(df):curve_3_5_1064,2548 -def curve_5_10(df):curve_5_1075,2872 -def on_the_run_theta(index='IG', rolling=6):on_the_run_theta80,3033 -def curve_returns(index='IG', rolling=6):curve_returns88,3405 - def sharpe(df, period="daily"):sharpe107,4344 -def cross_series_curve(index='IG', rolling=6):cross_series_curve119,4843 -def forward_loss(index='IG'):forward_loss137,5704 -def curve_model(tenor_1='5yr', tenor_2='10yr'):curve_model154,6655 -def curve_model_results(df, model):curve_model_results169,7304 -def spread_fin_crisis(index='IG'):spread_fin_crisis182,8088 -def forward_spread(index='IG', series=None, tenors=['3yr', '5yr', '7yr', '10yr']):forward_spread206,8989 -def spot_forward(index='IG', series=None, tenors=['3yr', '5yr', '7yr', '10yr']):spot_forward220,9485 +pyisda/c_layer/cdsbootstrap.h,512 +#define SUCCESS SUCCESS12,171 +#define FAILURE FAILURE13,189 +{__anoneade35ba010816,224 + TDate stepinDate;stepinDate17,226 + TDate cashSettleDate;cashSettleDate18,258 + TCurve *discountCurve;discountCurve19,294 + TCurve *cdsCurve;cdsCurve20,329 + double recoveryRate;recoveryRate21,359 + double spread;spread22,393 + TContingentLeg *cl;cl23,421 + TFeeLeg *fl;fl24,445 +} cds_bootstrap_ctx;cds_bootstrap_ctx25,469 -exploration/backtest.py,130 -def calc_mark_diff():calc_mark_diff5,64 - def closest(s):closest12,385 - def avg_minus_maxmin(s):avg_minus_maxmin20,592 +pyisda/setup.py,0 -exploration/option_trades.py,1558 -serenitasdb = dbengine('serenitasdb')serenitasdb14,310 -def realized_vol(index, series, tenor='5yr', date=None, years=None, return_type='spread'):realized_vol16,349 -def lr_var(res):lr_var29,1048 -def atm_vol_calc(df, index_type, moneyness):atm_vol_calc42,1443 -def atm_vol(index, date, series=None, moneyness=0.2):atm_vol75,3123 -def rolling_vol(df, col='atm_vol', term=[3]):rolling_vol91,3914 - def aux(s, col, term):aux95,4128 -def vol_var(percentile=0.975, index='IG', start_date=datetime.date(2014, 6, 11)):vol_var106,4606 -def get_index_spread(index, series, date, conn):get_index_spread119,5093 -def get_index_ref(index, series, date, expiry, conn):get_index_ref131,5487 -def get_option_pnl(strike, expiry, index, series, start_date, engine):get_option_pnl144,5988 -def sell_vol_strategy(index="IG", months=3):sell_vol_strategy179,7669 -def aggregate_trades(d):aggregate_trades205,8976 -def compute_allocation(df):compute_allocation211,9119 - df = atm_vol("HY", datetime.date(2017, 3, 20))df246,10413 - df_hy28 = df.xs(28, level='series')df_hy28250,10603 - results = smf.ols('log_atm_vol ~ log_forward_spread + T', data=df_hy28).fit()results251,10643 - beta_hy28 = 1 + results.params.log_forward_spreadbeta_hy28252,10725 - df = atm_vol("IG", datetime.date(2017, 3, 20))df256,10819 - df_ig28 = df.xs(28, level='series')df_ig28260,11009 - results = smf.ols('log_atm_vol ~ log_forward_spread + T', data=df_ig28).fit()results261,11049 - beta_ig28 = 1 + results.params.log_forward_spreadbeta_ig28262,11131 +pyisda/example.py,0 -exploration/curve_trades2.py,945 -def on_the_run(index):on_the_run10,267 -def curve_spread_diff(index='IG', rolling=6):curve_spread_diff16,470 -def spreads_diff_table(spreads_diff):spreads_diff_table31,1140 - def current(s):current32,1178 - def zscore(s):zscore34,1223 -def theta_matrix_by_series(index='IG', rolling=6):theta_matrix_by_series40,1440 -def ratio_within_series(index='IG', rolling=6, param='duration'):ratio_within_series49,1922 -def curve_3_5_10(theta_ratio_within_series):curve_3_5_1059,2417 -def curve_5_10(theta_ratio_within_series):curve_5_1071,2983 -def on_the_run_theta(index='IG', rolling=6):on_the_run_theta77,3211 -def curve_returns(index='IG', rolling=6):curve_returns85,3583 - def sharpe(df, period="daily"):sharpe102,4387 -def cross_series_curve(index='IG'):cross_series_curve114,4886 -def forward_loss(index='IG'):forward_loss131,5655 -def read_IG_curve_pos():read_IG_curve_pos148,6606 -def curve_model():curve_model155,6840 +pyisda/pyisda/legs.pyx,864 +cdef class ContingentLeg:ContingentLeg7,221 + def __cinit__(self, start_date, end_date, double notional,__cinit__20,532 + def __dealloc__(self):__dealloc__30,989 + def __reduce__(self):__reduce__34,1087 + def __hash__(self):__hash__41,1459 + def end_date(self):end_date48,1712 + def pv(self, today, step_in_date, value_date, YieldCurve yc not None,pv51,1791 +cdef class FeeLeg:FeeLeg79,2932 + def __cinit__(self, start_date, end_date, bint pay_accrued_on_default,__cinit__99,3520 + def __reduce__(self):__reduce__122,4593 + def __hash__(self):__hash__131,5114 + def inspect(self):inspect140,5501 + def cashflows(self):cashflows155,6149 + def pv(self, today, step_in_date, value_date, YieldCurve yc not None,pv165,6479 + def accrued(self, today):accrued193,7608 + def __dealloc__(self):__dealloc__208,7914 -exploration/marketing.py,357 -gridsize = 500gridsize6,131 -def run_scenario(pool_size, rho, successprob, issuerweights, amount):run_scenario8,147 -def plot_scenarios(df, bins = [0,0.1, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 2000]):plot_scenarios17,553 -def stats(df):stats37,1333 -def plot_prob_over(df):plot_prob_over44,1565 -def add_to_plot(df, ax):add_to_plot51,1763 +pyisda/pyisda/logging.pxd,0 -exploration/.ropeproject/config.py,90 -def set_prefs(prefs):set_prefs5,45 -def project_opened(project):project_opened110,4652 +pyisda/pyisda/version.pyx,28 +def version():version4,71 -exploration/sell_vol.py,575 -df = index_returns(index="IG", tenor=["5yr"])df12,438 -df = df.reset_index(['index', 'tenor'], drop=True)df13,484 -spreads = df.dropna().groupby(['date']).nth(-1)['spread_return']spreads14,535 -monthly_returns = spreads.rolling('30D').apply(lambda s: (1 + s).prod() - 1)monthly_returns15,600 -mu = monthly_returns.median()mu16,677 -ecdf = ECDF(monthly_returns)ecdf17,707 -def implied_vol(q):implied_vol19,737 -engine = dbengine('serenitasdb')engine24,949 -sched = Schedule.from_rule(Date(1, 6, 2014), Date(1, 4, 2018), Period(1, Months), UnitedStates())sched25,982 +pyisda/pyisda/cdsone.pxd,0 -exploration/swaption_calendar_spread.py,406 -engine = dbengine('serenitasdb')engine22,606 -def plot_df(df, spread_shock, vol_shock, attr="pnl"):plot_df25,642 -def plot_color_map(df, spread_shock, vol_shock, attr="pnl", path=".", index ='IG'):plot_color_map40,1237 -def plot_trade_scenarios(portf, shock_min=-.15, shock_max=.2, period = -1, vol_time_roll=True):plot_trade_scenarios65,2461 -def exercise_probability():exercise_probability94,4069 +pyisda/pyisda/optim.pyx,375 +cdef free_my_ctx(object cap):free_my_ctx50,2064 +def init_context(YieldCurve yc not None, trade_date, value_date, start_date,init_context58,2310 +cdef api double pv(double Z, void* ctx) nogil except NAN:pv110,4631 +def update_context(object ctx, double S0):update_context144,6167 +def expected_pv(double[:] tilt, double[:] w, double S0, object ctx):expected_pv150,6382 -exploration/compression.py,181 -df = get_index_quotes(["IG", "HY"], 27, "5yr")df2,40 -df = df.groupby(level=['date', 'index']).nth(-1)df3,87 -df = df.groupby(level=['date', 'index', 'version']).nth(-1)df5,168 +pyisda/pyisda/credit_index.pyx,2474 +from cython.operator cimport dereference as deref, preincrement as preincderef7,272 +from cython.operator cimport dereference as deref, preincrement as preincpreinc7,272 +cimport numpy as npnp22,1113 +import pandas as pdpd24,1151 +cdef TFeeLeg* copyFeeLeg(TFeeLeg* leg) nogil:copyFeeLeg31,1278 +cdef TContingentLeg* copyContingentLeg(TContingentLeg* leg) nogil:copyContingentLeg43,1802 +cdef class CurveList:CurveList49,2048 + def __init__(self, list curves not None, value_date=None):__init__52,2107 + def __getitem__(self, tuple name not None):__getitem__92,3464 + def items(self):items114,4453 + def weights(self):weights128,4955 + def tickers(self):tickers137,5277 + def value_date(self):value_date146,5572 + def value_date(self, d):value_date150,5669 + def curves(self):curves154,5757 + def curves(self, list l not None):curves173,6403 + def __reduce__(self):__reduce__205,7564 +cdef class CreditIndex(CurveList):CreditIndex209,7698 + def __init__(self, start_date, maturities, list curves, value_date=None):__init__210,7733 + def __dealloc__(self):__dealloc__227,8566 + def __reduce__(self):__reduce__264,10230 + def __hash__(self):__hash__269,10421 + def pv_vec(self, step_in_date, cash_settle_date, YieldCurve yc not None):pv_vec299,11771 + def accrued(self):accrued355,14242 + def pv(self, step_in_date, cash_settle_date, maturity, YieldCurve yc not None,pv360,14382 + def theta(self, step_in_date, cash_settle_date, maturity, YieldCurve yc not None,theta390,15594 + def protection_leg(self, step_in_date, cash_settle_date, maturity, YieldCurve yc not None):protection_leg447,18058 + def duration(self, step_in_date, cash_settle_date, maturity, YieldCurve yc not None):duration482,19617 + def maturities(self):maturities531,21337 + def maturities(self, list val):maturities541,21560 + def tweak_portfolio(self, double epsilon, maturity, bint inplace=True):tweak_portfolio554,22030 + def survival_matrix(self, const TDate[::1] schedule=None, double epsilon=0.):survival_matrix575,22847 +cdef unsigned long fill_mask(const TDate maturity, const vector[TDate]& maturities,fill_mask604,23893 +cdef inline int get_maturity_index(TDate maturity, const vector[TDate]& maturities):get_maturity_index631,24590 +cdef pair[TContingentLeg_ptr, TFeeLeg_ptr] get_legs(TDate maturity,get_legs640,24830 +cdef double pv(const vector[shared_ptr[TCurve]]& curves,pv663,25819 -exploration/cds_pnl.py,318 -trade_date = datetime.date(2017, 5, 31)trade_date7,126 -def get_portf(trade_date):get_portf9,167 -portf = get_portf(datetime.date(2017, 5, 31))portf29,870 -dr = pd.date_range('2017-06-01', '2017-06-30', freq=bus_day)dr30,916 -pnl = []pnl32,978 - portf = get_portf(datetime.date(2017, 6, 27))portf38,1175 +pyisda/pyisda/date.pyx,965 +from cpython cimport datetime as c_datetimec_datetime2,16 +cimport numpy as npnp6,159 +cpdef TDate pydate_to_TDate(c_datetime.date d):pydate_to_TDate13,250 +cpdef c_datetime.date TDate_to_pydate(TDate d):TDate_to_pydate16,363 +cdef long dcc(str day_count) except -1:dcc24,601 +def dcc_tostring(long day_count):dcc_tostring34,862 +cdef TDate _previous_twentieth(TDate d, bint roll) nogil:_previous_twentieth39,980 +def previous_twentieth(d, bint roll=True):previous_twentieth66,1634 +def cds_accrued(d, double coupon):cds_accrued72,1804 +cdef TMonthDayYear next_twentieth(TDate d) nogil:next_twentieth78,2010 +cdef inline TDate next_business_day(TDate date, long method) nogil:next_business_day96,2451 +cdef void _roll_date(TDate d, const double* tenors, int n_dates, TDate* output) nogil:_roll_date103,2645 +def roll_date(d, tenor):roll_date139,3771 +def default_accrual(trade_date, edd, start_date, end_date, double notional,default_accrual166,4595 -exploration/portfolio_var.py,463 -dawndb = dbengine('dawndb')dawndb14,330 -serenitasdb = dbengine('serenitasdb')serenitasdb15,358 -def on_the_run(index):on_the_run17,397 -def rel_spread_diff(report_date = datetime.date.today(), index='HY', rolling=10):rel_spread_diff23,600 -def get_pos(report_date):get_pos38,1249 -def cleared_cds_margins(report_date=datetime.date.today()):cleared_cds_margins49,1712 -def index_curve_margins(report_date=datetime.date.today()):index_curve_margins71,2856 +pyisda/pyisda/curve.pyx,3241 +from cython.operator import dereference as deref, preincrement as preincderef1,0 +from cython.operator import dereference as deref, preincrement as preincpreinc1,0 +cimport numpy as npnp14,726 +import numpy as npnp15,746 +import pandas as pdpd17,783 +cdef inline void double_free(double* ptr) nogil:double_free33,1198 +cdef double survival_prob(const TCurve* curve, TDate start_date, TDate maturity_date, double epssurvival_prob37,1263 +cdef class Curve(object):Curve57,1996 + def __getstate__(self):__getstate__59,2023 + def __setstate__(self, bytes state):__setstate__68,2318 + cdef size_t size(self) nogil:size75,2564 + def from_bytes(cls, object state):from_bytes79,2661 + def __hash__(self):__hash__94,3192 + def inspect(self):inspect104,3540 + def to_series(self, bint forward=True):to_series120,4098 + def __iter__(self):__iter__151,5303 + def __len__(self):__len__158,5531 + def __deepcopy__(self, dict memo):__deepcopy__161,5597 + def forward_hazard_rates(self):forward_hazard_rates170,5875 + def base_date(self):base_date202,7081 + def __forward_zero_price(self, d2, d1=None):__forward_zero_price205,7166 +cdef fArray_to_list(TRatePt* fArray, int fNumItems):fArray_to_list224,7764 +cdef class YieldCurve(Curve):YieldCurve231,7971 + def __init__(self, date, str types,__init__260,8933 + cdef size_t size(self) nogil:size317,11087 + def __getstate__(self):__getstate__320,11207 + def __setstate__(self, bytes state):__setstate__332,11586 + def __deepcopy__(self, dict memo):__deepcopy__345,12076 + def from_bytes(cls, object state):from_bytes353,12363 + def __hash__(self):__hash__376,13163 + def from_discount_factors(cls, base_date, list dates, double[:] dfs, str day_count_conv):from_discount_factors393,13727 + def dates(self):dates413,14661 + def expected_forward_curve(self, forward_date):expected_forward_curve419,14801 +cdef void tweak_curve(const TCurve* sc, TCurve* sc_tweaked, double epsilon,tweak_curve443,15873 +cdef class SpreadCurve(Curve):SpreadCurve462,16544 + def __init__(self, today, YieldCurve yc not None, start_date, step_in_date,__init__484,17217 + cdef size_t size(self) nogil:size622,23359 + def __getstate__(self):__getstate__627,23568 + def __setstate__(self, bytes state):__setstate__644,24196 + def __deepcopy__(self, dict memo):__deepcopy__662,24926 + def defaulted(self):defaulted675,25549 + def default_date(self):default_date679,25625 + def from_bytes(cls, bytes state):from_bytes684,25755 + def __hash__(self):__hash__710,26809 + def from_flat_hazard(cls, base_date, double rate, Basis basis=CONTINUOUS,from_flat_hazard728,27502 + def tweak_curve(self, double epsilon, bint multiplicative=True,tweak_curve764,29003 + def par_spread(self, today, step_in_date, start_date, end_dates,par_spread801,30360 + def recovery_rates(self):recovery_rates854,32556 + def ticker(self):ticker862,32861 + def full_ticker(self):full_ticker866,32936 + def seniority(self):seniority870,33023 + def doc_clause(self):doc_clause874,33120 +cdef TCurve* _fill_curve(const TCurve* sc, const TDate* end_dates, int n_dates) nogil:_fill_curve880,33257 -exploration/portfolio_example.py,681 -option_delta = Index.from_tradeid(870)option_delta7,210 -option1 = BlackSwaption.from_tradeid(5, option_delta)option18,249 -option2 = BlackSwaption.from_tradeid(6, option_delta)option29,303 -portf = Portfolio([option1, option2, option_delta])portf11,358 -date_range = pd.bdate_range(option_delta.trade_date,date_range12,410 -vol_shock = np.arange(-0.15, 0.3, 0.01)vol_shock14,529 -spread_shock = np.arange(-0.2, 0.3, 0.01)spread_shock15,569 -vs = BlackSwaptionVolSurface("IG", 27, trade_date=option_delta.trade_date)vs16,611 -vol_surface = vs[vs.list()[-1]]vol_surface17,686 -df = run_portfolio_scenarios(portf, date_range, spread_shock, vol_shock, vol_surface,df18,718 +pyisda/pyisda/credit_index.pxd,92 +cdef class CurveList:CurveList8,224 +cdef class CreditIndex(CurveList):CreditIndex16,471 -murano.py,1029 -df = pd.read_table("/home/share/guillaume/murano leads.csv.txt", encoding="utf-16-le", low_memory=False)df6,71 -df = df.dropna(1, 'all')df8,204 -todrop = []todrop10,271 -df = df.drop(todrop, axis=1)df14,378 -df = df.drop([col for col in df if 'ID' in col], axis=1)df16,437 -website = df.Websitewebsite18,509 -website = website.replace("http://","")website19,530 -df = df.drop(['Teams', 'Do Not Call', 'Assigned User Name', 'Hit Status'], axis=1)df23,706 -col = df['Primary Address Country']col58,2741 -col = col.str.strip().str.title()col59,2777 -col = col.replace(["Republic Of Ireland", "United State Of America", "The Netherlands"],col60,2811 -def generate_table(df):generate_table64,2976 -def list_placeholders(df):list_placeholders99,4294 -def nat_to_null(d, _NULL=AsIs('NULL'),nat_to_null118,4962 -investorsdb = dbengine('investorsdb')investorsdb125,5202 -sql_str = "INSERT INTO investors VALUES({})".format(",".join(list_placeholders(df)))sql_str126,5240 -conn = investorsdb.raw_connection()conn127,5325 +pyisda/pyisda/legs.pxd,607 + cdef TContingentLeg* JpmcdsCdsContingentLegMake(JpmcdsCdsContingentLegMake39,866 + cdef TFeeLeg* JpmcdsCdsFeeLegMake(JpmcdsCdsFeeLegMake50,1276 + cdef int JpmcdsContingentLegPV(TContingentLeg *cl, # Contingent legJpmcdsContingentLegPV80,2612 + cdef int JpmcdsFeeLegPV(TFeeLeg *fl,JpmcdsFeeLegPV90,3247 + cdef TCashFlowList* JpmcdsFeeLegFlows(TFeeLeg *fl)JpmcdsFeeLegFlows99,3605 + cdef void JpmcdsFeeLegFree(TFeeLeg *p)JpmcdsFeeLegFree101,3660 + cdef void FeeLegAI(TFeeLeg* fl,FeeLegAI103,3703 +cdef class ContingentLeg:ContingentLeg107,3808 +cdef class FeeLeg:FeeLeg111,3870 -mark_backtest_underpar.py,794 -def get_mark_df(asset_class = 'Subprime'):get_mark_df12,235 -def calc_mark_diff(df, sources= ['PRICESERVE', 'PRICINGDIRECT','BVAL','MARKIT','BROKER', 'REUTERS', 'S&P', 'IDC']):calc_mark_diff25,1000 -def closest(x):closest51,2224 -def remove_max_min(x):remove_max_min58,2431 -def diff_by_source(df):diff_by_source64,2572 -def diff_by_source_percentage(df):diff_by_source_percentage73,2980 -def count_sources(df):count_sources80,3190 -def alt_navs():alt_navs86,3483 -def annual_performance(nav_100):annual_performance100,4184 -def alt_nav_impact():alt_nav_impact106,4376 -def back_test(begindate = '2013-01-01', enddate = '2018-01-01', sell_price_threshold = 200):back_test112,4551 -def stats(df_long, diff_threshold = 5):stats133,5865 -def pretty_plot(df_long):pretty_plot144,6224 +pyisda/pyisda/date.pxd,440 +from cpython cimport datetime as c_datetimec_datetime1,0 +cdef long dcc(str day_count) except -1dcc7,206 +cpdef TDate pydate_to_TDate(c_datetime.date d)pydate_to_TDate89,3090 +cpdef c_datetime.date TDate_to_pydate(TDate d)TDate_to_pydate91,3138 +cdef void _roll_date(TDate d, const double* tenors, int n_dates, TDate* output) nogil_roll_date93,3186 +cdef TDate _previous_twentieth(TDate d, bint roll) nogil_previous_twentieth94,3272 -insert_index.py,1288 -engine = create_engine('postgresql://serenitas_user@debian/serenitasdb')engine4,74 -metadata = MetaData(bind = engine)metadata5,148 -index_desc = Table('index_desc', metadata, autoload=True)index_desc6,184 -index_ins = index_desc.insert()index_ins7,243 -offset=183000offset9,278 -index = [[offset, 'EU', 21, datetime.date(2017, 6, 20), 'Y3', 100, 0],index10,293 - index = line[1],index31,1558 - series = line[2],series32,1597 - maturity = line[3],maturity33,1637 - tenor = line[4],tenor34,1679 - indexfactor = line[5],indexfactor35,1718 - cumulativeloss = line[6])cumulativeloss36,1763 -tranche_desc = Table('tranche_desc', metadata, autoload = True)tranche_desc38,1813 -tranche_ins = tranche_desc.insert()tranche_ins39,1878 -eubasketid = 183000eubasketid67,2954 -euattach = [0, 3, 6, 12, 100]euattach68,2975 -eutenors = ['Y3', 'Y5']eutenors69,3006 - trancheid =eubasketid+i,trancheid74,3209 - basketid = eubasketid,basketid75,3260 - tenor = tenor,tenor76,3309 - attach = attach,attach77,3350 - detach = detach)detach78,3393 +pyisda/pyisda/logging.pyx,244 +def enable_logging():enable_logging3,53 +def disable_logging():disable_logging11,239 +def set_logging_file(str file_name, TBoolean append = True):set_logging_file15,312 +def log_message(str msg):log_message21,502 +def flush():flush25,585 -Makefile,109 -CFLAGS=-O2 -march=native -fpicCFLAGS1,0 -LDLIBS=-lm -llapackLDLIBS2,31 -LDFLAGS=-fpic -sharedLDFLAGS3,51 +pyisda/pyisda/curve.pxd,924 +cdef inline size_t TCurve_size(const TCurve* curve) nogil:TCurve_size46,1483 +cdef inline unsigned char* serialize(const TCurve* curve, unsigned char* buf) nogil:serialize50,1660 +cdef inline void serialize_vector(const vector[TDate]& v, unsigned char* cursor) nogil:serialize_vector62,2187 +cdef inline const unsigned char* deserialize(const unsigned char* buf, TCurve* curve) nogil:deserialize69,2435 +cdef double survival_prob(const TCurve* curve, TDate start_date,survival_prob184,7819 +cdef inline const TCurve* get_TCurve(Curve c) nogil:get_TCurve246,9502 +cdef class Curve:Curve249,9593 + cdef size_t size(self) nogilsize251,9648 +cdef class YieldCurve(Curve):YieldCurve253,9682 +cdef class SpreadCurve(Curve):SpreadCurve256,9742 +cdef fArray_to_list(TRatePt* fArray, int fNumItems)fArray_to_list261,9878 +cdef void tweak_curve(const TCurve* sc, TCurve* sc_tweaked, double epsilon,tweak_curve263,9931 -notebooks/path.py,0 +pyisda/pyisda/__init__.py,0 -test_hyoption.py,410 -index = Index.from_name("hy", 27, "5yr",index3,54 - trade_date = datetime.date(2016, 11, 16))trade_date4,95 -exercise_date = datetime.date(2017, 3, 15)exercise_date6,182 -strike = 102.5strike7,225 -payer = Swaption(index, exercise_date, strike, strike_is_price = True)payer8,240 -receiver = Swaption(index, exercise_date, strike, "receiver", strike_is_price = True)receiver13,374 +pyisda/pyisda/cdsone.pyx,198 +def upfront_charge(date, value_date, benchmark_start_date, stepin_date,upfront_charge7,119 +def spread_from_upfront(date, value_date, benchmark_start_date, stepin_date,spread_from_upfront69,2760 -bbg_prices.py,1158 -engine = create_engine('postgresql://et_user@debian/ET')engine9,252 -fields_update = ["LN_ISSUE_STATUS", "AMT_OUTSTANDING", "PX_LAST","LAST_UPDATE_DT",fields_update11,310 - "AND not called", engine, index_col='cusip')cusips19,807 -securities = ["{0} Corp".format(cusip) for cusip in cusips.index]securities21,880 - data = retrieve_data(session, securities, fields_update)data24,989 -df = pd.DataFrame.from_dict(data, orient='index')df26,1051 -to_insert = df[['DEFAULTED', 'DEFAULT_DATE', 'CALLED', 'CALLED_DT', 'LN_ISSUE_STATUS', 'ID_BB_UNIQUE']]to_insert31,1256 -to_insert = to_insert.where(to_insert.notnull(), None)to_insert32,1360 -conn = engine.raw_connection()conn34,1416 -currentdata = pd.read_sql_query("SELECT id_bb_unique, pricingdate from bloomberg_corp",currentdata42,1806 - parse_dates=["pricingdate"],parse_dates44,1934 - index_col=['id_bb_unique', 'pricingdate'])index_col45,1995 -df = df.ix[df.index.difference(currentdata.index)]df49,2227 -to_insert = df[['ID_BB_UNIQUE','LAST_UPDATE_DT','PX_LAST','LN_CURRENT_MARGIN',to_insert53,2360 +pyisda/pyisda/utils.py,317 +import numpy as npnp22,516 +import xml.etree.ElementTree as ETET27,605 +def getMarkitIRData(getMarkitIRData32,709 +def rate_helpers(currency="USD", MarkitData=None):rate_helpers62,1932 +def YC(currency="USD", helpers=None, MarkitData=None):YC117,3629 +def build_yc(trade_date, ql_curve=False):build_yc124,3864 -sftp.py,469 -hostname="alias.im"hostname4,27 -port=22port5,47 -username="guillaume"username6,55 -t = paramiko.Transport((hostname, port))t9,115 -keys = paramiko.Agent().get_keys()keys10,156 -gkey = rsakeys[0]gkey12,246 -host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))host_keys13,264 -hostkey = host_keys[hostname]['ssh-rsa']hostkey14,347 -sftp = paramiko.SFTPClient.from_transport(t)sftp16,448 -dirlist = sftp.listdir('.')dirlist17,493 +pyisda/tests/test_pickle.py,236 +import numpy as npnp2,16 +class TestPickle(unittest.TestCase):TestPickle10,202 + def assertListAlmostEqual(self, l1, l2):assertListAlmostEqual14,329 + def test_yc(self):test_yc20,513 + def test_legs(self):test_legs27,780 -mark_swaptions.py,815 - level=logging.INFO,level13,295 - format='%(asctime)s %(message)s')format14,335 -def get_trades(date, engine):get_trades16,390 -def get_swaptionvol(index, series, strike, expiry, date, engine):get_swaptionvol25,830 -def mark_trades(date, engine):mark_trades47,1739 - parser = argparse.ArgumentParser()parser95,4033 - type = lambda s: pd.datetime.strptime(s, "%Y-%m-%d").date()),type97,4119 - dawn_engine = dbengine('dawndb')dawn_engine98,4205 - serenitas_engine = dbengine('serenitasdb')serenitas_engine99,4242 - args = parser.parse_args()args100,4289 - workdate = (pd.Timestamp.today()-BDay()).date()workdate102,4350 - workdate = args.workdateworkdate104,4416 - r = mark_trades(workdate, dawn_engine)r106,4450 +pyisda/docs/Makefile,1125 +SPHINXOPTS =SPHINXOPTS5,92 +SPHINXBUILD = sphinx-buildSPHINXBUILD6,108 +PAPER =PAPER7,137 +BUILDDIR = _buildBUILDDIR8,153 +PAPEROPT_a4 = -D latex_paper_size=a4PAPEROPT_a411,199 +PAPEROPT_letter = -D latex_paper_size=letterPAPEROPT_letter12,240 +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .ALLSPHINXOPTS13,285 +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .I18NSPHINXOPTS15,441 +help:help18,510 +clean:clean48,2155 +html:html52,2198 +dirhtml:dirhtml58,2351 +singlehtml:singlehtml64,2519 +pickle:pickle70,2693 +json:json76,2847 +htmlhelp:htmlhelp82,2997 +qthelp:qthelp89,3219 +applehelp:applehelp99,3614 +devhelp:devhelp108,3942 +epub:epub118,4239 +epub3:epub3124,4388 +latex:latex130,4542 +latexpdf:latexpdf138,4837 +latexpdfja:latexpdfja145,5082 +text:text152,5337 +man:man158,5486 +texinfo:texinfo164,5637 +info:info172,5932 +gettext:gettext179,6175 +changes:changes185,6345 +linkcheck:linkcheck191,6498 +doctest:doctest198,6723 +coverage:coverage204,6935 +xml:xml210,7146 +pseudoxml:pseudoxml216,7296 +dummy:dummy222,7473 -risk_insight/__init__.py,31 -app = Flask(__name__)app2,24 +pyisda/docs/conf.py,0 -risk_insight/views.py,353 -def get_attach_from_name(index_type, series):get_attach_from_name11,176 -def get_db():get_db28,714 -def close_connection(exception):close_connection37,1020 -def get_risk_numbers():get_risk_numbers43,1165 -def get_indices_quotes():get_indices_quotes63,2174 -def tranches():tranches95,3405 -def indices():indices102,3711 -def main():main106,3832 +pyisda/docs/index.rst,121 +Welcome to PyISDA's documentation!Welcome to PyISDA's documentation!6,217 +Indices and tablesIndices and tables16,337 -risk_insight/.ropeproject/config.py,90 -def set_prefs(prefs):set_prefs5,45 -def project_opened(project):project_opened110,4652 +pyisda/docs/api.rst,18 +PyISDAPyISDA1,0 -risk_insight/templates/index.html,0 +graphics.py,474 +import numpy as npnp1,0 +import matplotlib.pyplot as pltplt2,19 +def shiftedColorMap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'):shiftedColorMap10,238 +def plot_color_map(series, sort_order = [True,True], color_map=cm.RdYlGn, centered = True):plot_color_map61,1995 +def plot_prob_map(df, attr="pnl", path=".", color_map=cm.RdYlGn, index='IG'):plot_prob_map94,3197 +def plot_swaption_df(df, spread_shock, vol_shock, attr="pnl"):plot_swaption_df122,4267 -risk_insight/templates/tranches.html,0 +insert_index.py,0 -risk_insight/templates/indices.html,0 +bbg_prices.py,57 +import numpy as npnp3,101 +import pandas as pdpd4,120 -Dawn/__init__.py,325 -app = Flask(__name__)app8,152 -csrf = CSRFProtect(app)csrf10,205 -db = SQLAlchemy(app, metadata=MetaData(schema=app.config['SCHEMA']))db11,229 - fh = logging.FileHandler(filename=app.config['LOGFILE'])fh14,317 - formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')formatter16,408 +tests/test_cds.py,357 +import numpy as npnp7,190 +class TestUpfront(unittest.TestCase):TestUpfront16,399 + def test_upfront(self):test_upfront22,590 + def test_cdsone(self):test_cdsone25,680 + def test_annuity(self):test_annuity44,1722 +class TestSpreadCurve(unittest.TestCase):TestSpreadCurve49,1965 + def test_upfront_curves(self):test_upfront_curves51,2008 -Dawn/models.py,15182 -class Counterparties(db.Model):Counterparties11,309 - __tablename__ = 'counterparties'__tablename__12,341 - code = db.Column(db.String(12), primary_key=True)code13,378 - name = db.Column(db.String)name14,432 - city = db.Column(db.String)city15,464 - state = db.Column(db.String(2))state16,496 - dtc_number = db.Column(db.Integer)dtc_number17,532 - sales_contact = db.Column(db.String)sales_contact18,571 - sales_email = db.Column(EmailType)sales_email19,612 - sales_phone = db.Column(PhoneNumberType())sales_phone20,651 - valuation_contact1 = db.Column(db.String)valuation_contact121,698 - valuation_email1 = db.Column(EmailType)valuation_email122,744 - valuation_contact2 = db.Column(db.String)valuation_contact223,788 - valuation_email2 = db.Column(EmailType)valuation_email224,834 - valuation_contact3 = db.Column(db.String)valuation_contact325,878 - valuation_email3 = db.Column(EmailType)valuation_email326,924 - valuation_contact4 = db.Column(db.String)valuation_contact427,968 - valuation_email4 = db.Column(EmailType)valuation_email428,1014 - notes = db.Column(db.String)notes29,1058 - instructions = db.Column(db.String, info={'form_field_class': FileField})instructions30,1091 -class Accounts(db.Model):Accounts32,1170 - __tablename__ = 'accounts'__tablename__33,1196 - code = db.Column(db.String(5), primary_key=True)code34,1227 - name = db.Column(db.String)name35,1280 - custodian = db.Column(db.String)custodian36,1312 - cash_account = db.Column(db.String)cash_account37,1349 - counterparty = db.Column(db.String(12), db.ForeignKey('counterparties.code'))counterparty38,1389 -BOND_STRAT = ENUM('M_STR_MAV', 'M_STR_MEZZ', 'CSO_TRANCH',BOND_STRAT40,1472 -CDS_STRAT = ENUM('HEDGE_CSO', 'HEDGE_CLO', 'HEDGE_MAC', 'HEDGE_MBS',CDS_STRAT45,1760 -SWAPTION_STRAT = ENUM('IGPAYER', 'IGREC', 'HYPAYER', 'HYREC',SWAPTION_STRAT50,2069 - name='swaption_strat')name51,2131 -FUTURE_STRAT = ENUM('M_STR_MAV', 'M_MTG_IO', 'M_STR_MEZZ', 'M_MTG_RW', 'SER_ITRXCURVE',FUTURE_STRAT53,2177 - name='future_strat')name54,2265 -CASH_STRAT = ENUM('M_CSH_CASH', 'MBSCDSCSH', 'SER_IGCVECSH', 'SER_ITRXCVCSH', 'CSOCDSCSH',CASH_STRAT56,2307 - name='cash_strat')name59,2521 -SWAPTION_TYPE = ENUM('PAYER', 'RECEIVER',SWAPTION_TYPE61,2559 - name='swaption_type')name62,2601 -REPO_TYPE = ENUM('REPO', 'REVERSE REPO', name='repo_type')REPO_TYPE64,2645 -FUTURE_TYPE = ENUM('FUTURE', 'CFD', 'SYNTHETIC-FUTURE', 'LME-FORWARD', name='future_type')FUTURE_TYPE65,2704 -CALL_NOTICE = ENUM('24H', '48H', '3D', '4D', '5D', '6D',CALL_NOTICE67,2796 -ASSET_CLASS = ENUM('CSO', 'Subprime', 'CLO', 'Tranches', 'Futures', 'Cash', 'FX', 'Cleared',ASSET_CLASS70,2936 - name='asset_class')name71,3029 -ACTION = ENUM('NEW', 'UPDATE', 'CANCEL', name='action')ACTION72,3068 -CCY = ENUM('USD', 'CAD', 'EUR', 'YEN', name='currency')CCY74,3125 -BBG_TYPE = ENUM('Mtge', 'Corp', name='bbg_type')BBG_TYPE76,3182 -SWAP_TYPE = ENUM('CD_INDEX', 'CD_INDEX_TRANCHE', 'CD_BASKET_TRANCHE', 'ABS_CDS', name='swap_type')SWAP_TYPE78,3232 -ISDA = ENUM('ISDA2014', 'ISDA2003Cred', name='isda')ISDA80,3332 -DAY_COUNT = ENUM('ACT/360', 'ACT/ACT', '30/360', 'ACT/365', name='day_count')DAY_COUNT82,3386 -BUS_DAY_CONVENTION = ENUM('Modified Following', 'Following', 'Modified Preceding', 'Preceding',BUS_DAY_CONVENTION84,3465 -PROTECTION = ENUM('Buyer', 'Seller', name='protection')PROTECTION86,3650 -class BondDeal(db.Model):BondDeal88,3707 - __tablename__ = 'bonds'__tablename__89,3733 - id = db.Column('id', db.Integer, primary_key=True)id90,3761 - dealid = db.Column(db.String(28))dealid91,3816 - lastupdate = db.Column(db.DateTime, server_default=db.func.now(), onupdate=db.func.now())lastupdate92,3854 - action = db.Column(ACTION)action93,3948 - folder = db.Column(BOND_STRAT, nullable=False)folder94,3979 - custodian = db.Column(db.String(12), default='BAC', nullable=False)custodian95,4030 - cashaccount = db.Column(db.String(10), default='V0NSCLMAMB', nullable=False)cashaccount96,4102 - cp_code = db.Column(db.String(12), db.ForeignKey('counterparties.code'),cp_code97,4183 - info={'choices': [(None, '')],info98,4260 - trade_date = db.Column(db.Date, nullable = False)trade_date100,4387 - settle_date = db.Column(db.Date, nullable = False)settle_date101,4441 - cusip = db.Column(db.String(9), info={'validators': Length(9, 9),cusip102,4496 - isin = db.Column(db.String(12), info={'validators': Length(12, 12),isin105,4700 - identifier = db.Column(db.String(12), info={'filters': [lambda x: x or None,],identifier108,4906 - description = db.Column(db.String(32), nullable = False, info={'trim': True})description110,5052 - buysell = db.Column(db.Boolean, nullable = False, info={'choices':[(0, 'sell'), (1, 'buy')],buysell111,5134 - faceamount = db.Column(db.Float, nullable=False)faceamount114,5412 - price = db.Column(db.Float, nullable=False)price115,5465 - accrued = db.Column(db.Float, nullable = False)accrued116,5513 - asset_class = db.Column(ASSET_CLASS)asset_class117,5565 - ticket = db.Column(db.String, info={'form_field_class': FileField})ticket118,5606 - principal_payment = db.Column(db.Float)principal_payment119,5678 - accrued_payment = db.Column(db.Float)accrued_payment120,5722 - counterparty = db.relationship(Counterparties)counterparty121,5764 - __table_args__= (db.CheckConstraint('cusip is not Null or isin is not Null'),)__table_args__122,5815 -class CDSDeal(db.Model):CDSDeal124,5899 - __tablename__ = 'cds'__tablename__125,5924 - id = db.Column('id', db.Integer, primary_key=True)id126,5950 - dealid = db.Column(db.String(28))dealid127,6005 - lastupdate = db.Column(db.DateTime, server_default=db.func.now(), onupdate=db.func.now())lastupdate128,6043 - action = db.Column(ACTION)action129,6137 - folder = db.Column(CDS_STRAT, nullable=False)folder130,6168 - custodian = db.Column(db.String(12), default='SGFCM', nullable=False)custodian131,6218 - cashaccount = db.Column(db.String(10), default='SGNSCLMASW', nullable=False)cashaccount132,6292 - cp_code = db.Column(db.String(12), db.ForeignKey('counterparties.code'),cp_code133,6373 - info={'choices': [(None, '')],info134,6450 - trade_date = db.Column(db.Date, nullable=False)trade_date136,6577 - effective_date = db.Column(db.Date, nullable=False)effective_date137,6629 - maturity = db.Column(db.Date, nullable=False)maturity138,6685 - currency = db.Column(CCY, nullable=False)currency139,6735 - payment_rolldate = db.Column(BUS_DAY_CONVENTION, nullable=False)payment_rolldate140,6781 - notional = db.Column(db.Float, nullable=False)notional141,6850 - fixed_rate = db.Column(db.Float, nullable=False)fixed_rate142,6901 - day_count = db.Column(DAY_COUNT, nullable=False)day_count143,6954 - frequency = db.Column(db.SmallInteger, default=4, nullable=False)frequency144,7007 - protection = db.Column(PROTECTION, nullable=False)protection145,7077 - security_id = db.Column(db.String(12), nullable=False)security_id146,7132 - security_desc = db.Column(db.String(32), nullable=False)security_desc147,7191 - upfront = db.Column(db.Float, nullable=False)upfront148,7252 - upfront_settle_date = db.Column(db.Date, nullable=False)upfront_settle_date149,7302 - initial_margin_percentage = db.Column(db.Float)initial_margin_percentage150,7363 - swap_type = db.Column(SWAP_TYPE, nullable=False)swap_type151,7415 - attach = db.Column(db.SmallInteger, info={'min': 0, 'max':100})attach152,7468 - detach = db.Column(db.SmallInteger, info={'min': 0, 'max':100})detach153,7536 - clearing_facility = db.Column(db.String(12), default='ICE-CREDIT')clearing_facility154,7604 - isda_definition = db.Column(ISDA)isda_definition155,7675 - counterparty = db.relationship(Counterparties)counterparty156,7713 - "clearing_facility is NULL)"),)__table_args__159,7936 -class RepoDeal(db.Model):RepoDeal161,8010 - __tablename__ = 'repo'__tablename__162,8036 - id = db.Column('id', db.Integer, primary_key=True)id163,8063 - lastupdate = db.Column(db.DateTime, server_default=db.func.now(), onupdate=db.func.now())lastupdate164,8118 - action = db.Column(ACTION)action165,8212 - folder = db.Column(CDS_STRAT, nullable=False)folder166,8243 - custodian = db.Column(db.String(12), default='SGFCM', nullable=False)custodian167,8293 - cashaccount = db.Column(db.String(10), default='SGNSCLMASW', nullable=False)cashaccount168,8367 - cp_code = db.Column(db.String(12), db.ForeignKey('counterparties.code'),cp_code169,8448 - info={'choices': [(None, '')],info170,8525 - trade_date = db.Column(db.Date, nullable=False)trade_date172,8652 - settle_date = db.Column(db.Date, nullable=False)settle_date173,8704 - cusip = db.Column(db.String(9), info={'validators': Length(9,9),cusip174,8757 - isin = db.Column(db.String(12), info={'validators': Length(12, 12),isin177,8960 - identifier = db.Column(db.String(12), info={'filters': [lambda x: x or None,],identifier180,9166 - description = db.Column(db.String(32), nullable=False, info={'trim': True})description182,9312 - transation_indicator = db.Column(REPO_TYPE)transation_indicator183,9392 - faceamount = db.Column(db.Float, nullable=False)faceamount184,9440 - price = db.Column(db.Float, nullable=False)price185,9493 - currency = db.Column(CCY, nullable=False)currency186,9541 - expiration_date = db.Column(db.Date)expiration_date187,9587 - weighted_amount = db.Column(db.Float)weighted_amount188,9628 - haircut = db.Column(db.Float)haircut189,9670 - repo_rate = db.Column(db.Float, nullable=False)repo_rate190,9704 - call_notice = db.Column(CALL_NOTICE)call_notice191,9756 - daycount = db.Column(DAY_COUNT)daycount192,9797 - ticket = db.Column(db.String, info={'form_field_class': FileField})ticket193,9833 - "haircut is NULL and weighted_amount is NOT NULL)"),__table__args195,10002 -class SwaptionDeal(db.Model):SwaptionDeal198,10178 - __tablename__ = 'swaptions'__tablename__199,10208 - id = db.Column('id', db.Integer, primary_key=True)id200,10240 - dealid = db.Column(db.String(28))dealid201,10295 - lastupdate = db.Column(db.DateTime, server_default=db.func.now(), onupdate=db.func.now())lastupdate202,10333 - action = db.Column(ACTION)action203,10427 - folder = db.Column(SWAPTION_STRAT, nullable=False)folder204,10458 - custodian = db.Column(db.String(12), default='NONE', nullable=False)custodian205,10513 - cashaccount = db.Column(db.String(10), default='SGNSCLMASW', nullable=False)cashaccount206,10586 - cp_code = db.Column(db.String(12), db.ForeignKey('counterparties.code'),cp_code207,10667 - info={'choices': [(None, '')],info208,10744 - trade_date = db.Column(db.Date, nullable=False)trade_date210,10871 - settle_date = db.Column(db.Date, nullable=False)settle_date211,10923 - buysell = db.Column(db.Boolean, nullable=False, info={'choices':[(0, 'sell'), (1, 'buy')],buysell212,10976 - notional = db.Column(db.Float, nullable=False)notional215,11250 - swaption_type = db.Column(SWAPTION_TYPE, nullable=False)swaption_type216,11301 - strike = db.Column(db.Float, nullable=False)strike217,11362 - price = db.Column(db.Float, nullable=False)price218,11411 - expiration_date = db.Column(db.Date, nullable=False)expiration_date219,11459 - initial_margin_percentage = db.Column(db.Float)initial_margin_percentage220,11516 - index_ref = db.Column(db.Float)index_ref221,11568 - security_id = db.Column(db.String(12), nullable=False)security_id222,11604 - security_desc = db.Column(db.String(32), nullable=False)security_desc223,11663 - fixed_rate = db.Column(db.Float, nullable=False)fixed_rate224,11724 - maturity = db.Column(db.Date, nullable=False)maturity225,11777 - currency = db.Column(CCY, nullable=False)currency226,11827 - counterparty = db.relationship(Counterparties)counterparty227,11873 -class FutureDeal(db.Model):FutureDeal229,11925 - __tablename__ = 'futures'__tablename__230,11953 - id = db.Column('id', db.Integer, primary_key=True)id231,11983 - dealid = db.Column(db.String(28))dealid232,12038 - lastupdate = db.Column(db.DateTime, server_default=db.func.now(), onupdate=db.func.now())lastupdate233,12076 - action = db.Column(ACTION)action234,12170 - folder = db.Column(FUTURE_STRAT, nullable=False)folder235,12201 - custodian = db.Column(db.String(12), default='INTBR', nullable=False)custodian236,12254 - cashaccount = db.Column(db.String(10), default='IANSCLMAFU', nullable=False)cashaccount237,12328 - cp_code = db.Column(db.String(12), db.ForeignKey('counterparties.code'),cp_code238,12409 - info={'choices': [('IBKRNY', 'Interactive Brokers')],info239,12486 - trade_date = db.Column(db.Date, nullable=False)trade_date241,12636 - settle_date = db.Column(db.Date, nullable=False)settle_date242,12688 - buysell = db.Column(db.Boolean, nullable=False, info={'choices':[(0, 'sell'), (1, 'buy')],buysell243,12741 - bbg_ticker = db.Column(db.String(32), nullable=False)bbg_ticker246,13015 - quantity = db.Column(db.Float, nullable=False)quantity247,13073 - price = db.Column(db.Float, nullable=False)price248,13124 - commission = db.Column(db.Float)commission249,13172 - swap_type = db.Column(FUTURE_TYPE, nullable=False)swap_type250,13209 - security_desc = db.Column(db.String(32), nullable=False)security_desc251,13264 - maturity = db.Column(db.Date, nullable=False)maturity252,13325 - currency = db.Column(CCY, nullable=False)currency253,13375 - exchange = db.Column(db.String(3), default='CME', nullable=False)exchange254,13421 - counterparty = db.relationship(Counterparties)counterparty255,13491 -class CashFlowDeal(db.Model):CashFlowDeal257,13543 - __tablename__ = 'wires'__tablename__258,13573 - id = db.Column('id', db.Integer, primary_key=True)id259,13601 - dealid = db.Column(db.String(28))dealid260,13656 - lastupdate = db.Column(db.DateTime, server_default=db.func.now(), onupdate=db.func.now())lastupdate261,13694 - action = db.Column(ACTION)action262,13788 - folder = db.Column(CASH_STRAT, nullable=False)folder263,13819 - code = db.Column(db.String(5), db.ForeignKey('accounts.code'), nullable=False)code264,13870 - amount = db.Column(db.Float, nullable=False)amount265,13953 - currency = db.Column(CCY, nullable=False)currency266,14002 - trade_date = db.Column(db.Date, nullable=False)trade_date267,14048 - account = db.relationship(Accounts)account268,14100 -BaseModelForm = model_form_factory(FlaskForm)BaseModelForm270,14141 -class ModelForm(BaseModelForm):ModelForm271,14187 - def get_session(self):get_session273,14236 +tests/test_tranche_basket.py,320 +import numpy as npnp4,85 +class TestPickle(unittest.TestCase):TestPickle8,120 + def test_pickle(self):test_pickle11,207 + def test_pv(self):test_pv15,343 +class TestTopDown(unittest.TestCase):TestTopDown19,426 + def test_bottomup(self):test_bottomup25,656 + def test_topdown(self):test_topdown30,852 -Dawn/views.py,2767 -fed_cal = get_calendar('USFederalHolidayCalendar')fed_cal27,754 -bond_cal = HolidayCalendarFactory('BondCalendar', fed_cal, GoodFriday)bond_cal28,805 -bus_day = CustomBusinessDay(calendar=bond_cal())bus_day29,876 -def cp_choices(kind='bond'):cp_choices31,926 -def account_codes():account_codes43,1403 -def get_queue():get_queue46,1512 -def get_db():get_db56,1813 -def close_connection(exception):close_connection65,2119 -class CounterpartyForm(ModelForm):CounterpartyForm70,2234 - class Meta:Meta71,2269 - model = Counterpartiesmodel72,2285 - include_primary_keys = Trueinclude_primary_keys73,2316 -class BondForm(ModelForm):BondForm75,2353 - upload_globeop = BooleanField(label="Upload to globeop?")upload_globeop76,2380 - class Meta:Meta77,2442 - model = BondDealmodel78,2458 - include_foreign_keys = Trueinclude_foreign_keys79,2483 - exclude = ['dealid', 'lastupdate', #we generate it with a trigger at the server levelexclude80,2519 -class CDSForm(ModelForm):CDSForm83,2673 - upload_globeop = BooleanField(label="Upload to globeop?")upload_globeop84,2699 - class Meta:Meta85,2761 - model = CDSDealmodel86,2777 - include_foreign_keys = Trueinclude_foreign_keys87,2801 - exclude = ['dealid', 'lastupdate']exclude88,2837 -class SwaptionForm(ModelForm):SwaptionForm90,2881 - upload_globeop = BooleanField(label="Upload to globeop?")upload_globeop91,2912 - class Meta:Meta92,2974 - model = SwaptionDealmodel93,2990 - include_foreign_keys = Trueinclude_foreign_keys94,3019 - exclude = ['dealid', 'lastupdate']exclude95,3055 -class FutureForm(ModelForm):FutureForm97,3099 - upload_globeop = BooleanField(label="Upload to globeop?")upload_globeop98,3128 - class Meta:Meta99,3190 - model = FutureDealmodel100,3206 - include_foreign_keys = Trueinclude_foreign_keys101,3233 - exclude = ['dealid', 'lastupdate']exclude102,3269 -def get_deal(kind):get_deal104,3313 -def _get_form(kind):_get_form116,3596 -def get_form(trade, kind):get_form128,3880 -def get_wire_form(wire):get_wire_form153,4819 -def get_trade(tradeid, kind):get_trade161,5011 -def save_ticket(trade, old_ticket_name):save_ticket165,5126 -def split_direction(g, direction):split_direction178,5610 -def gen_cashflow_deals(form, session, wire_id=None):gen_cashflow_deals190,6170 -def wire_manage(wire_id):wire_manage221,7514 -def trade_manage(tradeid, kind):trade_manage260,9590 -def list_trades(kind):list_trades296,11024 -def download_ticket(tradeid):download_ticket305,11329 -def list_counterparties(instr):list_counterparties318,11843 -def edit_counterparty(cpcode):edit_counterparty329,12370 -def get_bbg_id():get_bbg_id355,13280 +tests/test_upfront_cds.py,263 +import pandas as pdpd13,777 +import numpy as npnp21,1008 +def snac_pv(spread, term_date, fixed_coupon=0.01, recovery=0.4, ts=YC()):snac_pv23,1028 +def jpmorgan_curves(trade_date, value_date, start_date, end_date, spread, recovery=0.4):jpmorgan_curves45,2470 -Dawn/.ropeproject/config.py,90 -def set_prefs(prefs):set_prefs5,45 -def project_opened(project):project_opened110,4652 +tests/test_cms_spread.py,350 +import numpy as npnp3,28 +class TestCmsSpread(unittest.TestCase):TestCmsSpread24,872 + def setUp(self):setUp26,913 + def test_black_model(self):test_black_model78,3182 + def test_h1_hcall(self):test_h1_hcall91,3903 + def test_scipy_integrate(self):test_scipy_integrate101,4301 + def test_CmsSpread(self):test_CmsSpread108,4657 -Dawn/templates/swaption_blotter.html,0 +tests/test_yieldcurve.py,207 +class TestYieldCurve(unittest.TestCase):TestYieldCurve10,233 + def assertListAlmostEqual(self, list1, list2, places = 7):assertListAlmostEqual12,275 + def test_bloomberg(self):test_bloomberg17,476 -Dawn/templates/wire_blotter.html,0 +tests/test_sabr_quantlib.py,28 +import numpy as npnp5,237 -Dawn/templates/trade_entry.html,0 +tests/test_index.py,626 +import numpy as npnp3,32 +class TestPickle(unittest.TestCase):TestPickle13,235 + def test_pickle(self):test_pickle18,400 + def test_pickle_basket(self):test_pickle_basket22,532 + def test_from_tradeid(self):test_from_tradeid26,719 +class TestStrike(unittest.TestCase):TestStrike31,841 + def test_pv(self):test_pv37,1060 + def test_strike(self):test_strike42,1277 + def test_price_setting(self):test_price_setting51,1722 +class TestForwardIndex(unittest.TestCase):TestForwardIndex56,1856 + def test_forward_pv(self):test_forward_pv64,2149 + def test_forward_pv(self):test_forward_pv70,2449 -Dawn/templates/wire_entry.html,0 +tests/test_scenarios.py,166 +import numpy as npnp2,16 +import pandas as pdpd3,35 +class TestSenarios(unittest.TestCase):TestSenarios12,344 + def test_portfolio(self):test_portfolio20,779 -Dawn/templates/edit_cp.html,0 +tests/test_swap_index.py,107 +class UsdLiborSwap(unittest.TestCase):UsdLiborSwap8,176 + def test_creation(self):test_creation9,215 -Dawn/templates/base.html,0 +tests/test_swaption.py,539 +class TestPutCallParity(unittest.TestCase):TestPutCallParity10,157 + def test_parity(self):test_parity17,394 + def test_parity_black(self):test_parity_black27,905 + def test_calibration(self):test_calibration37,1432 + def test_hy(self):test_hy45,1707 +class TestBreakeven(unittest.TestCase):TestBreakeven55,2093 + def test_hypayer(self):test_hypayer68,2493 + def test_hyreceiver(self):test_hyreceiver74,2726 + def test_igpayer(self):test_igpayer81,3014 + def test_igreceiver(self):test_igreceiver87,3239 -Dawn/templates/cds_blotter.html,0 +tests/test_dates.py,1009 +import pandas as pdpd3,32 + roll_date as roll_date_c,roll_date_c11,203 + cds_accrued as cds_accrued_c,cds_accrued_c12,233 +class TestStartDate(unittest.TestCase):TestStartDate20,368 + def test_previous_twentieth(self):test_previous_twentieth21,408 + def test_previous_twentieth_timestamp(self):test_previous_twentieth_timestamp42,1210 +class TestEndDate(unittest.TestCase):TestEndDate57,1755 + def test_enddate(self):test_enddate58,1793 + def test_enddate_pre2015(self):test_enddate_pre201572,2294 +class TestEndDateC(unittest.TestCase):TestEndDateC93,3041 + def test_enddate(self):test_enddate94,3080 + def test_enddate_pre2015(self):test_enddate_pre2015108,3589 +class TestCdsAccrued(unittest.TestCase):TestCdsAccrued129,4348 + def test_cdsaccrued(self):test_cdsaccrued130,4389 + def test_cdsaccrued_c(self):test_cdsaccrued_c145,4948 +class TestDaysAccrued(unittest.TestCase):TestDaysAccrued161,5537 + def test_days_accrued(self):test_days_accrued162,5579 -Dawn/templates/bond_blotter.html,0 +tests/.ropeproject/config.py,90 +def set_prefs(prefs):set_prefs5,45 +def project_opened(project):project_opened120,4706 -Dawn/templates/future_blotter.html,0 +tests/__init__.py,0 -Dawn/templates/counterparties.html,0 +Dawn/templates/cds_blotter.html,0 -Dawn/utils.py,89 -def bump_rev(filename):bump_rev6,66 -def simple_serialize(obj):simple_serialize12,308 +Dawn/templates/bond_blotter.html,0 -trade_template.py,234 -default = "\underline{\hspace{1cm}}"default3,29 -checked = "\underline{\hspace{0.35cm}X\hspace{0.35cm}}"checked4,66 -d = {}d5,122 - texfile = Template(fh.read())texfile29,887 - texfile = texfile.substitute(d)texfile30,921 +Dawn/templates/base.html,0 -dates.py,567 -fed_cal = get_calendar('USFederalHolidayCalendar')fed_cal9,259 -bond_cal = HolidayCalendarFactory('BondCalendar', fed_cal, GoodFriday)bond_cal10,310 -bus_day = CustomBusinessDay(calendar=bond_cal())bus_day11,381 -def imm_dates(start_date, end_date):imm_dates13,431 -def previous_twentieth(d):previous_twentieth21,771 -def days_accrued(tradedate):days_accrued30,986 -def isleapyear(date):isleapyear40,1431 -def yearfrac(date1, date2, daycount):yearfrac43,1539 -class TestDaysAccrued(unittest.TestCase):TestDaysAccrued60,2081 - def test(self):test61,2123 +Dawn/templates/edit_cp.html,0 -bbg_newids.py,1671 -engine = create_engine('postgresql://et_user@debian/ET')engine7,220 -meta = MetaData(bind=engine)meta8,277 -deal_indicative = meta.tables['deal_indicative']deal_indicative11,388 -bloomberg_corp_ref = meta.tables['bloomberg_corp_ref']bloomberg_corp_ref12,438 -bloomberg_corp = meta.tables['bloomberg_corp']bloomberg_corp13,493 - select_from(func.et_latestdealinfo(bindparam('dealname'))).where(Column('cusip')!=None)s16,592 -result = select([deal_indicative.c.dealname]).execute()result19,782 -d = defaultdict(set)d20,838 - result2 = engine.execute(s, dealname = r.dealname)result222,876 -clean_mapping = ((cusip, loanxid - {None}) for cusip, loanxid in d.items())clean_mapping26,988 -def f(s):f28,1065 -clean_mapping = {cusip: f(loanxid) for cusip, loanxid in clean_mapping}clean_mapping34,1152 -mapping = pd.DataFrame.from_dict(clean_mapping, orient='index')mapping35,1224 -currentdata = pd.read_sql_query("select id_bb_unique, cusip from bloomberg_corp_ref",currentdata38,1347 -mapping = mapping.ix[mapping.index.difference(currentdata.index)]mapping40,1492 -df = pd.DataFrame.from_dict(df, orient='index')df51,2202 -df = df.ix[df.index.difference(currentdata.index)]df60,2670 -sql_colnames = [c.name for c in bloomberg_corp_ref.columns]sql_colnames61,2721 -pd_colnames = ['ID_BB_UNIQUE', 'ID_CUSIP', 'ISSUER', 'MATURITY', 'CPN', 'CPN_TYP',pd_colnames62,2781 -to_insert = df.filter(pd_colnames)to_insert66,3127 -pd_colnames = ['ID_BB_UNIQUE','LAST_UPDATE_DT','PX_LAST','LN_CURRENT_MARGIN',pd_colnames70,3333 -sql_colnames = [c.name for c in bloomberg_corp.columns]sql_colnames72,3462 -to_insert2 = df.filter(pd_colnames)to_insert273,3518 +Dawn/templates/future_blotter.html,0 -process_queue.py,1414 -HEADERS = {'bond_trades': [HEADERS25,531 -def get_effective_date(d):get_effective_date101,5942 -def get_trades(q, queue_name='bond_trades'):get_trades104,6032 -def rename_keys(d, mapping):rename_keys122,6684 -def build_line(obj, queue_name='bond_trades'):build_line128,6865 -def get_bbg_data(conn, session, identifier, cusip=None, isin = None, settle_date = None, asset_class=None,get_bbg_data236,12001 -def bond_trade_process(conn, session, trade):bond_trade_process291,14889 -def cds_trade_process(serenitasdb, dawndb, session, trade):cds_trade_process317,15994 -def generate_csv(l, queue_name='bond_trades'):generate_csv332,16604 -def get_filename(timestamp, queue_name):get_filename343,16961 -def upload_file(timestamp, queue_name='bond_trades'):upload_file351,17287 -def write_buffer(buf, queue_name='bond_trades'):write_buffer363,17769 -def email_subject(trade):email_subject373,18159 -def print_trade(trade):print_trade377,18399 - parser = argparse.ArgumentParser()parser383,18573 - args = parser.parse_args()args385,18711 - q = get_redis_queue()q386,18742 - serenitasdb = dbconn('serenitasdb')serenitasdb387,18768 - dawndb = dbconn('dawndb')dawndb388,18808 - list_trades = get_trades(q, queue_name)list_trades390,18936 - buf = generate_csv(list_trades, queue_name)buf401,19452 - timestamp = write_buffer(buf, queue_name)timestamp402,19508 +Dawn/templates/capfloor_blotter.html,0 -task_server/__init__.py,320 -app = Flask(__name__)app2,24 -fh = logging.FileHandler(filename=os.path.join(os.environ["LOG_DIR"], 'tasks.log'))fh7,96 -formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')formatter8,180 -loggers = [logging.getLogger('intex'), app.logger, logging.getLogger(__name__)]loggers11,294 +Dawn/templates/trade_entry.html,179 + <datalist id="index_list"></datalist>index_list8,235 + <input id="upload_globeop" name="upload_globeop" type="checkbox" value="y">Upload upload_globeop31,1113 -task_server/insert_tranche_quotes.py,658 -logger = logging.getLogger(__name__)logger8,160 -engine = create_engine('postgresql://serenitas_user@debian/serenitasdb')engine10,198 -metadata = MetaData(bind = engine)metadata11,271 -quotes = Table('tranche_quotes', metadata, autoload = True)quotes12,306 -ins = quotes.insert()ins13,366 -def convert(x):convert15,389 -def convert_int(x):convert_int24,581 -tenordict = {'3': '3yr', '5': '5yr', '7':'7yr', '10':'10yr'}tenordict33,780 -runningdict1 = {0: 500, 3:100, 7:100, 15: 25}runningdict134,841 -runningdict2 = {0: 500, 3:500, 7:500, 10:100, 15:100, 30:100}runningdict235,887 -def insert_quotes(year=2016, quote_dir=None):insert_quotes37,950 +Dawn/templates/wire_blotter.html,0 -task_server/rest.py,238 -def get_db():get_db11,283 -def get_queue():get_queue20,584 -def close_db(error):close_db27,768 -def intex():intex34,948 -def globeop():globeop40,1116 -def insert_tranches():insert_tranches46,1364 -def run_tasks():run_tasks51,1475 +Dawn/templates/wire_entry.html,996 + <select class="form-control" id="action" name="action">action15,505 + <fieldset id="outgoing">outgoing31,1159 + <fieldset id="incoming">incoming34,1250 + <input class="form-control" id="trade_date" name="trade_date" value="{{trade_date}}" ttrade_date47,1562 + <input class="form-control" id="csrf_token" name="csrf_token" value="{{csrf_token()}}"csrf_token54,1763 + <input id="upload_globeop" name="upload_globeop" value="y" type="checkbox">Upload upload_globeop63,2036 + <template id="fragment">fragment74,2400 + <select class="form-control" id="folder" name="folder">folder80,2585 + <select class="form-control" id="code" name="code">code96,3025 + <input class="form-control" id="amount" name="amount" value="" type="text">amount110,3452 + <select class="form-control" id="currency" name="currency">currency116,3707 + <input id="btn" type="button" class="btn" value="+">btn123,3964 -task_server/__main__.py,565 - level=logging.INFO,level9,224 - format='%(asctime)s %(message)s')format10,264 -parser = argparse.ArgumentParser()parser12,319 -group = parser.add_mutually_exclusive_group(required=True)group13,354 - help="download reports from GlobeOp")help17,576 - help="upload marks to GlobeOp")help19,692 - default=datetime.datetime.today())default21,841 -args = parser.parse_args()args22,896 - engine = create_engine('postgresql://dawn_user@debian/dawndb')engine27,996 +Dawn/templates/counterparties.html,0 -task_server/.ropeproject/config.py,90 -def set_prefs(prefs):set_prefs5,45 -def project_opened(project):project_opened110,4652 +Dawn/templates/spot_blotter.html,0 -task_server/config.py,330 -ftp_password = 'B6#dEu7V'ftp_password1,0 -key_password = 'Serenitas;1'key_password2,27 -gmail_password = 'dweeks314'gmail_password3,57 -gmail_login = 'david.weeks@serenitascapital.com'gmail_login4,87 -markit_password = 'Welcome3!'markit_password5,137 -markit_login = 'guillaume.horel@serenitascapital.com'markit_login6,168 +Dawn/templates/swaption_blotter.html,0 -task_server/globeop.py,619 -logger = logging.getLogger(__name__)logger15,263 -def get_ped(s):get_ped23,412 -def key_fun(s):key_fun33,725 -def run_date(s):run_date43,1042 -def get_ftp(folder):get_ftp50,1240 -def get_gpg():get_gpg56,1383 -def convert_to_csv(f):convert_to_csv65,1743 -def download_data(workdate):download_data71,1954 -def insert_todb(workdate):insert_todb120,4076 -def upload_bond_marks(engine, workdate):upload_bond_marks140,5075 -def upload_cds_marks(engine, workdate):upload_cds_marks152,5683 -def upload_data(engine, workdate):upload_data164,6298 -def back_fill(start_date=pd.datetime(2017,7,20)):back_fill168,6417 +Dawn/models.py,582 +class Counterparties(db.Model):Counterparties11,278 +class Accounts(db.Model):Accounts33,1140 +class BondDeal(db.Model):BondDeal235,5000 +class CDSDeal(db.Model):CDSDeal294,7143 +class RepoDeal(db.Model):RepoDeal372,10726 +class SwaptionDeal(db.Model):SwaptionDeal431,12904 +class FutureDeal(db.Model):FutureDeal488,15278 +class CashFlowDeal(db.Model):CashFlowDeal528,16918 +class SpotDeal(db.Model):SpotDeal544,17531 +class CapFloorDeal(db.Model):CapFloorDeal574,18827 +class ModelForm(BaseModelForm):ModelForm654,22090 + def get_session(self):get_session656,22139 -parse_gs.py,2375 -data_dir = "/home/share/guillaume/swaptions"data_dir6,52 -all_df = {}all_df7,97 -fwd_index = []fwd_index8,109 - full_path = os.path.join(data_dir, index + " swaptions")full_path10,151 - flag = Falseflag13,342 - masterdf = {}masterdf14,367 - line = line.decode('utf-8', 'ignore')line16,421 - line = line.rstrip()line17,475 - m = re.search("(IG|HY)(\d{2}) 5y (?:.*)SWAPTION (?:UPDATE|CLOSES|CLOSE) - Ref\D+(.+)$", line)m18,512 - indextype = m.groups()[0]indextype20,644 - series = int(m.groups()[1])series21,690 - refspread = float(m.groups()[2])refspread26,972 - quotedate = pd.to_datetime(line[4:])quotedate29,1100 - m = re.match("Expiry (\d{2}\w{3}\d{2}) \((?:([\S]+) )?([\S]+)\)", line)m32,1232 - date = pd.to_datetime(date, format='%d%b%y')date35,1411 - flag = Trueflag38,1552 - r = []r39,1584 - vals = re.sub(" +", " ", line).split(" ")vals43,1694 - cols = ['Strike', 'Sprd', 'Pay', 'DeltaPay', 'Rec', 'Vol',cols54,2136 - cols = ['Strike', 'Pay', 'DeltaPay', 'Rec', 'Vol',cols57,2317 - df = pd.DataFrame.from_records(r, columns = cols)df59,2460 - d = {'quotedate': quotedate,d67,2961 - flag = Falseflag79,3521 - r = []r80,3558 -all_df = pd.concat(all_df, names = ['quotedate', 'index', 'series'])all_df83,3709 -index_df = pd.DataFrame(fwd_index)index_df86,3845 -all_df = all_df.rename(columns={'Strike':'strike',all_df89,3914 -index_df = index_df.drop_duplicates(['quotedate', 'index', 'series', 'expiry'])index_df101,4450 -serenitasdb = dbengine('serenitasdb')serenitasdb105,4571 -conn = serenitasdb.raw_connection()conn106,4609 - "ON CONFLICT DO NOTHING"format_str108,4710 -cols = index_df.columnscols109,4748 -sqlstr = format_str.format(",".join(cols), ",".join(["%s"] * len(cols)))sqlstr110,4772 -format_str = "INSERT INTO swaption_quotes({}) VALUES({}) ON CONFLICT DO NOTHING"format_str116,4946 -cols = all_df.columnscols117,5027 -sqlstr = format_str.format(",".join(cols), ",".join(["%s"] * len(cols)))sqlstr118,5049 +Dawn/views.py,1783 +import pandas as pdpd3,26 +def cp_choices(kind="bond"):cp_choices53,1030 +def account_codes():account_codes68,1522 +def fcm_accounts():fcm_accounts72,1632 +def get_queue():get_queue80,1812 +def get_db():get_db91,2114 +def close_connection(exception):close_connection101,2355 +class CounterpartyForm(ModelForm):CounterpartyForm107,2471 + class Meta:Meta108,2506 +class BondForm(ModelForm):BondForm113,2591 + class Meta:Meta116,2681 +class CDSForm(ModelForm):CDSForm127,2955 + class Meta:Meta130,3044 +class SwaptionForm(ModelForm):SwaptionForm147,3423 + class Meta:Meta150,3517 +class FutureForm(ModelForm):FutureForm163,3805 + class Meta:Meta166,3897 +class SpotForm(ModelForm):SpotForm172,4021 + class Meta:Meta175,4111 +class CapFloorForm(ModelForm):CapFloorForm181,4233 + class Meta:Meta184,4327 +def get_deal(kind):get_deal197,4615 +def _get_form(kind):_get_form216,5067 +def get_form(trade, kind):get_form233,5458 +def get_trade(tradeid, kind):get_trade278,7072 +def save_ticket(trade, old_ticket_name):save_ticket283,7188 +def save_confirm(trade, old_confirm):save_confirm295,7584 +def split_direction(g, direction):split_direction305,7938 +def gen_cashflow_deals(form, session, wire_id=None):gen_cashflow_deals334,8715 + to_date = lambda s: datetime.datetime.strptime(s, "%Y-%m-%d")to_date335,8768 +def wire_manage(wire_id):wire_manage373,10168 +def trade_manage(tradeid, kind):trade_manage418,12016 +def list_trades(kind):list_trades475,14015 +def download_ticket(tradeid):download_ticket490,14496 +def download_confirm(tradeid):download_confirm503,14913 +def list_counterparties(instr):list_counterparties513,15262 +def edit_counterparty(cpcode):edit_counterparty527,15767 +def get_bbg_id():get_bbg_id557,16692 -experiments/test_matrix.py,727 -openblas_lib = ctypes.cdll.LoadLibrary(find_library('openblas'))openblas_lib8,150 -def get_num_threads():get_num_threads10,216 -def set_num_threads(n):set_num_threads13,291 -seed = 1234seed16,366 -N = 1000000N19,400 -p = 100p20,412 -X = np.random.random(N * p).reshape((N, p), order='F')X21,420 -XT = X.T.copy()XT22,475 -true_value=33334547.40257686true_value23,491 -old_num_threads = get_num_threads()old_num_threads25,559 -def test():test26,595 -def test2():test230,692 -def test3():test334,815 -t = timeit.timeit(test, number=5)t38,912 -t = timeit.timeit(test2, number=5)t41,1030 -t = timeit.timeit(test3, number=5)t44,1155 -t = timeit.timeit(test, number=5)t48,1299 - def test_dask():test_dask55,1521 +Dawn/.ropeproject/config.py,90 +def set_prefs(prefs):set_prefs5,45 +def project_opened(project):project_opened120,4706 -experiments/test_timestamptz.py,418 -engine = dbengine('serenitasdb')engine3,44 -df1 = pd.read_sql_query("SELECT date FROM test", engine)df15,78 -df2 = pd.read_sql_query("SELECT date FROM test WHERE date<='2014-10-17'",df27,136 -df2bis = pd.read_sql_query("SELECT date FROM test WHERE date<='2014-10-17'",df2bis9,242 -df3 = pd.read_sql_query("SELECT date FROM test", engine,df311,376 - parse_dates=['date'])parse_dates12,433 +Dawn/config.ini,618 +SQLALCHEMY_DATABASE_URI = 'postgresql://dawn_user:Serenitas2@debian/dawndb'SQLALCHEMY_DATABASE_URI2,70 +SQLALCHEMY_TRACK_MODIFICATIONS = FalseSQLALCHEMY_TRACK_MODIFICATIONS3,146 +TICKETS_FOLDER = '/home/serenitas/Daily/tickets'TICKETS_FOLDER5,209 +CONFIRMS_FOLDER = '/home/serenitas/Daily/confirms'CONFIRMS_FOLDER6,258 +CP_FOLDER = '/home/serenitas/Daily/counterparties'CP_FOLDER7,309 +SECRET_KEY = 'papa'SECRET_KEY8,360 +LOGFILE = '/home/serenitas/CorpCDOs/logs/dawn-ziggy.log'LOGFILE9,380 +DEBUG = FalseDEBUG10,437 +SEND_FILE_MAX_AGE_DEFAULT = 60SEND_FILE_MAX_AGE_DEFAULT11,451 +SCHEMA = NoneSCHEMA13,497 -experiments/test_async.py,157 -async def pomme():pomme3,16 -async def poire():poire8,106 -async def main():main13,196 -async def ping(msg):ping18,275 -async def pong(msg):pong26,416 +Dawn/static/dawn.css,16 +body {body1,0 -experiments/test_trace.py,359 -df = pd.read_clipboard(header=None)df5,101 -trace_data = {}trace_data6,137 - security = "{}@TRAC Mtge".format(cusip)security9,228 - start_date=datetime.datetime(2016, 5, 22, 12, 42),start_date11,337 - end_date=datetime.datetime(2017, 5, 22, 18, 42))end_date12,430 +Dawn/__init__.py,0 -experiments/test_dask.py,721 -strip_percent = lambda s: float(s.rstrip('%'))/100 if s else np.nanstrip_percent4,48 -tenors = ['6m'] + [f'{y}y' for y in [1, 2, 3, 4, 5, 7, 10, 15, 20, 30]]tenors5,116 - for t in tenors}converters8,233 -dtype = {'Rating' + t: 'object' for t in tenors}dtype10,303 -df = dd.read_csv("/home/guillaume/composites/*.csv",df14,483 - skiprows=2,skiprows15,536 - converters=converters,converters16,556 - dtype=dtype,dtype17,587 - parse_dates=['Date'])parse_dates18,608 - ["Rating" + t for t in tenors]to_categorize22,802 -df = df.categorize(columns=to_categorize, index=False)df23,841 -df = df.set_index("Date")df24,896 -df = df.repartition(npartitions=100)df25,922 +Dawn/utils.py,99 +def bump_rev(filename):bump_rev5,37 +def simple_serialize(obj, **kwargs):simple_serialize12,268 -experiments/.ropeproject/config.py,90 -def set_prefs(prefs):set_prefs5,45 -def project_opened(project):project_opened110,4652 +bbg_cds_quotes.py,61 +def build_tuple(k, v, workdate, source):build_tuple32,1139 -experiments/test_basket.py,138 -ig29 = TrancheBasket("IG", 29, "5yr", trade_date=pd.Timestamp.today().normalize() - BDay())ig294,96 -df = ig29.tranche_deltas()df8,220 +backfill_ref.py,0 -experiments/test_asyncpg.py,235 -async def dbconn():dbconn10,178 -async def get_singlenames_quotes_async(con, indexname, date):get_singlenames_quotes_async16,388 -async def get_curves(con, currency="USD", date=None):get_curves24,738 -async def main():main29,1022 +client.py,21 +def run():run9,155 -experiments/exchange_example.py,369 -credentials = Credentials(username='LEEMUNDER\\ghorel', password='')credentials3,46 -config = Configuration(server='autodiscover.lmcg.com', credentials=credentials)config4,115 -account = Account(primary_smtp_address='ghorel@lmcg.com',config=config, autodiscover=False, access_type=DELEGATE)account5,195 -folder = account.root.get_folder_by_name('Citi')folder6,309 +trade_template.py,0 -backfill_cds.py,676 -def convert(x):convert10,156 -sqlstr = "select markit_ticker, cds_curve from index_members(%s, %s)"sqlstr16,238 -basedir = "/home/share/CorpCDOs/Scenarios/Calibration"basedir21,449 -filelist = [f for f in os.listdir(basedir) if "hy17_singlenames" in f]filelist23,505 - "runningbid, runningask, source, recovery) VALUES(%s, %s, %s, %s, %s, %s, %s, %s)"sqlstr25,656 -tenors = [str(i)+'Y' for i in [1, 2, 3, 4, 5, 7, 10]]tenors27,749 - date = f[17:27]date30,835 - csvreader = csv.DictReader(fh)csvreader32,902 - c = serenitasdb.cursor()c33,941 - toinsert = [(date, ticker, convert(line[tenor]), convert(line[tenor]),toinsert37,1065 +backfill_cds.py,31 +def convert(x):convert10,162 -markit_tranches.py,544 -engine = dbengine("serenitasdb")engine4,45 -df = {}df5,78 -sheets = ["AskClose", "Close", "BidClose"]sheets6,86 -df= pd.read_excel("/home/share/CorpCDOs/NewSpreadsheet/Markit tranches history.xlsx",df7,129 -df = pd.concat(df)df11,359 -df = df.unstack(level=0).stack(level=0).reset_index(level=1)df12,378 - "AND series=21 AND tenor='5yr'",index_quotes17,665 -tranche_quotes = df.join(index_quotes)tranche_quotes20,813 - index_label='quotedate')index_label27,1292 +calibrate_tranches_BC.py,139 +import pandas as pdpd7,145 +def get_lastdate(conn, index, series, tenor):get_lastdate13,235 +def build_sql_str(df):build_sql_str26,613 -common.py,99 -def sanitize_float(intex_float):sanitize_float6,50 -def get_redis_queue():get_redis_queue18,445 +marks_to_HY.py,302 +import pandas as pdpd1,0 +import numpy as npnp3,44 +import statsmodels.api as smsm4,63 +def monthlySpreadDiff(index="IG", tenor="5yr"):monthlySpreadDiff16,435 +def nearestDate(base, dates):nearestDate27,1077 +def interpolate_rates(s, hist_data):interpolate_rates31,1235 +def aux(df):aux36,1410 -futures.py,1105 -ticker = "GE"ticker11,178 -monthcodes = ["F", "G", "H", "J", "K", "M", "N", "Q", "U", "V", "X", "Z"]monthcodes12,193 -def nextIMMDates(startdate, length = 8):nextIMMDates14,270 - workdate = datetime.datetime.strptime(sys.argv[1], "%Y-%m-%d")workdate28,780 - workdate = datetime.datetime.today()workdate30,855 -def QLnextIMMCodes(startdate, length = 8):QLnextIMMCodes33,932 -contracts = ["GE" + monthcodes[d.month-1] + str(d.year)[-1:] for d in nextIMMDates(workdate.date())]contracts41,1196 - ts = int(datetime.datetime.timestamp(workdate) * 1000)ts45,1370 - ts = datetime.datetime.strftime(workdate, '%s') + '000'ts47,1437 -base_uri = "http://www.cmegroup.com/CmeWS/md/MDServer/V1/Venue/G/Exchange/XCME/FOI/FUT/Product/GE"base_uri49,1500 -payload = {'currentTime': ts,payload50,1600 -r = requests.get(base_uri, params=payload)r52,1679 -quotes = json.loads(r.text)quotes53,1723 -central = pytz.timezone('US/Central')central55,1754 - tradedate = datetime.datetime.strptime(q['tradeDate'],tradedate60,2057 - tradedate = central.localize(tradedate)tradedate62,2200 +mailing_list.py,50 +def get_mailinglist(name):get_mailinglist14,315 -optim_alloc.py,493 -def cor2cov(Rho, vol):cor2cov7,106 -def rho(sigma, delta, volF):rho10,175 -def resid_vol(rho, delta, volF):resid_vol14,329 -def var(rho, delta, volF):var18,462 -def compute_allocation(rho_clo = 0.9, rho_cso=0.6, rho_subprime=0.2,compute_allocation22,596 -def plot_allocation(W, fund_return, fund_vol):plot_allocation60,2146 - volHY = 0.07volHY77,2718 - rho = {'CLO': 0.6,rho79,2736 - delta = {'CLO': 0.4,delta82,2810 - mu = np.array([0.01, 0.075, 0.065, 0.25])mu85,2890 +mark_backtest_backfill.py,270 +import pandas as pdpd1,0 +def runAllFill():runAllFill16,340 +def runSingleFill(f):runSingleFill22,497 +def get_CUSIPs():get_CUSIPs53,1849 +def get_BVAL():get_BVAL59,2039 +def pop_BVAL_to_database(df):pop_BVAL_to_database76,2794 +def get_globs():get_globs89,3293 -download_markit_quotes.py,478 - level=logging.INFO,level17,720 - format='%(asctime)s %(message)s')format18,760 -profile = FirefoxProfile()profile21,904 -driver = Firefox(profile)driver27,1214 - menu = WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.ID,menu35,1474 -hiddenmenu = WebDriverWait(driver, 10).until(hiddenmenu45,1789 - link = WebDriverWait(driver, 10).until(EC.element_to_be_clickable(link53,2069 -total_wait = 0total_wait63,2446 +secret.json,1244 +{"installed":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","client_secret":"kGFeE9blSXauth_uri1,0 +{"installed":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","client_secret":"kGFeE9blSXclient_secret1,0 +{"installed":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","client_secret":"kGFeE9blSXtoken_uri1,0 +{"installed":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","client_secret":"kGFeE9blSXclient_email1,0 +{"installed":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","client_secret":"kGFeE9blSX01,0 +{"installed":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","client_secret":"kGFeE9blSX11,0 +{"installed":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","client_secret":"kGFeE9blSXredirect_uris1,0 +{"installed":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","client_secret":"kGFeE9blSXclient_x509_cert_url1,0 +{"installed":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","client_secret":"kGFeE9blSXclient_id1,0 +{"installed":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","client_secret":"kGFeE9blSXauth_provider_x509_cert_url1,0 +{"installed":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","client_secret":"kGFeE9blSXinstalled1,0 -mark_backtest_backfill.py,273 -def runAllFill():runAllFill15,307 -def runSingleFill(f):runSingleFill21,464 -def get_CUSIPs():get_CUSIPs51,1733 -def get_BVAL():get_BVAL57,1930 -def pop_BVAL_to_database(df):pop_BVAL_to_database74,2685 -def get_globs():get_globs87,3161 -settings = {settings99,3701 +parse_html.py,320 +import pandas as pdpd1,0 +def combine_df(state, new):combine_df9,135 +def event_loop(conn):event_loop15,267 +def get_index_indicative(conn):get_index_indicative41,1280 +def parse_soup(soup):parse_soup49,1486 +def parse_index(df, df_indic):parse_index72,2316 +def parse_options(df, df_indic):parse_options88,2790 -load_cf.py,1172 -def sanitize_float(string):sanitize_float20,588 -def processzipfiles(tradedate=datetime.date.today()):processzipfiles31,841 -def get_configfile(dealname, tradedate):get_configfile51,1913 -def get_dist(date):get_dist61,2291 -def get_dealdata(dealname, tradedate):get_dealdata67,2562 -def get_cusipdata(cusip, tradedate):get_cusipdata75,3015 -def get_dealschedule(dealdata, freq='1Mo', adj=Unadjusted):get_dealschedule80,3218 -def dealname_from_cusip(conn, cusips):dealname_from_cusip87,3668 -def discounts(tradedate):discounts93,3852 -def getdealcf(dealnames, zipfiles, tradedate = datetime.date.today()):getdealcf104,4409 -def getcusipcf(params, cfdata, tradedate):getcusipcf145,6421 -def compute_delta(dist, dealweight, cusip_pv, tradedate, K1 = 0, K2 = 1):compute_delta178,8288 - tradedate = datetime.datetime.strptime(sys.argv[1], "%Y-%m-%d").date()tradedate189,8764 - tradedate = datetime.date.today()tradedate191,8855 - params = processzipfiles(tradedate)params192,8898 - cfdata = getdealcf(params["dealnames"], params["zipfiles"], tradedate)cfdata193,8939 - cusipdata = getcusipcf(params, cfdata, tradedate)cusipdata194,9015 +calibrate_tranches.py,89 +import numpy as npnp1,0 +import pandas as pdpd7,115 + def aux(rho):aux70,1906 |
