VOOZH about

URL: https://www.analyticsvidhya.com/blog/2021/05/create-a-dummy-stock-market-using-geometric-brownian-motion-in-python/

⇱ Geometric Brownian Motion. | Dummy Stock Market with GBM


India's Most Futuristic AI Conference Is Back – Bigger, Sharper, Bolder

  • d
  • :
  • h
  • :
  • m
  • :
  • s

Create a Dummy Stock Market Using Geometric Brownian Motion in Python

Arnab M Last Updated : 28 Oct, 2024
5 min read
This article was published as a part of the Data Science Blogathon.

Introduction :

The goal is to create a replica of a financial stock market or this can be extended to the cryptocurrency market also using Geometric Brownian Motion.

Stochastic processes are full of options and anyone who wants to begin trading can first experiment on a demo market and strategies accordingly as to how the market plays out when the variables change. You can simulate a market and change your strategy and plan it out accordingly and decide the final one for you.

ROI ( Return on Investment)

The most important factor in the stock market is the returns on any share. If we consider the price of a particular day β€˜n’ and let the previous day be denoted by β€˜n-1’. Then the returns can be calculated by the formula :

πŸ‘ https://miro.medium.com/max/230/1*KcG2pmCIfDQp7pFwnualRw.png dummy stock market

Then using this formula we can create a price time series by using the following formula :

πŸ‘ https://miro.medium.com/max/258/1*oiPAm7rvQCwIC-pUe5kNaQ.png

So if we know the first starting price or p0 then we can calculate the future price of the stock using the sequence of returns.

The one thing about the model is that all the returns are stochastic objects and hence all the different realization of the various returns will give us a different time series for all the prices. The behavior of the price is modeled in this way.

Hence to prepare our model, we need to assume a few parameters about the returns and then apply the above formula. The one formula we will be using here which is the Geometric Brownian Motion is one of these assumptions.

What is Geometric Brownian Motion?

The Geometric Brownian Motion is a specific model for the stock market where the returns are not correlated and distributed normally. It can be mathematically written as :

πŸ‘ https://miro.medium.com/max/174/1*0PJfgG-8nIbeQV_pgy5hSg.png

This means that the returns are normally distributed with a mean of β€˜ΞΌβ€˜ and the standard deviation is denoted by β€˜Οƒβ€˜. We need to keep in mind that their parameters are all-time dependant and hence these processes are known as stationary.

ΞΌ: This symbol denotes the mean value of the returns. A positive value denotes a bullish trend and a negative value denotes a bearish trend. The higher the absolute value of this parameter, the stronger the trend.

Οƒ: This symbol denotes the volatility of the returns and a higher value denotes a more erratic price.

Overall you can analyze your portfolio with the Sharpe Ratio with a risk-free return equals to 0 and can be denoted by β€˜ΞΌ/σ’. If you love the maths behind the statistics, you can move on a continuous-time and we can use an SDE or Stochastic Differential Equation.

For those of you who, like me, love the math behind statistics, if we switch to a continuous time we can write this stochastic differential equation (SDE):

drt =   ΞΌrtdt + ΟƒrtdWt

where W denotes the β€˜Wiener process’

This model is also used in financial mathematics because it is one of the simplest stock market simulations which can be built. This is also the theoretical base of the Nobel Aware Black Sholes options theory. Though while applying with the real market, we need to consider other factors into the equation and remember that the stock market returns are not normally distributed and neither stationary. Though it is a good starting point to begin from.

The idea is that we generate n normally distributed random variables and then calculate the future prices after starting from a start price. We can achieve this in less than 10 lines of code in Python.

Python Code

We will begin  by importing some useful libraries with their usual naming conventions :

import numpy as np
import matplotlib.pyplot as plt

Now we will define the following parameters, to begin with, which can be changed later to test out different outcomes and how each of the variables can influence the end result.

mu = 0.001
sigma = 0.01
start_price = 5

Now coming to the simulation part, we need to set a seed for NumPy random number generator so that we can make reproducible results. We create 100 values for returns and then we build the time series beginning from the starting price.

np.random.seed(0)
returns = np.random.normal(loc=mu, scale=sigma, size=100)
price = start_price*(1+returns).cumprod()

You can more values for a more detailed one or even less, that is entirely up to you, and then finally, we will plot out results :

import numpy as np
import matplotlib.pyplot as plt

mu = 0.001
sigma = 0.01
start_price = 5

np.random.seed(0)
returns = np.random.normal(loc=mu, scale=sigma, size=100)
price = start_price*(1+returns).cumprod()

plt.plot(price)
plt.show()

That is all and we did it in 9 lines of code only.

We can change various parameters and see how it affects the stock market. For example, if we change the value of β€˜ΞΌβ€™ and then inspect the results :

If we change the value of ΞΌ to 0.004, we get the following graph :

Hence we can conclude that a higher value of β€˜ΞΌβ€™ will lead to a stronger and bullish trend.

Similarly, if we increase the value of the other parameter we will find more interesting results about how volatility affects a stock in the long term and this will help you decide how much you want to invest in safe stocks and how much into volatile ones. Whatever be the ultimate result, you should never put all your eggs in one basket and hence always diversify your portfolio. The information in this article is for educational purposes only and should not be taken as financial advice. The author or the platform is in no way responsible for your financial actions.

 

Conclusions 

Creating a Stock market in python using the GBM is easy to do but then we need to remember that the stock market is not always normally distributed and hence we can apply a time dependence factor on β€˜ΞΌβ€™ and β€˜Οƒβ€™. We can also use a separate probability distribution function for the returns and achieve a better result. Replicating the same results for multiple stocks over a certain amount of time and with variable return parameters can actually replicate a whole stock market with different stocks. In the real world, the most important factor to consider is that the ROI or return on investment is not continuous but it is a discrete function.

The link to an online google collab notebook can be found here.

The media shown in this article are not owned by Analytics Vidhya and is used at the Author’s discretion. 

I love to code and create new software for any purpose. I also love to play MMO and RTG games. Other hobbies include Exploring new places and restaurants and making new friends. Feel free to ping me on LinkedIn for any new ideas or same and if you need any help with any code too.

Login to continue reading and enjoy expert-curated content.

Free Courses

Ensemble Learning and Ensemble Learning Techniques

Learn ensemble learning, its techniques, and how it works in this course!

Bagging and Boosting ML Algorithms

Explore Bagging and Boosting to understand advanced ML algorithms.

Naive Bayes from Scratch

Master NaΓ―ve Bayes for ML: Build classifiers, analyze data, and apply Bayes.

Dimensionality Reduction for Machine Learning

Master key dimensionality reduction techniques for ML success!

Responses From Readers

Flagship Programs

GenAI Pinnacle Program| GenAI Pinnacle Plus Program| AI/ML BlackBelt Program| Agentic AI Pioneer Program

Free Courses

Generative AI| DeepSeek| OpenAI Agent SDK| LLM Applications using Prompt Engineering| DeepSeek from Scratch| Stability.AI| SSM & MAMBA| RAG Systems using LlamaIndex| Building LLMs for Code| Python| Microsoft Excel| Machine Learning| Deep Learning| Mastering Multimodal RAG| Introduction to Transformer Model| Bagging & Boosting| Loan Prediction| Time Series Forecasting| Tableau| Business Analytics| Vibe Coding in Windsurf| Model Deployment using FastAPI| Building Data Analyst AI Agent| Getting started with OpenAI o3-mini| Introduction to Transformers and Attention Mechanisms

Popular Categories

AI Agents| Generative AI| Prompt Engineering| Generative AI Application| News| Technical Guides| AI Tools| Interview Preparation| Research Papers| Success Stories| Quiz| Use Cases| Listicles

Generative AI Tools and Techniques

GANs| VAEs| Transformers| StyleGAN| Pix2Pix| Autoencoders| GPT| BERT| Word2Vec| LSTM| Attention Mechanisms| Diffusion Models| LLMs| SLMs| Encoder Decoder Models| Prompt Engineering| LangChain| LlamaIndex| RAG| Fine-tuning| LangChain AI Agent| Multimodal Models| RNNs| DCGAN| ProGAN| Text-to-Image Models| DDPM| Document Question Answering| Imagen| T5 (Text-to-Text Transfer Transformer)| Seq2seq Models| WaveNet| Attention Is All You Need (Transformer Architecture) | WindSurf| Cursor

Popular GenAI Models

Llama 4| Llama 3.1| GPT 4.5| GPT 4.1| GPT 4o| o3-mini| Sora| DeepSeek R1| DeepSeek V3| Janus Pro| Veo 2| Gemini 2.5 Pro| Gemini 2.0| Gemma 3| Claude Sonnet 3.7| Claude 3.5 Sonnet| Phi 4| Phi 3.5| Mistral Small 3.1| Mistral NeMo| Mistral-7b| Bedrock| Vertex AI| Qwen QwQ 32B| Qwen 2| Qwen 2.5 VL| Qwen Chat| Grok 3

AI Development Frameworks

n8n| LangChain| Agent SDK| A2A by Google| SmolAgents| LangGraph| CrewAI| Agno| LangFlow| AutoGen| LlamaIndex| Swarm| AutoGPT

Data Science Tools and Techniques

Python| R| SQL| Jupyter Notebooks| TensorFlow| Scikit-learn| PyTorch| Tableau| Apache Spark| Matplotlib| Seaborn| Pandas| Hadoop| Docker| Git| Keras| Apache Kafka| AWS| NLP| Random Forest| Computer Vision| Data Visualization| Data Exploration| Big Data| Common Machine Learning Algorithms| Machine Learning| Google Data Science Agent
πŸ‘ Av Logo White

Continue your learning for FREE

Forgot your password?
πŸ‘ Av Logo White

Enter OTP sent to

Edit

Wrong OTP.

Enter the OTP

Resend OTP

Resend OTP in 45s

πŸ‘ Popup Banner
πŸ‘ AI Popup Banner