Skip to content
Open
Show file tree
Hide file tree
Changes from 36 commits
Commits
Show all changes
103 commits
Select commit Hold shift + click to select a range
5ced119
Did initial reformatting (with black) and a little cleanup.
crh23 Jul 3, 2019
d86bf04
Removed most abce dependance, except for gui function, and some unnec…
KloskaT Jul 3, 2019
bbe554f
A bit more aesthetic cleanup
crh23 Jul 3, 2019
b4783d2
Cleaned up the init file for InsuranceSimulation and added a function…
KloskaT Jul 3, 2019
77f7972
Removed ABCE. There are probably some simplifications that can be mad…
crh23 Jul 3, 2019
bf53795
More cleanup and minor fixes.
crh23 Jul 4, 2019
8c9b867
Added docstring to every function in the simulation class. Small typo…
KloskaT Jul 4, 2019
2b72fb9
Removed redundant functions from insurancesimulation: reinsurance_cap…
KloskaT Jul 5, 2019
202b1ab
Reimplemented replication using file names instead of replic_id, more…
crh23 Jul 5, 2019
1a01d78
Minor performance improvements
crh23 Jul 5, 2019
83f3cc6
Added docstring to all functions in metainsuranceorg. Also created fu…
KloskaT Jul 5, 2019
829c001
More minor performance improvements
crh23 Jul 8, 2019
facfeba
Made the get_mean_std function take a tuple as an argument to enable …
crh23 Jul 8, 2019
b9ab7e4
Added comments, cleaned up remnants of parent functions.
KloskaT Jul 8, 2019
919537b
Added comments. Removed some redundant lines.
KloskaT Jul 8, 2019
e95bd39
Created file and class that acts as central bank in awarding agents i…
KloskaT Jul 8, 2019
53810ad
Mostly just refactoring/comments
crh23 Jul 9, 2019
c87453f
Added docstring to all methods. Merged create_reinrisk into ask_reins…
KloskaT Jul 9, 2019
882d0bf
Apply black.py to all python files. Just a code formatter, zero chang…
crh23 Jul 9, 2019
9713c53
Small change
crh23 Jul 9, 2019
5c0f021
Added docstring to all methods. General clean up.
KloskaT Jul 9, 2019
697e7f6
Small change
crh23 Jul 9, 2019
a346ab8
Bugfix (I think) and small improvement (bigger for more risk categories)
crh23 Jul 9, 2019
7e52a5c
Added method to allow continually updating network in same figure with
KloskaT Jul 10, 2019
1ea7ae3
Removed last of abce references.
KloskaT Jul 10, 2019
b70f504
Updated to include new arguments, removed abce, altered plotting section
KloskaT Jul 10, 2019
9493a18
Update README.md
KloskaT Jul 10, 2019
c742f3a
Save state now includes events. Removed abce from resume.py and now w…
KloskaT Jul 11, 2019
2ea0bcc
Merge branch 'master' of https://github.com/KloskaT/isle
KloskaT Jul 11, 2019
d3080e7
Fixed resume.py
KloskaT Jul 11, 2019
fbc6944
Cleaned up, added central bank to award interest
KloskaT Jul 11, 2019
3408f8b
Starting to add docstrings and set relevant attributes and methods to…
crh23 Jul 10, 2019
65e944f
Merge branch 'cleanup'
crh23 Jul 11, 2019
64810af
Fix simulation saving
crh23 Jul 12, 2019
1ccb7f1
black.py
crh23 Jul 12, 2019
2edc655
Merge branch 'thomas'
crh23 Jul 12, 2019
c466b9b
Merge branch 'privatise'
crh23 Jul 12, 2019
d8c22ad
Cleanup after merge
crh23 Jul 12, 2019
444bc28
Moved agent creating code into insurancesimulation.py from start.py
crh23 Jul 12, 2019
d8fcce6
Fixed error where reinsurance were initialized using insurance firm IDs
KloskaT Jul 15, 2019
c82025a
Attempting to get resume working, not successfully (pickle?!)
crh23 Jul 12, 2019
8470ae3
Minor tweaks
crh23 Jul 16, 2019
25fb93b
Added animated pie chart for percent contracts on same figure, for bo…
KloskaT Jul 16, 2019
361f02a
Minor tweaks
crh23 Jul 16, 2019
d0c1c45
Merge remote-tracking branch 'thomas/master'
crh23 Jul 16, 2019
bbc1b08
Fixed bug due to slightly improper merge
crh23 Jul 16, 2019
6c7bc05
Implemented scaling of insurance (not reinsurance) premiums and risk …
crh23 Jul 16, 2019
465adf3
Fixed bug due to slightly improper merge
crh23 Jul 16, 2019
3b4fc96
Merge branch 'bigger_is_better'
crh23 Jul 16, 2019
1130cab
Lots of little aesthetic cleanups
crh23 Jul 16, 2019
8d225fa
Lots of little aesthetic cleanups
crh23 Jul 16, 2019
e093301
Slightly updated the readme
crh23 Jul 16, 2019
f7d3bfd
Can now call either pie plots or timeseries from command line when ru…
KloskaT Jul 17, 2019
5cc359f
Necessary network data is now saved. Added class that animates (and s…
KloskaT Jul 17, 2019
681c287
Added condition for saving network data, set true by default.
KloskaT Jul 17, 2019
eccc94b
Updated README for visualisation.
KloskaT Jul 17, 2019
7d56c23
Added some classes and lots of type hints
crh23 Jul 17, 2019
94f5e5f
Added visualisation_paper3.py stuff to file, inluding histogram and C…
KloskaT Jul 17, 2019
c3c6376
Remove replicid argument
crh23 Jul 17, 2019
64d6fe5
Commented. Now saves all to 'figures' folder. Updated visualisation R…
KloskaT Jul 18, 2019
88816ce
Fixed a bug causing contracts to be lost
crh23 Jul 18, 2019
0f08920
Even more type hints
crh23 Jul 18, 2019
e233b27
Merge branch 'dataclasses_and_type_hints'
crh23 Jul 18, 2019
9bccdd2
Merge remote-tracking branch 'chris/master'
crh23 Jul 18, 2019
b08ce8c
Can plot specific data types against each other for all riskmodels, w…
KloskaT Jul 18, 2019
e7f442a
Misc cleanups
crh23 Jul 19, 2019
7f910e8
Allow firms to issue multi-layered requests for reinsurance
crh23 Jul 19, 2019
bb16e69
Properly integrated metaplotter_pl_timescale_additional_measures_alph…
KloskaT Jul 19, 2019
868a7d8
Updated README for visualisation.
KloskaT Jul 19, 2019
695929d
Start creating a way for firms to track reinsurance
crh23 Jul 19, 2019
aee9048
Merge in changes for python 3.6 (and notes from meeting)
crh23 Jul 23, 2019
5da97e5
Made multi-layer reinsurance work. Also fix for python 3.6
crh23 Jul 23, 2019
36900c9
Add provision for what should happen when paying a non-operational firm
crh23 Jul 23, 2019
8cfc49c
Apply black.py
crh23 Jul 23, 2019
771083b
Change excess to limit
crh23 Jul 23, 2019
bdbaf64
Little bit of cleanup
crh23 Jul 24, 2019
c7cff96
Merge branch 'layered_reinsurance'
crh23 Jul 24, 2019
3aca163
Both types of firms going bankrupt can now be bought by others. If no…
KloskaT Jul 24, 2019
8b9aa5d
Changed event damage values so they are just a number not array (allo…
KloskaT Jul 24, 2019
b78513b
Merge remote-tracking branch 'thomas/master'
crh23 Jul 25, 2019
9b17456
Network data now saved (to separate file) using logger for both types…
KloskaT Jul 25, 2019
75ae851
Deleted redundant plotter files. Visualisation prints when each reque…
KloskaT Jul 25, 2019
a3dca48
Added save network to start.py for single run using logger object.
KloskaT Jul 25, 2019
10a8f1e
Creates figures folder if not already existing.
KloskaT Jul 25, 2019
c23aefd
Checks, creates, and writes animation to figures folder
KloskaT Jul 25, 2019
747b188
Added regulator to central bank based on solvency ii, issues warning …
KloskaT Jul 29, 2019
555f54b
Added method to central bank that grants disaster relief aid to firms…
KloskaT Jul 30, 2019
6c389d6
Added file to load different data sets and compare them by plot or test
KloskaT Jul 31, 2019
d1756a2
Removed redundant method
KloskaT Aug 1, 2019
05739aa
Regulator changed such that it includes reinsurance contract values a…
KloskaT Aug 1, 2019
f9e5b0d
Merge branch 'master' into comparison
KloskaT Aug 2, 2019
44050e2
black
crh23 Aug 2, 2019
bb971b3
Merge branch 'thomas'
crh23 Aug 2, 2019
951d8e3
Merge branch 'thomas'
crh23 Aug 2, 2019
72f010b
Now looks at percentage difference between original and new values. A…
KloskaT Aug 2, 2019
2ef0649
Fixed some bugs causing logged data to be incorrect. Included (or mor…
KloskaT Aug 5, 2019
cba79a8
Added more denominations to aid fractions. Removed comparison.py and …
KloskaT Aug 6, 2019
2a6ddba
Merge branch 'master' of https://github.com/crh23/isle into chris
KloskaT Aug 6, 2019
c83983c
Merged Chris Master Branch. Almost fixed regulator for multi layer re…
KloskaT Aug 6, 2019
ae8e0ea
Fixed bug causing most firms to exit market (firms with warnings dont…
KloskaT Aug 7, 2019
a1c106e
Final. Changes due to Chris' changes. Tweaking firm pricing. Removed …
KloskaT Aug 9, 2019
656aebf
Changed aid check in line with change to insurance claims' claim time…
KloskaT Aug 9, 2019
e06666c
Updated readme
KloskaT Aug 9, 2019
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 23 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ $ pip install -r requirements.txt

## Simulation

Execute the simulation with this command
Execute a single simulation run with the command:

```
$ python3 start.py
Expand All @@ -25,9 +25,9 @@ $ python3 start.py
The ```start.py``` script accepts a number of options.

```
usage: start.py [-h] [--abce] [--oneriskmodel] [--riskmodels {1,2,3,4}]
[--replicid REPLICID] [--replicating]
[--randomseed RANDOMSEED] [--foreground] [-p] [-v]
usage: start.py [--oneriskmodel] [--riskmodels {1,2,3,4}] [--replicid REPLICID]
[--replicating] [--randomseed RANDOMSEED] [--foreground]
[--shownetwork] [-p] [-v] [--save_iterations]
```

See the help for more details
Expand All @@ -36,17 +36,9 @@ See the help for more details
python3 start.py --help
```

## Graphical simulation runs

abce can be used to run simulations with a graphical interface:

```
python3 start.py --abce
```

## Ensemble simulations

The bash scripts ```starter_*.sh``` can be used to run ensembles of a large number of simulations for settings with 1-4 different riskmodels. ```starter_two.sh``` is set up to generate random seeds and risk event schedules that are - for consistency and comparability - also used by the other scripts (i.e. ```starter_two.sh``` needs to be run first).
The bash scripts ```starter_*.sh``` can be used to run ensembles of a large number of simulations for settings with 1-4 different risk models. ```starter_two.sh``` is set up to generate random seeds and risk event schedules that are - for consistency and comparability - also used by the other scripts (i.e. ```starter_two.sh``` needs to be run first).

```
bash starter_two.sh
Expand All @@ -55,7 +47,23 @@ bash starter_four.sh
bash starter_three.sh
```

## Plotting
## Visualisation

#### Single runs
Use the script ```visualisation.py [--single]``` from the command line to plot data from a single run. It also takes the
arguments ```[--pie] [--timeseries]``` for which data representation is wanted.

If the necessary data has been saved a network animation can also be created by running ```visualization_network.py```
which takes the arguments ```[--save] [--number_iterations]``` if you want the animation to be saved as an mp4, and how
many time iterations you want in the animation.

#### Ensemble runs
Ensemble runs can be plotted if the correct data is available using ``visualisation.py`` which has a number of arguments.

```
visualiation.py [--timeseries_comparison] [--firmdistribution]
[--bankruptcydistribution] [--compare_riskmodels]
```

Use the scripts ```plotter_pl_timescale.py``` and ```visualize.py``` for plotting/visualizing single simulation runs. Use ```.py```, ```metaplotter_pl_timescale.py```, or ```metaplotter_pl_timescale_additional_measures.py``` to visualize ensemble runs.
See help for more information.

235 changes: 36 additions & 199 deletions catbond.py

Large diffs are not rendered by default.

62 changes: 62 additions & 0 deletions centralbank.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
from isleconfig import simulation_parameters


class CentralBank:
def __init__(self):
"""Constructor Method.
No accepted arguments.
Constructs the CentralBank class. This class is currently only used to award interest payments."""
self.interest_rate = simulation_parameters['interest_rate']
self.inflation_target = 0.02
self.actual_inflation = 0
self.onemonth_CPI = 0
self.twelvemonth_CPI = 0
self.feedback_counter = 0
self.prices_list = []

def set_interest_rate(self):
"""Method to set the interest rate
No accepted arguments
No return values
This method is meant to set interest rates dependant on prices however insurance firms have little effect on
interest rates therefore is not used and needs work if to be used."""
if self.actual_inflation > self.inflation_target:
if self.feedback_counter > 4:
self.interest_rate += 0.0001
self.feedback_counter = 0
else:
self.feedback_counter += 1
elif self.actual_inflation < -0.01:
if self.feedback_counter > 4:
if self.interest_rate > 0.0001:
self.interest_rate -= 0.0001
self.feedback_counter = 0
else:
self.feedback_counter += 1
else:
self.feedback_counter = 0
print(self.interest_rate)

def award_interest(self, firm, total_cash):
"""Method to award interest.
Accepts:
firm: Type class, the agent that is to be awarded interest.
total_cash: Type decimal
This method takes an agents cash and awards it an interest payment on the cash."""
interest_payment = total_cash * self.interest_rate
firm.receive(interest_payment)

def calculate_inflation(self, current_price, time):
"""Method to calculate inflation in insurance prices.
Accepts:
current_price: Type decimal
time: Type integer
This method is designed to calculate both the percentage change in insurance price last 1 and 12 months as an
estimate of inflation. This is to help calculate how insurance rates should be set. Currently unused."""
self.prices_list.append(current_price)
if time < 13:
self.actual_inflation = self.inflation_target
else:
self.onemonth_CPI = (current_price - self.prices_list[-2])/self.prices_list[-2]
self.twelvemonth_CPI = (current_price - self.prices_list[-13])/self.prices_list[-13]
self.actual_inflation = self.twelvemonth_CPI
1 change: 1 addition & 0 deletions distributiontruncated.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from math import ceil
import scipy.integrate


class TruncatedDistWrapper():
def __init__(self, dist, lower_bound=0, upper_bound=1):
self.dist = dist
Expand Down
45 changes: 25 additions & 20 deletions ensemble.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#This script allows to launch an ensemble of simulations for different number of risks models.
#It can be run locally if no argument is passed when called from the terminal.
#It can be run in the cloud if it is passed as argument the server that will be used.
"""This script allows to launch an ensemble of simulations for different number of risks models.
It can be run locally if no argument is passed when called from the terminal.
It can be run in the cloud if it is passed as argument the server that will be used."""
import sys
import random
import os
Expand All @@ -16,7 +16,6 @@
from sandman2.api import operation, Session



@operation
def agg(*outputs):
# do nothing
Expand All @@ -29,13 +28,13 @@ def rake(hostname):

"""Configuration of the ensemble"""

replications = 70 #Number of replications to be carried out for each configuration. Usually one risk model, two risk models, three risk models, four risk models.
replications = 70 # Number of replications to be carried out for each configuration. Usually one risk model, two risk models, three risk models, four risk models.

model = start.main

m = operation(model, include_modules = True)

riskmodels = [1,2,3,4] #The number of risk models that will be used.
riskmodels = [1,2,3,4] # The number of risk models that will be used.

parameters = isleconfig.simulation_parameters

Expand Down Expand Up @@ -73,19 +72,21 @@ def rake(hostname):
'rc_event_schedule_initial': '_rc_event_schedule.dat',
'rc_event_damage_initial': '_rc_event_damage.dat',
'number_riskmodels': '_number_riskmodels.dat'
'individual_contracts' '_insurance_contracts.dat'
'reinsurance_contracts' '_reinsurance_contracts.dat'
}

if isleconfig.slim_log:
for name in ['insurance_firms_cash', 'reinsurance_firms_cash']:
for name in ['insurance_firms_cash', 'reinsurance_firms_cash', 'individual_contracts', 'reinsurance_contracts']:
del requested_logs[name]

assert "number_riskmodels" in requested_logs


"""Configure log directory and ensure that the directory exists"""
dir_prefix = "/data/"
directory = os.getcwd() + dir_prefix
try: #Here it is checked whether the directory to collect the results exists or not. If not it is created.
try: # Here it is checked whether the directory to collect the results exists or not. If not it is created.
os.stat(directory)
except:
os.mkdir(directory)
Expand All @@ -95,11 +96,11 @@ def rake(hostname):
filename = os.getcwd() + dir_prefix + nums[str(i)] + "_history_logs.dat"
if os.path.exists(filename):
os.remove(filename)


"""Setup of the simulations"""

setup = SetupSim() #Here the setup for the simulation is done.
setup = SetupSim() # Here the setup for the simulation is done.
[general_rc_event_schedule, general_rc_event_damage, np_seeds, random_seeds] = setup.obtain_ensemble(replications) #Since this script is used to carry out simulations in the cloud will usually have more than 1 replication..
save_iter = isleconfig.simulation_parameters["max_time"] + 2 # never save simulation state in ensemble runs (resuming is impossible anyway)

Expand All @@ -108,7 +109,8 @@ def rake(hostname):
simulation_parameters = copy.copy(parameters) #Here the parameters used for the simulation are loaded. Clone is needed otherwise all the runs will be carried out with the last number of thee loop.
simulation_parameters["no_riskmodels"] = i #Since we want to obtain ensembles for different number of risk models, we vary here the number of risks models.
job = [m(simulation_parameters, general_rc_event_schedule[x], general_rc_event_damage[x], np_seeds[x], random_seeds[x], save_iter, list(requested_logs.keys())) for x in range(replications)] #Here is assembled each job with the corresponding: simulation parameters, time events, damage events, seeds, simulation state save interval (never, i.e. longer than max_time), and list of requested logs.
jobs.append(job) #All jobs are collected in the jobs list.
jobs.append(job) # All jobs are collected in the jobs list.


"""Here the jobs are submitted"""

Expand All @@ -118,17 +120,14 @@ def rake(hostname):

"""Run simulation and obtain result"""
result = sess.submit(job)
"""find number of riskmodels from log"""


"""Find number of riskmodels from log"""
delistified_result = [listify.delistify(list(res)) for res in result]
#nrmidx = result[0][-1].index("number_riskmodels")
#nrm = result[0][nrmidx]
nrm = delistified_result[0]["number_riskmodels"]

"""These are the files created to collect the results"""
wfiles_dict = {}

logfile_dict = {}

for name in requested_logs.keys():
Expand All @@ -154,8 +153,10 @@ def rake(hostname):

"""Save logs as dict (to <num>_history_logs.dat)"""
L.save_log(True)
if isleconfig.save_network:
L.save_network_data(ensemble=True)

"""Save logs as indivitual files"""
"""Save logs as individual files"""
for name in logfile_dict:
wfiles_dict[name].write(str(delistified_result[i][name]) + "\n")

Expand All @@ -168,5 +169,9 @@ def rake(hostname):
if __name__ == '__main__':
host = None
if len(sys.argv) > 1:
host = sys.argv[1] #The server is passed as an argument.
host = sys.argv[1] # The server is passed as an argument.
rake(host)

# ID = OxeChiwQ3l0vsBnkLLXKMnpSBn948ptW
# Secret = lfK_Gav8EK2B_gN0bsNXjUVQq84ua1iL2xlYs8Ef58tFyTSwzzJcWeDdSH21BnHx
# Hostname = bright-lemur.clusters.sandman.ai
Loading