montecarlo

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 24, 2024 License: MIT Imports: 3 Imported by: 0

README

Monte Carlo Simulation Library

This library provides tools for running Monte Carlo simulations. It includes functionality for estimating the value of Pi and predicting portfolio values based on daily returns.

Installation

To install the library, use the following command:

go get github.com/datamango-uk/montecarlo

Usage

Estimating the Value of Pi

The following example demonstrates how to use the Monte Carlo simulation to estimate the value of Pi.

package main

import (
    "github.com/datamango-uk/montecarlo"
)

func main() {
    simulation := montecarlo.New(
        100000, // Iterations
        200,    // Worker pool size
        montecarlo.RunFunc(func(_ map[string]float64) float64 {
            x := montecarlo.UniformFloat64(0, 1)
            y := montecarlo.UniformFloat64(0, 1)
            if x*x+y*y <= 1 {
                return 1
            }
            return 0
        }),
    )
    summary := simulation.Run(nil) // This simulation doesnt require any inputs, so we pass nil


    // Using the results to estimate the value of Pi
    var insideCircle float64
    for _, result := range summary.Results {
        insideCircle += result
    }
    piEstimate := (insideCircle / float64(simulation.Iterations)) * 4
    // ~= 3.141592653589793
}
Predicting Portfolio Values

The following example demonstrates how to use the Monte Carlo simulation to predict the value of a portfolio based on daily returns.

// This function simulates the daily returns of a portfolio over a given number of days.
// It uses a normal distribution to generate daily returns based on the mean and standard deviation provided.
// The portfolio value is updated daily and the final value is returned.
func estimatePortfolio(input map[string]float64) float64 {
    portfolioValue := input["initialValue"]
    meanReturn := input["meanReturn"]
    stddevReturn := input["stddevReturn"]
    days := int(input["days"])
    for i := 0; i < days; i++ {
        dailyReturn := montecarlo.NormalFloat64(meanReturn, stddevReturn)
        portfolioValue *= (1 + dailyReturn)
    }
    return portfolioValue
}

func main() {
    summary := montecarlo.New(
        100000, // Iterations
        200,    // Worker pool size
        montecarlo.RunFunc(estimatePortfolio),
    ).Run(map[string]float64{
        "initialValue": 10000.0,
        "meanReturn":   0.0005,
        "stddevReturn": 0.01,
        "days":         365,
    })

    fmt.Println(summary.Stats)
    // {Mean:12036.539859964061 StandardDeviation:2279.4204494720975 Min:6481.218067148653 Max:23742.014047666456}
}
Running multiple simulations

If you want to run a simulation multiple times with different inputs, you can use the RunMultiple method.

func main() {
    simulation := montecarlo.New(100000, 200, montecarlo.RunFunc(estimatePortfolio))
    inputs := []map[string]float64{
        {
            "initialValue": 100.0,
            "meanReturn":   0.0005,
            "stddevReturn": 0.01,
            "days":         365,
        },
        {
            "initialValue": 100.0,
            "meanReturn":   0.00010,
            "stddevReturn": 0.02,
            "days":         200,
        },
    }
    simulation.RunMultiple(inputs...)
    // []Summary{
    //    {Results: [...] Stats:{} InputValues: {"initialValue": 10000.0, "meanReturn": 0.0005, "stddevReturn": 0.01, "days": 365}},
    //    {Results: [...] Stats:{} InputValues: {"initialValue": 10000.0, "meanReturn": 0.00010, "stddevReturn": 0.02, "days": 200}},
    // }
}

License

This project is licensed under the MIT License.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NormalFloat64

func NormalFloat64(mean, stdDeviation float64) float64

Normal returns a random number which falls within the normal distribution as defined by the mean and standard deviation

func UniformFloat64

func UniformFloat64(min, max float64) float64

Uniform returns a random number which is within the specified limits

Types

type RunFunc

type RunFunc func(map[string]float64) float64

Implements Runner

func (RunFunc) Run

func (f RunFunc) Run(i map[string]float64) float64

type Runner

type Runner interface {
	Run(map[string]float64) float64
}

RunFunc is a function type that defines the operation to be performed in each iteration of the simulation.

type Simulation

type Simulation struct {
	Iterations int
	Runner     Runner
	Workers    int
}

Simulation represents a Monte Carlo simulation.

func New

func New(iterations, workers int, runFunc Runner) *Simulation

func (*Simulation) Run

func (s *Simulation) Run(input map[string]float64) Summary

Run executes the simulation and returns a summary.

func (*Simulation) RunMultiple

func (s *Simulation) RunMultiple(inputs ...map[string]float64) []Summary

RunMultiple executes the simulation for each map of inputs provided.

type Statistics

type Statistics struct {
	Mean              float64
	StandardDeviation float64
	Min               float64
	Max               float64
}

Stats represents the statistical results of a simulation.

func Stats

func Stats(results []float64) Statistics

Stats calculates and returns Statistics from a slice of float64.

type Summary

type Summary struct {
	Results     []float64
	Stats       Statistics
	InputValues map[string]float64
}

StatsResults holds the results and statistics of a single simulation run.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL