Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Quantitative Finance Code in Python - Fixes #36 #45

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
183 changes: 183 additions & 0 deletions Quantitative_Finance/Quantitative_Finance_Examples.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Quantitative Finance with Python\n",
"\n",
"This notebook demonstrates the usage of various quantitative finance functions implemented in `financial_utils.py`. We'll cover:\n",
"\n",
"1. Time Value of Money Calculations\n",
"2. Investment Performance Metrics\n",
"3. Risk Measures\n",
"4. Options Pricing\n",
"\n",
"Fixes #36"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"source": [
"from financial_utils import *\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1. Time Value of Money\n",
"\n",
"Let's explore how money changes value over time using Present Value (PV) and Future Value (FV) calculations."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"source": [
"# Example: Calculate present value of $10,000 received in 5 years with 5% interest rate\n",
"future_amount = 10000\n",
"rate = 0.05\n",
"years = 5\n",
"\n",
"pv = present_value(future_amount, rate, years)\n",
"print(f\"Present value of ${future_amount:,} in {years} years at {rate:.1%} interest: ${pv:,.2f}\")\n",
"\n",
"# Verify with future value calculation\n",
"fv = future_value(pv, rate, years)\n",
"print(f\"Future value verification: ${fv:,.2f}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2. Investment Performance Analysis\n",
"\n",
"Let's analyze a series of stock prices and calculate returns."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"source": [
"# Sample stock price data\n",
"stock_prices = [100, 102, 99, 105, 103, 106, 109, 108, 110, 112]\n",
"\n",
"# Calculate returns\n",
"returns = calculate_returns(stock_prices)\n",
"\n",
"# Plot the prices and returns\n",
"fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 8))\n",
"\n",
"ax1.plot(stock_prices, marker='o')\n",
"ax1.set_title('Stock Price Over Time')\n",
"ax1.set_ylabel('Price ($)')\n",
"\n",
"ax2.bar(range(len(returns)), [r * 100 for r in returns])\n",
"ax2.set_title('Daily Returns')\n",
"ax2.set_ylabel('Return (%)')\n",
"\n",
"plt.tight_layout()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3. Risk Analysis\n",
"\n",
"Let's calculate some risk metrics including the Sharpe Ratio and Beta."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"source": [
"# Calculate Sharpe ratio\n",
"risk_free_rate = 0.02 # 2% annual risk-free rate\n",
"sharpe = sharpe_ratio(returns, risk_free_rate)\n",
"print(f\"Sharpe Ratio: {sharpe:.2f}\")\n",
"\n",
"# Calculate Beta using simulated market returns\n",
"market_returns = [0.01, -0.005, 0.02, 0.015, -0.01, 0.02, 0.01, -0.005, 0.015]\n",
"beta_value = beta(returns, market_returns)\n",
"print(f\"Beta: {beta_value:.2f}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4. Options Pricing\n",
"\n",
"Let's explore option pricing using the Black-Scholes model."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"source": [
"# Parameters for Black-Scholes\n",
"S = 100 # Current stock price\n",
"K = 100 # Strike price\n",
"T = 1.0 # Time to expiration (1 year)\n",
"r = 0.05 # Risk-free rate (5%)\n",
"sigma = 0.2 # Volatility (20%)\n",
"\n",
"# Calculate call and put option prices\n",
"call_price = black_scholes(S, K, T, r, sigma, 'call')\n",
"put_price = black_scholes(S, K, T, r, sigma, 'put')\n",
"\n",
"print(f\"Call Option Price: ${call_price:.2f}\")\n",
"print(f\"Put Option Price: ${put_price:.2f}\")\n",
"\n",
"# Plot option prices for different strike prices\n",
"strikes = np.linspace(80, 120, 41)\n",
"call_prices = [black_scholes(S, k, T, r, sigma, 'call') for k in strikes]\n",
"put_prices = [black_scholes(S, k, T, r, sigma, 'put') for k in strikes]\n",
"\n",
"plt.figure(figsize=(10, 6))\n",
"plt.plot(strikes, call_prices, label='Call Option')\n",
"plt.plot(strikes, put_prices, label='Put Option')\n",
"plt.axvline(x=S, color='gray', linestyle='--', alpha=0.5)\n",
"plt.xlabel('Strike Price')\n",
"plt.ylabel('Option Price')\n",
"plt.title('Option Prices vs Strike Price')\n",
"plt.legend()\n",
"plt.grid(True)\n",
"plt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.0"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
76 changes: 76 additions & 0 deletions Quantitative_Finance/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Quantitative Finance Module

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.

Fixes #36

## Contents

1. `financial_utils.py` - Core financial calculation utilities
2. `Quantitative_Finance_Examples.ipynb` - Interactive examples and tutorials

## Features

- Time Value of Money Calculations
- Present Value (PV)
- Future Value (FV)

- Investment Performance Metrics
- Return Calculations
- Sharpe Ratio

- Risk Measures
- Beta Calculation
- Volatility Analysis

- Options Pricing
- Black-Scholes Model
- Call and Put Option Pricing

## Usage

```python
from financial_utils import *

# Calculate present value
pv = present_value(future_value=1000, rate=0.05, periods=5)

# Calculate investment returns
returns = calculate_returns([100, 102, 99, 105, 103])

# Calculate Sharpe ratio
sharpe = sharpe_ratio(returns, risk_free_rate=0.02)

# Price options using Black-Scholes
call_price = black_scholes(S=100, K=100, T=1, r=0.05, sigma=0.2, option_type='call')
```

## Requirements

- Python 3.8+
- NumPy
- Matplotlib (for visualizations in the notebook)

## Getting Started

1. Install the required dependencies:
```bash
pip install numpy matplotlib jupyter
```

2. Open the Jupyter notebook for interactive examples:
```bash
jupyter notebook Quantitative_Finance_Examples.ipynb
```

## Contributing

Feel free to contribute by:
- Adding new financial models and calculations
- Improving existing implementations
- Adding more examples and use cases
- Enhancing documentation

## License

This project is open source and available under the MIT License.
Binary file not shown.
132 changes: 132 additions & 0 deletions Quantitative_Finance/financial_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
"""
Quantitative Finance Utilities
This module provides essential functions for financial calculations and analysis.
"""

import numpy as np
import math

def present_value(future_value: float, rate: float, periods: int) -> float:
"""
Calculate the present value of a future sum of money.

Args:
future_value: The future sum of money
rate: The interest rate (as a decimal)
periods: Number of time periods

Returns:
The present value
"""
return future_value / (1 + rate) ** periods

def future_value(present_value: float, rate: float, periods: int) -> float:
"""
Calculate the future value of a current sum of money.

Args:
present_value: The current sum of money
rate: The interest rate (as a decimal)
periods: Number of time periods

Returns:
The future value
"""
return present_value * (1 + rate) ** periods

def calculate_returns(prices: list[float]) -> list[float]:
"""
Calculate the periodic returns from a series of prices.

Args:
prices: List of asset prices

Returns:
List of periodic returns
"""
returns = []
for i in range(1, len(prices)):
periodic_return = (prices[i] - prices[i-1]) / prices[i-1]
returns.append(periodic_return)
return returns

def sharpe_ratio(returns: list[float], risk_free_rate: float) -> float:
"""
Calculate the Sharpe ratio for a series of returns.

Args:
returns: List of periodic returns
risk_free_rate: The risk-free rate (as a decimal)

Returns:
The Sharpe ratio
"""
returns_array = np.array(returns)
excess_returns = returns_array - risk_free_rate
return np.mean(excess_returns) / np.std(excess_returns) if len(returns) > 1 else 0

def beta(asset_returns: list[float], market_returns: list[float]) -> float:
"""
Calculate the beta of an asset relative to the market.

Args:
asset_returns: List of asset returns
market_returns: List of market returns

Returns:
The beta value
"""
if len(asset_returns) != len(market_returns):
raise ValueError("Asset and market returns must have the same length")

covariance = np.cov(asset_returns, market_returns)[0][1]
market_variance = np.var(market_returns)
return covariance / market_variance if market_variance != 0 else 0

def black_scholes(S: float, K: float, T: float, r: float, sigma: float, option_type: str = 'call') -> float:
"""
Calculate option price using Black-Scholes formula.

Args:
S: Current stock price
K: Strike price
T: Time to expiration (in years)
r: Risk-free interest rate
sigma: Volatility of the underlying asset
option_type: Type of option ('call' or 'put')

Returns:
Option price
"""
d1 = (math.log(S/K) + (r + sigma**2/2)*T) / (sigma*math.sqrt(T))
d2 = d1 - sigma*math.sqrt(T)

if option_type.lower() == 'call':
return S*norm_cdf(d1) - K*math.exp(-r*T)*norm_cdf(d2)
else: # put option
return K*math.exp(-r*T)*norm_cdf(-d2) - S*norm_cdf(-d1)

def norm_cdf(x: float) -> float:
"""
Calculate the cumulative distribution function of the standard normal distribution.

Args:
x: Input value

Returns:
Probability
"""
return (1 + math.erf(x/math.sqrt(2))) / 2

# Example usage:
if __name__ == "__main__":
# Present Value example
print(f"Present value of $1000 in 5 years at 5% interest: ${present_value(1000, 0.05, 5):.2f}")

# Returns calculation example
stock_prices = [100, 102, 99, 105, 103]
returns = calculate_returns(stock_prices)
print(f"Stock returns: {[f'{r:.2%}' for r in returns]}")

# Sharpe ratio example
print(f"Sharpe ratio: {sharpe_ratio(returns, 0.02):.2f}")