TP: Monte Carlo Option Pricing with Decorators
TP: Monte Carlo Option Pricing with Decorators
In this practical exercise, we’ll create a Monte Carlo simulator for option pricing and use decorators to inject different payoff functions into the simulator. This approach will allow us to easily create and price various types of options using the same underlying simulation framework.
Scenario: Flexible Option Pricing System
We want to build a system that can price different types of options using Monte Carlo simulation. The system should be flexible enough to handle various payoff structures without modifying the core simulation logic.
Step 1: Implement the Base Monte Carlo Simulator
First, let’s implement our base MonteCarloSimulator class:
Step 2: Implement the Decorator
Now, implement a decorator called option_pricer. This decorator should:
- Take a payoff function as input
- Create a new class that inherits from
MonteCarloSimulator - Inject the input function as the
payoffmethod of the new class - Return the new class
Here’s the skeleton for the decorator:
Step 3: Use the Decorator
Once you’ve implemented the decorator, you should be able to use it like this:
Your Task
- Implement the
option_pricerdecorator to make the above code work. - Ensure that the new classes created by the decorator inherit from
MonteCarloSimulator. - Make sure that the
payoffmethod in the new classes calls the decorated function.
Hints
- You can use
type()to create a new class dynamically. - The payoff function will become a method, so it needs to take
selfas its first parameter. - You can use
__name__attribute of the function to name your new class. - You can use functools wraps to keep tracking of the base function
Bonus Challenges
Modify the decorator to allow for additional parameters in the payoff function, such as strike price or barrier levels.
Implement a more complex option type, such as an Asian option, where the payoff depends on the average stock price over the simulation period.
Add a method to calculate the standard error of the Monte Carlo estimate and use it to compute confidence intervals for the option prices.