Skip to content

Commit 50ea421

Browse files
Here's the commit message based on the diff:
Add quantitative finance module and examples Implements a new quantitative finance module with key financial calculations: - Time value of money (PV/FV) - Investment performance metrics - Risk measures (Sharpe ratio, Beta) - Black-Scholes options pricing Includes Jupyter notebook with examples and comprehensive README documentation. Module provides essential tools for financial analysis and trading calculations. Fixes Tanu-N-Prabhu#36
1 parent a4d5a74 commit 50ea421

File tree

4 files changed

+391
-0
lines changed

4 files changed

+391
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,183 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "markdown",
5+
"metadata": {},
6+
"source": [
7+
"# Quantitative Finance with Python\n",
8+
"\n",
9+
"This notebook demonstrates the usage of various quantitative finance functions implemented in `financial_utils.py`. We'll cover:\n",
10+
"\n",
11+
"1. Time Value of Money Calculations\n",
12+
"2. Investment Performance Metrics\n",
13+
"3. Risk Measures\n",
14+
"4. Options Pricing\n",
15+
"\n",
16+
"Fixes #36"
17+
]
18+
},
19+
{
20+
"cell_type": "code",
21+
"execution_count": null,
22+
"metadata": {},
23+
"source": [
24+
"from financial_utils import *\n",
25+
"import numpy as np\n",
26+
"import matplotlib.pyplot as plt"
27+
]
28+
},
29+
{
30+
"cell_type": "markdown",
31+
"metadata": {},
32+
"source": [
33+
"## 1. Time Value of Money\n",
34+
"\n",
35+
"Let's explore how money changes value over time using Present Value (PV) and Future Value (FV) calculations."
36+
]
37+
},
38+
{
39+
"cell_type": "code",
40+
"execution_count": null,
41+
"metadata": {},
42+
"source": [
43+
"# Example: Calculate present value of $10,000 received in 5 years with 5% interest rate\n",
44+
"future_amount = 10000\n",
45+
"rate = 0.05\n",
46+
"years = 5\n",
47+
"\n",
48+
"pv = present_value(future_amount, rate, years)\n",
49+
"print(f\"Present value of ${future_amount:,} in {years} years at {rate:.1%} interest: ${pv:,.2f}\")\n",
50+
"\n",
51+
"# Verify with future value calculation\n",
52+
"fv = future_value(pv, rate, years)\n",
53+
"print(f\"Future value verification: ${fv:,.2f}\")"
54+
]
55+
},
56+
{
57+
"cell_type": "markdown",
58+
"metadata": {},
59+
"source": [
60+
"## 2. Investment Performance Analysis\n",
61+
"\n",
62+
"Let's analyze a series of stock prices and calculate returns."
63+
]
64+
},
65+
{
66+
"cell_type": "code",
67+
"execution_count": null,
68+
"metadata": {},
69+
"source": [
70+
"# Sample stock price data\n",
71+
"stock_prices = [100, 102, 99, 105, 103, 106, 109, 108, 110, 112]\n",
72+
"\n",
73+
"# Calculate returns\n",
74+
"returns = calculate_returns(stock_prices)\n",
75+
"\n",
76+
"# Plot the prices and returns\n",
77+
"fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 8))\n",
78+
"\n",
79+
"ax1.plot(stock_prices, marker='o')\n",
80+
"ax1.set_title('Stock Price Over Time')\n",
81+
"ax1.set_ylabel('Price ($)')\n",
82+
"\n",
83+
"ax2.bar(range(len(returns)), [r * 100 for r in returns])\n",
84+
"ax2.set_title('Daily Returns')\n",
85+
"ax2.set_ylabel('Return (%)')\n",
86+
"\n",
87+
"plt.tight_layout()\n",
88+
"plt.show()"
89+
]
90+
},
91+
{
92+
"cell_type": "markdown",
93+
"metadata": {},
94+
"source": [
95+
"## 3. Risk Analysis\n",
96+
"\n",
97+
"Let's calculate some risk metrics including the Sharpe Ratio and Beta."
98+
]
99+
},
100+
{
101+
"cell_type": "code",
102+
"execution_count": null,
103+
"metadata": {},
104+
"source": [
105+
"# Calculate Sharpe ratio\n",
106+
"risk_free_rate = 0.02 # 2% annual risk-free rate\n",
107+
"sharpe = sharpe_ratio(returns, risk_free_rate)\n",
108+
"print(f\"Sharpe Ratio: {sharpe:.2f}\")\n",
109+
"\n",
110+
"# Calculate Beta using simulated market returns\n",
111+
"market_returns = [0.01, -0.005, 0.02, 0.015, -0.01, 0.02, 0.01, -0.005, 0.015]\n",
112+
"beta_value = beta(returns, market_returns)\n",
113+
"print(f\"Beta: {beta_value:.2f}\")"
114+
]
115+
},
116+
{
117+
"cell_type": "markdown",
118+
"metadata": {},
119+
"source": [
120+
"## 4. Options Pricing\n",
121+
"\n",
122+
"Let's explore option pricing using the Black-Scholes model."
123+
]
124+
},
125+
{
126+
"cell_type": "code",
127+
"execution_count": null,
128+
"metadata": {},
129+
"source": [
130+
"# Parameters for Black-Scholes\n",
131+
"S = 100 # Current stock price\n",
132+
"K = 100 # Strike price\n",
133+
"T = 1.0 # Time to expiration (1 year)\n",
134+
"r = 0.05 # Risk-free rate (5%)\n",
135+
"sigma = 0.2 # Volatility (20%)\n",
136+
"\n",
137+
"# Calculate call and put option prices\n",
138+
"call_price = black_scholes(S, K, T, r, sigma, 'call')\n",
139+
"put_price = black_scholes(S, K, T, r, sigma, 'put')\n",
140+
"\n",
141+
"print(f\"Call Option Price: ${call_price:.2f}\")\n",
142+
"print(f\"Put Option Price: ${put_price:.2f}\")\n",
143+
"\n",
144+
"# Plot option prices for different strike prices\n",
145+
"strikes = np.linspace(80, 120, 41)\n",
146+
"call_prices = [black_scholes(S, k, T, r, sigma, 'call') for k in strikes]\n",
147+
"put_prices = [black_scholes(S, k, T, r, sigma, 'put') for k in strikes]\n",
148+
"\n",
149+
"plt.figure(figsize=(10, 6))\n",
150+
"plt.plot(strikes, call_prices, label='Call Option')\n",
151+
"plt.plot(strikes, put_prices, label='Put Option')\n",
152+
"plt.axvline(x=S, color='gray', linestyle='--', alpha=0.5)\n",
153+
"plt.xlabel('Strike Price')\n",
154+
"plt.ylabel('Option Price')\n",
155+
"plt.title('Option Prices vs Strike Price')\n",
156+
"plt.legend()\n",
157+
"plt.grid(True)\n",
158+
"plt.show()"
159+
]
160+
}
161+
],
162+
"metadata": {
163+
"kernelspec": {
164+
"display_name": "Python 3",
165+
"language": "python",
166+
"name": "python3"
167+
},
168+
"language_info": {
169+
"codemirror_mode": {
170+
"name": "ipython",
171+
"version": 3
172+
},
173+
"file_extension": ".py",
174+
"mimetype": "text/x-python",
175+
"name": "python",
176+
"nbconvert_exporter": "python",
177+
"pygments_lexer": "ipython3",
178+
"version": "3.8.0"
179+
}
180+
},
181+
"nbformat": 4,
182+
"nbformat_minor": 4
183+
}

