Full Script

from statistics import NormalDist import math def corporate(pd, lgd=1, M=1, large=True, alpha=0.999, R=None, cecl=True): avc = 1 if (large == True) : avc = 1.25 if (R == None) : R = avc * (0.12 * (1 - math.exp(-50 * pd)) / (1 - math.exp(-50)) + 0.24 *(1- (1 - math.exp(-50 * pd)) / (1 - math.exp(-50)))) b = math.pow(0.11852 - 0.05478 * math.log(pd), 2) maturityAdjustment = (1 + (M - 2.5) * b) / (1 - 1.5 * b) factor1 = math.sqrt(1 / (1 - R)) factor2 = math.sqrt(R / (1 - R)) K = lgd * maturityAdjustment * (NormalDist().cdf(factor1 * NormalDist(mu=0, sigma=1).inv_cdf(pd) + factor2 * NormalDist(mu=0, sigma=1).inv_cdf(alpha))); if(cecl == True) : K = K - pd*lgd return K def otherRetail(pd, lgd=1, alpha=0.999, R=None, cecl=True): if(R == None) : R = 0.03 * (1-math.exp(-35*pd))/(1-math.exp(-35)) + 0.16*(1 - (1-math.exp(-35*pd))/(1-math.exp(-35))) factor1 = math.sqrt(1 / (1 - R)); factor2 = math.sqrt(R / (1 - R)); K = lgd * (NormalDist().cdf(factor1 * NormalDist(mu=0, sigma=1).inv_cdf(pd) + factor2 * NormalDist(mu=0, sigma=1).inv_cdf(alpha))) if(cecl == True) : K = K -pd*lgd return K def retail(pd, lgd=1, alpha=0.999, R=None, cecl=True): if(R == None) : R = 0.04 factor1 = math.sqrt(1 / (1 - R)) factor2 = math.sqrt(R / (1 - R)) K = lgd * (NormalDist().cdf(factor1 * NormalDist(mu=0, sigma=1).inv_cdf(pd) + factor2 * NormalDist(mu=0, sigma=1).inv_cdf(alpha))) if(cecl == True) : K = K -pd*lgd return K def sme(pd, lgd=1, M=1, S=0, alpha=0.999, R=None, cecl=True): if (S != None) : S = min(max(S, 5), 50) if (S != None and R == None) : R = 0.12 * (1 - math.exp(-50 * pd)) / (1 - math.exp(-50)) + 0.24 * (1 - (1 - math.exp(-50 * pd)) / (1 - math.exp(-50))) - 0.04 * (1 - max(S - 5, 0) / 45) else : R = 0.12 * (1 - math.exp(-50 * pd)) / (1 - math.exp(-50)) + 0.24 * (1 - (1 - math.exp(-50 * pd)) / (1 - math.exp(-50))) b = math.pow(0.11852 - 0.05478 * math.log(pd), 2); maturityAdjustment = (1 + (M - 2.5) * b) / (1 - 1.5 * b) K = lgd * maturityAdjustment * (NormalDist().cdf(math.sqrt(1 / (1 - R)) * NormalDist(mu=0, sigma=1).inv_cdf(pd) + math.sqrt(R / (1 - R)) * NormalDist(mu=0, sigma=1).inv_cdf(alpha))) if(cecl == True): K = K -pd*lgd return K def mortgage(pd, lgd=1, alpha=0.999, R=None, cecl=True): if(R == None) : R = 0.15 factor1 = math.sqrt(1 / (1 - R)); factor2 = math.sqrt(R / (1 - R)); K = lgd * (NormalDist().cdf(factor1 * NormalDist(mu=0, sigma=1).inv_cdf(pd) + factor2 * NormalDist(mu=0, sigma=1).inv_cdf(alpha))); if(cecl == True): K = K -pd*lgd return K ''' Given a probability of default for loan 1 and loan 2, and a default correlation rho, calculates the asset rho necessary to achieve the given inputs. asset rho = w1 * w2 ''' ''' def assetRho(p1, p2, rho): d1 = NormalDist(mu=0, sigma=1).inv_cdf(p1); d2 = NormalDist(mu=0, sigma=1).inv_cdf(p2); temp = rho * math.sqrt(p1*p2*(1-p1)*(1-p2)) + p1*p2; def f(rhoa): t1 = bv.cumulative(d1, d2, rhoa); return t1 - temp; root = rt.root(f,-1,1); return root '''