Simple Credit Monte Carlo Example

Overview

Simple One Item

The simulate_item function takes an item and a date (and whatever contexts are available) and simulates the state of that item at the given date. It can update the item with any information about the results of the simulation.

''' takes an item, a date, and set of contexts (which in this case, we arent using) and returns an item representing the inputted item simulated ''' def simulate_item(item, date, contexts): result = {} if date > item['maturity']: return None else: rand = random.random() item['defaulted'] = False if item['grade'] == 6: if rand<0.01: item['defaulted'] = True item['loss'] = beta.rvs(a=2.0, b=5.0).item() pass return item pass

Process Results

''' process takes an iteration of the simuation (that is, the results of simulating each item for each date once.) it is called after each iteration to collect the results. IN this case, we only care about dollar losses, so we aggregate the total dollar loss. ''' def process(iteration, contexts): total_loss = 0 for iter in iteration: if 'loss' in iter['simulation']: total_loss += iter['simulation']['loss'] * iter['simulation']['value'] pass return total_loss

Full Sample Script

import lib.credit.monte_carlo as mc from scipy.stats import beta import random loans = [{"grade":6, "maturity":'2026-09-10', "value":100}, {"grade":6, "maturity":'2028-09-10', "value":100}, {"grade":7, "maturity":'2028-09-10', "value":100}, ] dates = ['2026-07-01','2026-08-01','2026-09-01','2026-10-01'] def context(date, contexts): return None ''' process takes an iteration of the simuation (that is, the results of simulating each item for each date once.) it is called after each iteration to collect the results. IN this case, we only care about dollar losses, so we aggregate the total dollar loss. ''' def process(iteration, contexts): total_loss = 0 for iter in iteration: if 'loss' in iter['simulation']: total_loss += iter['simulation']['loss'] * iter['simulation']['value'] pass return total_loss ''' takes an item, a date, and set of contexts (which in this case, we arent using) and returns an item representing the inputted item simulated ''' def simulate_item(item, date, contexts): result = {} if date > item['maturity']: return None else: rand = random.random() item['defaulted'] = False if item['grade'] == 6: if rand<0.01: item['defaulted'] = True item['loss'] = beta.rvs(a=2.0, b=5.0).item() pass return item pass #iterations, items, dates, update, process, context=None losses = [] for sim in mc.simulate(100, loans, dates, simulate_item, process, context): losses.append(sum(sim)) pass average_loss = sum(losses)/len(losses) print(average_loss)

Run Sample