Skip to content

Commit

Permalink
first release
Browse files Browse the repository at this point in the history
first release

first release

first release

first release

Remove __pycache__ directory and update .gitignore

Remove __pycache__ directory and update .gitignore
  • Loading branch information
saeedbidi committed Oct 13, 2024
1 parent 6a67af3 commit 703811f
Show file tree
Hide file tree
Showing 25 changed files with 179 additions and 823 deletions.
Binary file added .DS_Store
Binary file not shown.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
myenv/
backtest_data/
build/
Extra-inf.md
Extra-inf.md
old/
155 changes: 86 additions & 69 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
# **Project Overview**

As a Senior Data Scientist with a PhD in Computational Physics, I have a strong foundation in analytical thinking and complex problem-solving. My current focus on finance projects stems from a deep passion for the field and a desire to apply my expertise to real-world financial challenges. Through hands-on work in finance, I am leveraging my data science skills to gain practical experience and build a robust understanding of financial systems.
## Note:

This project implements the **Black-Scholes model**, **Monte Carlo simulations** and the **Binomial Tree method** for pricing European call and put options. Real-world stock data is fetched via the **Yahoo Finance API** to compute option prices, historical volatility, and option sensitivities (the Greeks). The project also provides visualisations and comparisons of option prices using all three methods.
🚀 I am excited to share my project focusing on This project implements the **Black-Scholes model**, **Monte Carlo simulations** and the **Binomial Tree method** for pricing European call and put options. I am developing the project further by adding backtesting, a machine learning model, and deploying the app.

## **Option Pricing Model with Black-Scholes, Monte Carlo and Binomial Tree Methods**
🎉 I believe in hands on learning. As a Senior Data Scientist with a PhD in Computational Physics, I have a strong foundation in analytical thinking and complex problem-solving. Through hands-on work in Finance, I am leveraging my data science skills to gain practical experience and build a robust understanding of financial systems.

🛠️ Real-world stock data is fetched via the **Yahoo Finance API** to compute option prices, historical volatility, and option sensitivities (the Greeks). The project also provides visualisations and comparisons of option prices using all three methods.


## 💰 **Option Pricing Model with Black-Scholes, Monte Carlo and Binomial Tree Methods**

The **Black-Scholes model**, **Monte Carlo simulations**, and the **Binomial Tree method** are vital tools in financial markets for pricing options. Each method offers a distinct approach to estimating the price of European-style options, relying on parameters such as stock price, strike price, time to maturity, risk-free rate, and volatility.

Expand All @@ -20,7 +25,7 @@ The **Black-Scholes model**, **Monte Carlo simulations**, and the **Binomial Tre
- Provides visualisations showing how option prices vary with stock price for **both calls and puts**.
- **Compares** pricing results from the three methods.

### **Inputs**
### 📝 **Inputs**

1. **Stock Ticker**
2. **Stock Price (S)**
Expand All @@ -29,99 +34,111 @@ The **Black-Scholes model**, **Monte Carlo simulations**, and the **Binomial Tre
5. **Risk-Free Rate (r)**
6. **Market Price of the Option**

### **Outputs**
1. **Call and Put Option Prices** using the three pricing methods.
2. **Greeks** for the call and put options.
3. **Implied Volatility** of the option.
4. **Plots** illustrating price changes with respect to the underlying stock price.
5. **Comparison** of option prices from all three methods.
### 📤 **Outputs**

### **Sample Output**
The script will generate the following output:
- **options_report.txt**: a report file containing:
- **Call and Put Option Prices** using **Black-Scholes**, **Monte Carlo**, and **Binomial Tree** methods.
- **Greeks** and **implied volatility**.

- **Plots containing:**
- **Comparing the predictions by different models**
- **Option price vs stock price (using Black Scholes model)**
- **Monte Carlo payoff histogram**
- **Monte Carlo convergence plot**
- **Monte Carlo paths**

#### **Sample report file**

```
Options Pricing and Greeks Calculation Report:
----------------------------------
1. User Inputs:
- Stock Ticker: AAPL
- Stock Price (S): 191.8
- Strike Price (K): 207.5
- Days to Expiration: 7 days
- Risk-Free Rate (r): 5.00%
- Market Price of the Option: 22.25
2. Calculated Intermediate Values:
- Time to Maturity (T): 0.0192 years
- Historical Volatility (σ): 19.95%
3. Option Prices:
- Option Price (Black-Scholes): 15.50
- Option Price (Monte Carlo): 15.46
- Option Price (Binomial Tree): 15.50
4. Greeks:
- Delta: -0.9974
- Gamma: 0.0015
- Vega: 0.2113
- Theta: 9.2415
- Rho: -3.9663
5. Implied Volatility Calculation:
- Implied Volatility (IV): 118.69%
Options Pricing and Greeks Calculation Report
1. User Inputs:
- Option type: call
- Stock Ticker: AAPL
- Stock Price (S): 226.5
- Strike Price (K): 207.5
- Days to Expiration: 7 days
- Risk-Free Rate (r): 5.00%
- Market Price of the Option: 22.25
- Start and end date for calculating Historical Volatility: 2023-01-01 - 2024-09-24
2. Calculated Intermediate Values:
- Time to Maturity (T): 0.0192 years
- Historical Volatility (σ): 21.91%
3. Option Prices:
- Option Price (Black-Scholes): 19.17
- Option Price (Monte Carlo): 19.24
- Option Price (Binomial Tree): 19.17
4. Greeks:
- Delta: 0.9983
- Gamma: 0.0008
- Vega: 0.1710
- Theta: -11.3226
- Rho: 3.9682
5. Implied Volatility Calculation:
- Implied Volatility (IV): 82.16%
```
#### **Sample of Option vs Stock price plot using Black-Scholes model**

## **Project Structure**
![Option_price_vs_stock](/output/Option_price_vs_stock_price.png)

#### **Sample of Monte Carlo paths and convergence plot**

![Monte_Carlo_Paths](/output/Monte_Carlo_Paths.png)
![Convergence_Plot](/output/Convergence_Plot.png)


## 📂 **Project Structure**

```
.
├── main.py # Main Python script for the project
├── option_pricing.py # Main Python script for the project
├── option_pricing_app.py # Streamlit app
├── setup.py # Setup Python script to install the required libraries
├── README.md # This README file
├── output # Output folder containing the reports and plots
```

## **Customisation**
## ⚙️ **Customisation**
You can customise this project by:
- Changing the **stock ticker** (e.g., from `AAPL` to `MSFT`).
- Modifying the **strike price**, **risk-free rate**, **time to maturity**, or **volatility**.
- Adjusting the number of **simulations** for the Monte Carlo method or the number of **steps** for the Binomial Tree method.


## **How to Run the Project**
## 🎓 **How to Run the Project**

1. Clone the repository.
2. Install the following Python setup file including the necessary libraries:

```bash
python setup.py install
```
3. Execute the Python code `main.py` or the Jupyter Notebook script `main.ipynb`.
3. Execute the Python code `option_pricing.py` or the Jupyter Notebook script `option_pricing.ipynb`.


### **Example Output**
The script will generate the following output:
- **Call and Put Option Prices** using **Black-Scholes**, **Monte Carlo**, and **Binomial Tree** methods.
- The computed **Greeks** and **implied volatility**.
- **Option Price (call or put) vs. Stock Price** plots:

### **Parameters**
You can modify the following parameters in the script:
- **`ticker`**: Ticker symbol of the stock (e.g., `AAPL` for Apple).
- **`K`**: Strike price of the option.
- **`T`**: Time to maturity in years.
- **`r`**: Risk-free rate (annualised).
- **`n_simulations`**: Number of simulations for the Monte Carlo method.
- **`n_steps`**: Number of steps in the Binomial Tree method.

- **`mc_num_sim`**: Number of simulations for the Monte Carlo method.
- **`bt_num_step`**: Number of steps in the Binomial Tree method.

### **Comparison**
The script compares prices from the **Black-Scholes**, **Monte Carlo**, and **Binomial Tree** methods, showcasing their alignment or divergence under varying market conditions and parameters like volatility and time to maturity.

## **Code Explanation**
## 📖 **Code Explanation**

### **1. Black-Scholes Model**
The **Black-Scholes model** offers a closed-form solution for pricing European-style options, based on the assumption that stock prices follow a geometric Brownian motion.
The **Black-Scholes model** gives a closed-form solution for pricing European-style options, based on the assumption that stock prices follow a geometric Brownian motion.

#### **Formula**
For call options:
Expand Down Expand Up @@ -159,30 +176,30 @@ where:
- $Z$ is a random variable from a standard normal distribution (representing the random walk).

For each simulation:
1. Simulate the stock price over time using the GBM formula.
2. Calculate the option **payoff** at maturity:
1. Stock price over time is simulated using the GBM formula.
2. Option **payoff** at maturity is calculated:
- **Call Option**: $\max(0, S_T - K)$
- **Put Option**: $\max(0, K - S_T)$,

where $S_T$ is the simulated stock price at maturity and $K$ is the strike price.

3. Discount the payoff back to present value using the risk-free rate:
3. The payoff is discounted back to present value using the risk-free rate:
```math
\text{Option Price} = \exp(-r \cdot T) \cdot \text{Average Payoff},
```

where $T$ is the time to expiration in years.

This approach is flexible and can handle a wide variety of option types, but it requires many simulations for accuracy.
This approach is flexible and can handle a wide variety of option types though it requires many simulations for accuracy.


### **3. Binomial Tree Method**
The Binomial Tree method approximates option prices by constructing a tree of possible future stock prices, calculating option prices by working backwards from the terminal nodes.

#### **Steps**
1. Divide the time to expiration into `n` intervals.
1. Time is divided to expiration into `n` intervals.
2. Each interval allows the stock price to increase by a factor `u` or decrease by a factor `d`.
3. Compute option prices by working backwards using risk-neutral probabilities.
3. Option prices are computed by working backwards using risk-neutral probabilities.

### **Greeks Explanation**
- **$\Delta$**: Sensitivity of the option price to changes in the underlying stock price.
Expand All @@ -192,17 +209,17 @@ The Binomial Tree method approximates option prices by constructing a tree of po
- **$\rho$**: Sensitivity of the option price to changes in the risk-free interest rate.

### **Implied Volatility Calculation**
Implied volatility is derived from the Black-Scholes model to match the market price of an option, solved iteratively using **Brent's method**.
Implied volatility is derived from the Black-Scholes model to match the market price of an option, calculated through trying **Newton-Raphson** first, then **Bisection**, and finally **Brent's method**. They usually converge to the same solution.

### **Comparison of Methods**
Both Monte Carlo and Binomial Tree methods provide alternative means to calculate option prices, especially for options with complex features.
### ⚖️ **Comparison of Methods**
All methods provide alternative means to calculate option prices, especially for options with complex features. Why not running the code and observe the comparison plot?


## **References**
## 📚 **References**
- [Black-Scholes Model - Investopedia](https://www.investopedia.com/terms/b/blackscholes.asp)
- [Monte Carlo Methods - Investopedia](https://www.investopedia.com/terms/m/montecarlosimulation.asp)
- [Binomial Tree Model - Investopedia](https://www.investopedia.com/terms/b/binomialoptionpricing.asp)
- [Yahoo Finance API](https://pypi.org/project/yfinance/)

## **License**
## 📜 **License**
This project is open-source and available under the [MIT License](LICENSE).
Binary file removed __pycache__/main.cpython-312.pyc
Binary file not shown.
Binary file removed __pycache__/option_pricing.cpython-312.pyc
Binary file not shown.
459 changes: 38 additions & 421 deletions option_pricing.ipynb

Large diffs are not rendered by default.

Loading

0 comments on commit 703811f

Please sign in to comment.