From 50ea4219df561c3f60a659ee0bb8c89dcb5d8214 Mon Sep 17 00:00:00 2001 From: agentmarketbot Date: Sun, 26 Jan 2025 22:41:14 +0000 Subject: [PATCH] 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 #36 --- .../Quantitative_Finance_Examples.ipynb | 183 ++++++++++++++++++ Quantitative_Finance/README.md | 76 ++++++++ .../financial_utils.cpython-312.pyc | Bin 0 -> 5737 bytes Quantitative_Finance/financial_utils.py | 132 +++++++++++++ 4 files changed, 391 insertions(+) create mode 100644 Quantitative_Finance/Quantitative_Finance_Examples.ipynb create mode 100644 Quantitative_Finance/README.md create mode 100644 Quantitative_Finance/__pycache__/financial_utils.cpython-312.pyc create mode 100644 Quantitative_Finance/financial_utils.py diff --git a/Quantitative_Finance/Quantitative_Finance_Examples.ipynb b/Quantitative_Finance/Quantitative_Finance_Examples.ipynb new file mode 100644 index 0000000..bdc7e8d --- /dev/null +++ b/Quantitative_Finance/Quantitative_Finance_Examples.ipynb @@ -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 +} \ No newline at end of file diff --git a/Quantitative_Finance/README.md b/Quantitative_Finance/README.md new file mode 100644 index 0000000..6ece22e --- /dev/null +++ b/Quantitative_Finance/README.md @@ -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. \ No newline at end of file diff --git a/Quantitative_Finance/__pycache__/financial_utils.cpython-312.pyc b/Quantitative_Finance/__pycache__/financial_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7b75d80cd981f2a765b4d115c2040f55db0ae42 GIT binary patch literal 5737 zcmcgwTWlQF89uW+d+}c5_!`F~6JukW#E$I{(rhj!AthWL5<3Q&!gjnfYfrovb7nS) zmkqTLsvH#&TZ!u3hN`9@v5~9R5lA(vRJnaAQeSqn(1sxop!T78TX0|6m-he9?A39q zB2_)oxy-r#=ltLQo&U@q-EIeg@T-r1J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!;EPP?t@Rj0UdEqrC;h3CSI%m<;kz& z*9KwF{V=M#PPh5}QZ(TA>y}6?JUzp1a^rw3!BAAxbTbHMym}E`Iv+x%;_HX`ob0wn zPnI%EV~3{0?jzti;H1EC5lwfgD4gGT=rM;E1VD>shu&uxuKlp_hwCUEf)><<`ZlC_ zGskgXo6H=)?jT&<7sQ$8U0mOiB~KtrpJmzVFw54?u484s)y4H29r}$9{YHm=qeFkb z)x*^#rKSC;sXT#VT3XqEV`?3XdBM%Sz$M$0vDEH7!SYJX$k!Uy*>`@&7VadMNN)aq}P^=1G_X^K^reuk1JSwZeDi?2AT4CJ16+&wQ_g z>z#*9LYC}U$1LAMc-LI~mU-J(d`-qR_&fI}QfB1E%-Bo0$G(?&`TLncG2`aY1>MDZu_GvYNq8-#&P&F{z$%o@GbxN#zP+Psp$RuzQK9?sN>%$0+<8< literal 0 HcmV?d00001 diff --git a/Quantitative_Finance/financial_utils.py b/Quantitative_Finance/financial_utils.py new file mode 100644 index 0000000..2fd9832 --- /dev/null +++ b/Quantitative_Finance/financial_utils.py @@ -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}") \ No newline at end of file