Trading financial derivatives is one of the key functions for major investment banks.
A derivative is a contract between two or more parties whose value is based on an agreed-upon underlying financial asset (like a stock price) or set of assets ( basket of stocks ).
An example is a European call option on an equity stock( called the underlier of the option ). This option gives the buyer the right (but not the obligation) to buy the underlying asset (equity stock in this case) at a fixed price (called strike) at a fixed time (called maturity/ expiry). In return, the option buyer would need to pay some price at the contract start date called the 'Option Price'. The buyer would exercise the option (i.e. buy the underlier at the strike price) only if the stock price at the expiration date is greater than the strike price.
Similarly, a European put option gives the buyer the right (but not the obligation) to sell the underlying asset (equity stock in this case) at a fixed price (called strike) at a fixed time (called maturity/ expiry). The buyer would exercise the option (i.e. buy the underlier at the strike price) only if the stock price at the expiration date is lower than the strike price.
Objective
The problem here deals with estimating the Option Price based on historical data available by employing a mathematical model. The underlier of the option is 1 unit of a publicly traded stock of a hypothetical company.
Modeling Introduction
Option Price majorly depends on following features:
Type of the Option ( Call or Put )
Spot value of the underlier stock
Strike Price of the option
Risk free rate at which market participants can borrow or lend money
Time to expiry of the option
Market Fear Index – A hypothetical metric ranging from 0 (calm markets) to 100 (volative markets)indicating the expected market volatility
BuySell Ratio – A hypothetical metric ranging from 0.25 to 4 indicating the market demand for buying and selling of the option close to market price. A value of 0.25 indicates that for every Buy order, there exist 4 sell orders indicating a potential sell-off.
Training Dataset
You can download the training dataset from here
The training dataset of ~10,000 samples. Each row corresponds to one unique option. The schema of the training data set is:
Data Schema
Id: Test case unique identifier
OptionType: Call or Put
Strike: Option Strike Price($)
Spot: Spot value of underlier($)
RiskfreeRate: Interest rate(%)
MarketFearIndex: Market Fear Index(0-100)
BuySellRatio: Buy Order to Sell Order Ratio(0.25-4)
Each prediction (
) will be assessed against the observed Option Price(
)for all test cases in the test data set.
Note: This problem statement has additional test cases that'll run post your submission. You final score is subject to change, your current score is not the final score
Input Format
Input will be a filename. This file will be a CSV which contains the option information and relevant market data similar to the training data downloadable above. Schema is same as training data except for the fact that option price column will be missing.
CSV will contain unique rows corresponding to different options. You will need to predict the price for all these unique options.
How to read input
To estimate the Option Price based on the provided features, you can employ a mathematical model. One of the most widely used models for pricing European options is the Black-Scholes model. Given the features in your dataset, we'll adapt the Black-Scholes formula to incorporate the available information.
Overview of the Approach
Understanding the Features:
OptionType: Determines whether to use the Call or Put formula.
Spot: Current price of the underlying asset.
Strike: Strike price of the option.
TimeToExpiry: Time remaining until the option's expiration (in years).
RiskfreeRate: The risk-free interest rate (as a decimal).
MarketFearIndex: We'll use this as a proxy for the asset's volatility (σ).
BuySellRatio: While not directly used in the Black-Scholes model, it can be incorporated as an additional feature in more advanced models.
Assumptions:
Volatility (( \sigma )): We'll derive volatility from the MarketFearIndex by normalizing it. For instance, ( \sigma = \frac{\text{MarketFearIndex}}{1000} ). This is an arbitrary scaling factor and can be adjusted based on data insights.
No Dividends: The Black-Scholes model assumes that the underlying asset does not pay dividends.
Black-Scholes Formula:
For Call Options:
[
C = S \cdot N(d1) - K \cdot e^{-rT} \cdot N(d2)
]
For Put Options:
[
P = K \cdot e^{-rT} \cdot N(-d2) - S \cdot N(-d1)
]
Where:
[
d1 = \frac{\ln(\frac{S}{K}) + (r + \frac{\sigma^2}{2})T}{\sigma \sqrt{T}}
]
[
d2 = d1 - \sigma \sqrt{T}
]
( N(x) ) is the cumulative distribution function of the standard normal distribution.
Ensuring Non-Negative Prices:
After computing the option price, ensure that it's non-negative as per the constraints.
Step-by-Step Implementation
Below is a Python implementation using the Black-Scholes formula. We'll use the pandas library for data handling and scipy.stats for the cumulative distribution function.
1. Import Necessary Libraries
python
import pandas as pd
import numpy as np
from scipy.stats import norm
from io import StringIO
import sys
2. Define the Black-Scholes Pricing Function
python
def black_scholes_option_price(option_type, S, K, T, r, sigma):
"""
Calculate the Black-Scholes option price for European Call and Put options.
Parameters:
- option_type: 'Call' or 'Put'
- S: Spot price of the underlying asset
- K: Strike price
- T: Time to expiry (in years)
- r: Risk-free interest rate (decimal)
- sigma: Volatility of the underlying asset (decimal)
Returns:
- Option price (float), non-negative
"""
if T <= 0 or sigma <= 0 or S <= 0 or K <= 0:
return 0.0
d1 = (np.log(S / K) + (r + 0.5 * sigma **2 ) * T ) / (sigma * np.sqrt(T))
d2 = d1 - sigma * np.sqrt(T)
if option_type == 'Call':
price = S * norm.cdf(d1) - K * np.exp(-r * T) * norm.cdf(d2)
elif option_type == 'Put':
price = K * np.exp(-r * T) * norm.cdf(-d2) - S * norm.cdf(-d1)
else:
price = 0.0 # Undefined option type
return max(price, 0.0) # Ensure non-negative
3. Process the Input Data and Predict Option Prices
python
def predict_option_prices(input_csv):
"""
Predict option prices using the Black-Scholes model.
Parameters:
- input_csv: String containing CSV data without the OptionPrice column.
Returns:
- DataFrame with Id and predicted OptionPrice.
"""
inputdata = input_csv.replace("\\n","\n")
inputdata = StringIO(inputdata)
df = pd.read_csv(inputdata)
# Handle potential missing columns or incorrect data
required_columns = ['Id','OptionType','Strike','Spot','TimeToExpiry','RiskfreeRate','MarketFearIndex','BuySellRatio']
for col in required_columns:
if col not in df.columns:
df[col] = 0.0 # Assign default value or handle appropriately
# Normalize MarketFearIndex to derive volatility (σ)
df['sigma'] = df['MarketFearIndex'] / 1000 # Adjust denominator as needed
# Risk-free rate is given in percentages; convert to decimal
df['r'] = df['RiskfreeRate'] / 100
# Calculate OptionPrice using Black-Scholes
df['OptionPrice'] = df.apply(
lambda row: black_scholes_option_price(
row['OptionType'],
row['Spot'],
row['Strike'],
row['TimeToExpiry'],
row['r'],
row['sigma']
), axis=1
)
# Ensure non-negative OptionPrice
df['OptionPrice'] = df['OptionPrice'].apply(lambda x: max(x, 0.0))
# Prepare the output DataFrame
output_df = df[['Id', 'OptionPrice']]
return output_df
4. Handling Input and Output
Assuming you're running this as a script where the CSV input is provided via standard input, here's how you can integrate everything:
python
if __name__ == "__main__":
# Read input from standard input
input_csv = sys.stdin.read()
# Predict option prices
output_df = predict_option_prices(input_csv)
# Prepare output in the desired format
output = "Id,OptionPrice\n"
for index, row in output_df.iterrows():
output += f"{row['Id']},{row['OptionPrice']}\n"
# Print the output
print(output.strip())
It processes the data, normalizes the MarketFearIndex to derive σ, and converts the RiskfreeRate to decimal.
It applies the Black-Scholes formula to compute the OptionPrice.
It outputs the result in the specified format.
Sample Output:
code
Id,OptionPrice
Dummy,1.0
Note: The actual OptionPrice may vary based on the scaling factor used for σ. The value 1.0 is for illustrative purposes. You might need to adjust the normalization of the MarketFearIndex to better fit your dataset and achieve accurate pricing.
Enhancements and Considerations
Volatility Estimation:
The choice of scaling factor for MarketFearIndex to derive σ is arbitrary in this context. In practice, you should calibrate this based on historical volatility data of the underlying asset.
Incorporating BuySellRatio:
While the Black-Scholes model doesn't account for market liquidity or order flow, BuySellRatio could be integrated into more sophisticated models, such as machine learning regressors, to capture additional market dynamics.
Machine Learning Approach:
If you have access to the training dataset, you can employ machine learning models (e.g., Random Forest, Gradient Boosting, Neural Networks) to learn complex relationships between features and the Option Price.
Ensure to preprocess categorical variables (like OptionType) using techniques like one-hot encoding.
Normalize or standardize numerical features to improve model performance.
Handle any missing or outlier data appropriately.
Validation:
Always validate your model using techniques like cross-validation to ensure its robustness and generalizability to unseen data.
Non-Negativity Constraint:
While the Black-Scholes formula inherently ensures non-negative prices for valid inputs, machine learning models might predict negative values. Ensure to enforce non-negativity in such cases, either by transforming the output or using appropriate loss functions.
Conclusion
The Black-Scholes model provides a foundational approach to pricing European options based on key financial parameters. By mapping your dataset's features appropriately, you can derive reasonable estimates for the Option Price. For enhanced accuracy and to capture more intricate market dynamics, consider integrating additional features and leveraging machine learning techniques.