Lightweight, parallel, and reproducible Monte Carlo simulation framework
Project description
mcframework
A lightweight, deterministic Monte Carlo simulation framework with robust statistical analytics, parallel execution, and optional GPU acceleration.
- Documentation: https://milanfusco.github.io/mcFramework/
- Source: https://github.com/milanfusco/mcframework
- PyPI: https://pypi.org/project/mcframework/
Installation
pip install mcframework
The base install depends only on NumPy (>= 1.26) and SciPy (>= 1.10). Optional features are available as extras:
pip install "mcframework[torch]" # PyTorch backends (CPU, plus MPS/CUDA when available)
pip install "mcframework[cuda]" # PyTorch and CuPy for the cuRAND backend
pip install "mcframework[viz]" # Matplotlib for visualization
pip install "mcframework[gui]" # PySide6 desktop application
For development, install from source with the test and docs extras:
git clone https://github.com/milanfusco/mcframework.git
cd mcframework
pip install -e ".[dev,test,docs]"
Quick Start
from mcframework import PiEstimationSimulation
sim = PiEstimationSimulation()
sim.set_seed(42)
result = sim.run(10_000, backend="thread")
print(result)
Define a custom simulation by implementing a single method:
from mcframework import MonteCarloSimulation
class DiceSumSimulation(MonteCarloSimulation):
def __init__(self):
super().__init__("Dice Sum")
def single_simulation(self, _rng=None, n_dice: int = 5) -> float:
rng = self._rng(_rng, self.rng)
return float(rng.integers(1, 7, size=n_dice).sum())
sim = DiceSumSimulation()
sim.set_seed(42)
result = sim.run(10_000, backend="thread")
print(f"Mean: {result.mean:.2f}") # ~17.5
Request richer statistics on any run:
result = sim.run(
50_000,
percentiles=(1, 5, 50, 95, 99),
confidence=0.99,
ci_method="auto",
)
print(result.stats["ci_mean"]) # 99% confidence interval
Register and compare multiple simulations with MonteCarloFramework:
from mcframework import MonteCarloFramework, PiEstimationSimulation
fw = MonteCarloFramework()
fw.register_simulation(PiEstimationSimulation())
result = fw.run_simulation("Pi Estimation", 10_000, n_points=5000, backend="thread")
print(result.result_to_string())
Features
Core framework
MonteCarloSimulationbase class: define a simulation by implementingsingle_simulation().- Deterministic parallelism: reproducible results via NumPy
SeedSequencespawning. - Cross-platform execution: threads on POSIX, processes on Windows.
- Structured
SimulationResultwith metadata and formatting.
Statistics engine
- Descriptive statistics: mean, standard deviation, percentiles, skew, kurtosis.
- Parametric confidence intervals: z and t critical values with auto-selection.
- Bootstrap confidence intervals: percentile and BCa (bias-corrected and accelerated).
- Distribution-free bounds: Chebyshev intervals and Markov probability.
Torch backends
- CUDA (NVIDIA): adaptive batch sizing, CUDA streams, dual RNG (
torch.Generatorand cuRAND), native float64, multi-GPU. - MPS (Apple Silicon): Metal Performance Shaders on M1/M2/M3/M4, unified memory, best-effort determinism.
- Torch CPU: vectorized batch execution without GPU hardware.
- Pluggable
ExecutionBackendprotocol for custom backends.
Profiling
- PyTorch profiler integration for CPU and CUDA, with Chrome trace export and optional memory and FLOPs reporting.
Built-in simulations
- Pi estimation (geometric probability on the unit disk).
- Portfolio simulation (geometric Brownian motion wealth dynamics).
- Black-Scholes European and American option pricing with Greeks.
Execution Backends
MonteCarloSimulation.run() selects an execution strategy via the backend parameter:
| Backend | Selection | Description |
|---|---|---|
"sequential" |
backend="sequential" |
Single-threaded execution |
"thread" |
backend="thread" (POSIX default) |
ThreadPoolExecutor, effective when NumPy releases the GIL |
"process" |
backend="process" (Windows default) |
ProcessPoolExecutor, avoids GIL serialization |
"torch" |
`backend="torch", torch_device="cpu" | "mps" |
Performance
Execution time, throughput, and speedup across backends on Apple Silicon. Speedup is measured against single-sample sequential execution; the vectorized Torch and GPU backends benefit most at large simulation counts, where batching amortizes per-call overhead. Run python demos/demo_apple_silicon_benchmark.py to reproduce the figure on your own hardware.
GPU Acceleration
A simulation runs on PyTorch when it sets supports_batch = True and implements torch_batch(). The same implementation runs on CPU, Apple Silicon MPS, and NVIDIA CUDA.
from mcframework import MonteCarloSimulation
import torch
class MySimulation(MonteCarloSimulation):
supports_batch = True
def single_simulation(self, _rng=None, **kwargs):
rng = self._rng(_rng, self.rng)
x, y = rng.random(), rng.random()
return 4.0 if (x * x + y * y) <= 1.0 else 0.0
def torch_batch(self, n, *, device, generator):
x = torch.rand(n, device=device, generator=generator)
y = torch.rand(n, device=device, generator=generator)
return 4.0 * ((x * x + y * y) <= 1.0).float()
result = sim.run(1_000_000, backend="torch", torch_device="cuda") # or "mps", "cpu"
See the backend guides for configuration, determinism notes, and troubleshooting:
GUI Application
The gui extra installs a PySide6 desktop application for Black-Scholes Monte Carlo analysis: live market data, path simulations, option pricing with Greeks, what-if analysis, and 3D price surfaces.
pip install "mcframework[gui]"
python demos/gui/quant_black_scholes.py
Development
pytest --cov=mcframework -v # tests with coverage
ruff check src/ # lint
pylint src/mcframework/ # lint
sphinx-build -b html docs/source docs/_build/html # build docs
The Architecture guide documents the package layout, design patterns, and UML diagrams.
License
MIT License. See LICENSE.
Author
Milan Fusco (mdfusco@student.ysu.edu)
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file mcframework-0.3.0.tar.gz.
File metadata
- Download URL: mcframework-0.3.0.tar.gz
- Upload date:
- Size: 91.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a9fa582ac3426ecc9ae3c35d3f29e5a72c77f92c9e8900d6ad10a4c2b0c495bb
|
|
| MD5 |
c496788b2ec2789092bb9a66aa15435a
|
|
| BLAKE2b-256 |
e857309ee956b6b35747d25c6a826047177254151d52a07c444278e0828ebf1b
|
Provenance
The following attestation bundles were made for mcframework-0.3.0.tar.gz:
Publisher:
publish.yml on milanfusco/mcFramework
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
mcframework-0.3.0.tar.gz -
Subject digest:
a9fa582ac3426ecc9ae3c35d3f29e5a72c77f92c9e8900d6ad10a4c2b0c495bb - Sigstore transparency entry: 1839901589
- Sigstore integration time:
-
Permalink:
milanfusco/mcFramework@05668f6af4fa2d57c4c31bfe11f9ae5a028d2adf -
Branch / Tag:
refs/tags/v0.3.0 - Owner: https://github.com/milanfusco
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@05668f6af4fa2d57c4c31bfe11f9ae5a028d2adf -
Trigger Event:
release
-
Statement type:
File details
Details for the file mcframework-0.3.0-py3-none-any.whl.
File metadata
- Download URL: mcframework-0.3.0-py3-none-any.whl
- Upload date:
- Size: 68.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1fa2600416596ed9e8f8016d7d8e4f937188fd9babef1d0a91ee76bd65670da5
|
|
| MD5 |
f2d9b3b234258d08502d17f78d17fa2f
|
|
| BLAKE2b-256 |
8b588ee561939105af916f24113d384a547210a3c561f88beef890fe80e7b39b
|
Provenance
The following attestation bundles were made for mcframework-0.3.0-py3-none-any.whl:
Publisher:
publish.yml on milanfusco/mcFramework
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
mcframework-0.3.0-py3-none-any.whl -
Subject digest:
1fa2600416596ed9e8f8016d7d8e4f937188fd9babef1d0a91ee76bd65670da5 - Sigstore transparency entry: 1839901617
- Sigstore integration time:
-
Permalink:
milanfusco/mcFramework@05668f6af4fa2d57c4c31bfe11f9ae5a028d2adf -
Branch / Tag:
refs/tags/v0.3.0 - Owner: https://github.com/milanfusco
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@05668f6af4fa2d57c4c31bfe11f9ae5a028d2adf -
Trigger Event:
release
-
Statement type: