Wednesday, September 11, 2024

Monte Carlo simulations using Python for different mathematical problems:

 Here are a few more Monte Carlo simulations using Python for different mathematical problems:


1. Monte Carlo Integration


Monte Carlo integration is a method to approximate definite integrals using random sampling. For example, let’s estimate the value of the integral of the function  over the interval [0, 1].


Example: Estimating the integral of  from 0 to 1


The exact solution is .


Here’s how we can use Monte Carlo integration:


import numpy as np


def monte_carlo_integration(num_samples: int) -> float:

    # Randomly sample points from 0 to 1

    x = np.random.uniform(0, 1, num_samples)

    

    # Apply the function to each sampled point

    y = x**2

    

    # Estimate the integral as the mean of f(x)

    integral_estimate = np.mean(y)

    

    return integral_estimate


# Run the simulation with a large number of samples

num_samples = 1000000

integral_estimate = monte_carlo_integration(num_samples)

integral_estimate


Explanation:


We generate random points  uniformly in the interval [0, 1].


We compute  for each point.


The mean of the function values approximates the integral.



2. Monte Carlo Simulation for Buffon's Needle Problem


Buffon's Needle is a famous problem that estimates the value of Ο€ by dropping needles on a floor with parallel lines spaced equally apart. The probability that a needle will cross a line relates to the value of Ο€.


Problem Setup:


Needles of length  are dropped on a floor with lines spaced distance  apart.


If , the probability  that the needle crosses a line is .



We can use this relationship to estimate Ο€.


import numpy as np


def buffon_needle(num_trials: int, needle_length: float, line_distance: float) -> float:

    hits = 0

    for _ in range(num_trials):

        # Drop the needle: random angle and position

        angle = np.random.uniform(0, np.pi / 2)

        center_distance = np.random.uniform(0, line_distance / 2)

        

        # Check if the needle crosses a line

        if center_distance <= (needle_length / 2) * np.sin(angle):

            hits += 1

    

    # Estimate Ο€ from the probability

    pi_estimate = (2 * needle_length * num_trials) / (hits * line_distance)

    

    return pi_estimate


# Parameters for the simulation

needle_length = 1

line_distance = 1

num_trials = 1000000


# Run the Buffon Needle simulation

pi_estimate = buffon_needle(num_trials, needle_length, line_distance)

pi_estimate


Explanation:


We simulate the random drop of a needle by generating a random angle and position.


The number of times the needle crosses a line helps estimate Ο€.



3. Estimating the Area of a Circle Using Monte Carlo


We can estimate the area of a circle using random sampling within a bounding square. If we throw random points into a square that bounds a circle, the ratio of points inside the circle to the total points approximates the area of the circle.


Example: Estimating the area of a unit circle


The exact area of a unit circle (radius 1) is Ο€.


import numpy as np


def monte_carlo_circle_area(num_points: int) -> float:

    # Generate random points in the square [-1, 1] x [-1, 1]

    x = np.random.uniform(-1, 1, num_points)

    y = np.random.uniform(-1, 1, num_points)

    

    # Check how many points fall inside the circle

    inside_circle = (x**2 + y**2) <= 1

    

    # Estimate the area of the circle

    area_estimate = 4 * np.mean(inside_circle)  # since square area is 4

    return area_estimate


# Run the simulation with a large number of points

num_points = 1000000

circle_area_estimate = monte_carlo_circle_area(num_points)

circle_area_estimate


Explanation:


We randomly generate points within a square that bounds the circle.


The fraction of points inside the circle helps estimate the area (multiplied by 4 to account for the area of the square).



4. Monte Carlo Simulation for Estimating Stock Option Prices (Black-Scholes Model)


The Black-Scholes model is widely used to price options. Monte Carlo simulation can help estimate the price of an option based on random samples of the underlying asset’s future price.


Example: Estimating the price of a European call option


Given the stock price , strike price , risk-free rate , volatility , and time to maturity , we can simulate the future stock price and estimate the option price.


import numpy as np


def monte_carlo_option_price(S0, K, r, sigma, T, num_simulations):

    # Simulate future stock prices using geometric Brownian motion

    Z = np.random.standard_normal(num_simulations)

    ST = S0 * np.exp((r - 0.5 * sigma**2) * T + sigma * np.sqrt(T) * Z)

    

    # Calculate the payoff for a European call option

    payoff = np.maximum(ST - K, 0)

    

    # Discount the expected payoff back to present value

    option_price = np.exp(-r * T) * np.mean(payoff)

    

    return option_price


# Parameters for the simulation

S0 = 100    # Initial stock price

K = 105     # Strike price

r = 0.05    # Risk-free rate

sigma = 0.2 # Volatility

T = 1       # Time to maturity (1 year)

num_simulations = 1000000


# Run the Monte Carlo option pricing simulation

option_price_estimate = monte_carlo_option_price(S0, K, r, sigma, T, num_simulations)

option_price_estimate


Explanation:


We simulate future stock prices  using a random sample from a normal distribution.


We calculate the payoff of the option for each simulation and then discount it back to the present value.


The average payoff provides the estimated option price.



These are some additional mathematical and financial Monte Carlo simulations you can implement in Python. Each demonstrates a different aspect of Monte Carlo techniques applied to various problems. Let me know if you'd like to dive deeper into any of these examples!


No comments:

Meet the Authors
Zacharia Maganga’s blog features multiple contributors with clear activity status.
Active ✔
πŸ§‘‍πŸ’»
Zacharia Maganga
Lead Author
Active ✔
πŸ‘©‍πŸ’»
Linda Bahati
Co‑Author
Active ✔
πŸ‘¨‍πŸ’»
Jefferson Mwangolo
Co‑Author
Inactive ✖
πŸ‘©‍πŸŽ“
Florence Wavinya
Guest Author
Inactive ✖
πŸ‘©‍πŸŽ“
Esther Njeri
Guest Author
Inactive ✖
πŸ‘©‍πŸŽ“
Clemence Mwangolo
Guest Author

x̄ - > Bloomberg BS Model - King James Rodriguez Brazil 2014

Bloomberg BS Model - King James Rodriguez Brazil 2014 πŸ”Š Read ⏸ Pause ▶ Resume ⏹ Stop ⚽ The Silent Kin...

Labels

Data (3) Infographics (3) Mathematics (3) Sociology (3) Algebraic structure (2) Environment (2) Machine Learning (2) Sociology of Religion and Sexuality (2) kuku (2) #Mbele na Biz (1) #StopTheSpread (1) #stillamother #wantedchoosenplanned #bereavedmothersday #mothersday (1) #university#ai#mathematics#innovation#education#education #research#elearning #edtech (1) ( Migai Winter 2011) (1) 8-4-4 (1) AI Bubble (1) Accrual Accounting (1) Agriculture (1) Algebra (1) Algorithms (1) Amusement of mathematics (1) Analysis GDP VS employment growth (1) Analysis report (1) Animal Health (1) Applied AI Lab (1) Arithmetic operations (1) Black-Scholes (1) Bleu Ranger FC (1) Blockchain (1) CATS (1) CBC (1) Capital markets (1) Cash Accounting (1) Cauchy integral theorem (1) Coding theory. (1) Computer Science (1) Computer vision (1) Creative Commons (1) Cryptocurrency (1) Cryptography (1) Currencies (1) DISC (1) Data Analysis (1) Data Science (1) Decision-Making (1) Differential Equations (1) Economic Indicators (1) Economics (1) Education (1) Experimental design and sampling (1) Financial Data (1) Financial markets (1) Finite fields (1) Fractals (1) Free MCBoot (1) Funds (1) Future stock price (1) Galois fields (1) Game (1) Grants (1) Health (1) Hedging my bet (1) Holormophic (1) IS–LM (1) Indices (1) Infinite (1) Investment (1) KCSE (1) KJSE (1) Kapital Inteligence (1) Kenya education (1) Latex (1) Law (1) Limit (1) Logic (1) MBTI (1) Market Analysis. (1) Market pulse (1) Mathematical insights (1) Moby dick; ot The Whale (1) Montecarlo simulation (1) Motorcycle Taxi Rides (1) Mural (1) Nature Shape (1) Observed paterns (1) Olympiad (1) Open PS2 Loader (1) Outta Pharaoh hand (1) Physics (1) Predictions (1) Programing (1) Proof (1) Python Code (1) Quiz (1) Quotation (1) R programming (1) RAG (1) RL (1) Remove Duplicate Rows (1) Remove Rows with Missing Values (1) Replace Missing Values with Another Value (1) Risk Management (1) Safety (1) Science (1) Scientific method (1) Semantics (1) Statistical Modelling (1) Stochastic (1) Stock Markets (1) Stock price dynamics (1) Stock-Price (1) Stocks (1) Survey (1) Sustainable Agriculture (1) Symbols (1) Syntax (1) Taroch Coalition (1) The Nature of Mathematics (1) The safe way of science (1) Travel (1) Troubleshoting (1) Tsavo National park (1) Volatility (1) World time (1) Youtube Videos (1) analysis (1) and Belbin Insights (1) competency-based curriculum (1) conformal maps. (1) decisions (1) over-the-counter (OTC) markets (1) pedagogy (1) pi (1) power series (1) residues (1) stock exchange (1) uplifted (1)

Followers