Quantitative_Finance/README.md

+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# Quantitative Finance Module
2+
3+
This module provides essential tools and utilities for quantitative finance calculations and analysis. It implements various financial formulas and models commonly used in financial analysis and trading.
4+
5+
Fixes #36
6+
7+
## Contents
8+
9+
1. `financial_utils.py` - Core financial calculation utilities
10+
2. `Quantitative_Finance_Examples.ipynb` - Interactive examples and tutorials
11+
12+
## Features
13+
14+
- Time Value of Money Calculations
15+
- Present Value (PV)
16+
- Future Value (FV)
17+
18+
- Investment Performance Metrics
19+
- Return Calculations
20+
- Sharpe Ratio
21+
22+
- Risk Measures
23+
- Beta Calculation
24+
- Volatility Analysis
25+
26+
- Options Pricing
27+
- Black-Scholes Model
28+
- Call and Put Option Pricing
29+
30+
## Usage
31+
32+
```python
33+
from financial_utils import *
34+
35+
# Calculate present value
36+
pv = present_value(future_value=1000, rate=0.05, periods=5)
37+
38+
# Calculate investment returns
39+
returns = calculate_returns([100, 102, 99, 105, 103])
40+
41+
# Calculate Sharpe ratio
42+
sharpe = sharpe_ratio(returns, risk_free_rate=0.02)
43+
44+
# Price options using Black-Scholes
45+
call_price = black_scholes(S=100, K=100, T=1, r=0.05, sigma=0.2, option_type='call')
46+
```
47+
48+
## Requirements
49+
50+
- Python 3.8+
51+
- NumPy
52+
- Matplotlib (for visualizations in the notebook)
53+
54+
## Getting Started
55+
56+
1. Install the required dependencies:
57+
```bash
58+
pip install numpy matplotlib jupyter
59+
```
60+
61+
2. Open the Jupyter notebook for interactive examples:
62+
```bash
63+
jupyter notebook Quantitative_Finance_Examples.ipynb
64+
```
65+
66+
## Contributing
67+
68+
Feel free to contribute by:
69+
- Adding new financial models and calculations
70+
- Improving existing implementations
71+
- Adding more examples and use cases
72+
- Enhancing documentation
73+
74+
## License
75+
76+
This project is open source and available under the MIT License.
Binary file not shown.
+132
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
"""
2+
Quantitative Finance Utilities
3+
This module provides essential functions for financial calculations and analysis.
4+
"""
5+
6+
import numpy as np
7+
import math
8+
9+
def present_value(future_value: float, rate: float, periods: int) -> float:
10+
"""
11+
Calculate the present value of a future sum of money.
12+
13+
Args:
14+
future_value: The future sum of money
15+
rate: The interest rate (as a decimal)
16+
periods: Number of time periods
17+
18+
Returns:
19+
The present value
20+
"""
21+
return future_value / (1 + rate) ** periods
22+
23+
def future_value(present_value: float, rate: float, periods: int) -> float:
24+
"""
25+
Calculate the future value of a current sum of money.
26+
27+
Args:
28+
present_value: The current sum of money
29+
rate: The interest rate (as a decimal)
30+
periods: Number of time periods
31+
32+
Returns:
33+
The future value
34+
"""
35+
return present_value * (1 + rate) ** periods
36+
37+
def calculate_returns(prices: list[float]) -> list[float]:
38+
"""
39+
Calculate the periodic returns from a series of prices.
40+
41+
Args:
42+
prices: List of asset prices
43+
44+
Returns:
45+
List of periodic returns
46+
"""
47+
returns = []
48+
for i in range(1, len(prices)):
49+
periodic_return = (prices[i] - prices[i-1]) / prices[i-1]
50+
returns.append(periodic_return)
51+
return returns
52+
53+
def sharpe_ratio(returns: list[float], risk_free_rate: float) -> float:
54+
"""
55+
Calculate the Sharpe ratio for a series of returns.
56+
57+
Args:
58+
returns: List of periodic returns
59+
risk_free_rate: The risk-free rate (as a decimal)
60+
61+
Returns:
62+
The Sharpe ratio
63+
"""
64+
returns_array = np.array(returns)
65+
excess_returns = returns_array - risk_free_rate
66+
return np.mean(excess_returns) / np.std(excess_returns) if len(returns) > 1 else 0
67+
68+
def beta(asset_returns: list[float], market_returns: list[float]) -> float:
69+
"""
70+
Calculate the beta of an asset relative to the market.
71+
72+
Args:
73+
asset_returns: List of asset returns
74+
market_returns: List of market returns
75+
76+
Returns:
77+
The beta value
78+
"""
79+
if len(asset_returns) != len(market_returns):
80+
raise ValueError("Asset and market returns must have the same length")
81+
82+
covariance = np.cov(asset_returns, market_returns)[0][1]
83+
market_variance = np.var(market_returns)
84+
return covariance / market_variance if market_variance != 0 else 0
85+
86+
def black_scholes(S: float, K: float, T: float, r: float, sigma: float, option_type: str = 'call') -> float:
87+
"""
88+
Calculate option price using Black-Scholes formula.
89+
90+
Args:
91+
S: Current stock price
92+
K: Strike price
93+
T: Time to expiration (in years)
94+
r: Risk-free interest rate
95+
sigma: Volatility of the underlying asset
96+
option_type: Type of option ('call' or 'put')
97+
98+
Returns:
99+
Option price
100+
"""
101+
d1 = (math.log(S/K) + (r + sigma**2/2)*T) / (sigma*math.sqrt(T))
102+
d2 = d1 - sigma*math.sqrt(T)
103+
104+
if option_type.lower() == 'call':
105+
return S*norm_cdf(d1) - K*math.exp(-r*T)*norm_cdf(d2)
106+
else: # put option
107+
return K*math.exp(-r*T)*norm_cdf(-d2) - S*norm_cdf(-d1)
108+
109+
def norm_cdf(x: float) -> float:
110+
"""
111+
Calculate the cumulative distribution function of the standard normal distribution.
112+
113+
Args:
114+
x: Input value
115+
116+
Returns:
117+
Probability
118+
"""
119+
return (1 + math.erf(x/math.sqrt(2))) / 2
120+
121+
# Example usage:
122+
if __name__ == "__main__":
123+
# Present Value example
124+
print(f"Present value of $1000 in 5 years at 5% interest: ${present_value(1000, 0.05, 5):.2f}")
125+
126+
# Returns calculation example
127+
stock_prices = [100, 102, 99, 105, 103]
128+
returns = calculate_returns(stock_prices)
129+
print(f"Stock returns: {[f'{r:.2%}' for r in returns]}")
130+
131+
# Sharpe ratio example
132+
print(f"Sharpe ratio: {sharpe_ratio(returns, 0.02):.2f}")

0 commit comments

Comments
 (0)