Last active
July 18, 2020 16:26
-
-
Save mattysmith22/737c269f770efee0ca14ae3dccba5386 to your computer and use it in GitHub Desktop.
Monte-carlo risk analysis implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
class Project: | |
risks = [] | |
def add(self, risk): | |
self.risks.append(risk) | |
def run_simulation(self, num_runs=1000): | |
result = ProjectResult() | |
for i in range(num_runs): | |
acc = 0 | |
for i in self.risks: | |
acc += i.calculate_value_from_probability(random.random()) | |
result.addResult(acc) | |
return result | |
class Risk: | |
probability = None | |
value = None | |
def __init__(self, prob, val): | |
self.probability = prob | |
self.value = val | |
def calculate_value_from_probability(self, probEntered): | |
if probEntered < self.probability: | |
return 0 | |
else: | |
return self.value | |
class ProjectResult: | |
results = [] | |
def addResult(self, val): | |
self.results.append(val) | |
def get_probability_enough_contingency(self, contingency): | |
amount_enough = 0 | |
for i in self.results: | |
if i <= contingency: | |
amount_enough += 1 | |
print("amount enough = {}, len = {}".format(amount_enough, len(self.results))) | |
return (amount_enough/len(self.results)) | |
if __name__ == '__main__': | |
project = Project() | |
project.add(Risk(0.5, 100)) | |
project.add(Risk(0.25, 300)) | |
project.add(Risk(0.3, 200)) | |
result = project.run_simulation() | |
prob =result.get_probability_enough_contingency(500) | |
print("There is a {}% chance that £500 is enough".format(round(prob*100))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment