Discussion about this post

User's avatar
Orith Loeb's avatar

Thanks!

Here's my solution:

# DDC-38: Random walk

import matplotlib.pyplot as plt

import numpy as np

import random

import pandas as pd

# ---method A - using a for loop---

time_series_length = 1000

brownian_motion = [0]

# ---generating the data using a for loop---

for i in range (1, time_series_length):

direction = 2*np.random.randint(0,2)-1

brownian_motion.append (brownian_motion[i-1]+ direction)

# ---convert to a pandas series---

time_series = pd.Series (brownian_motion)

# ---plot---

plt.figure(figsize= (12,8))

plt.plot (time_series)

plt.xlabel ("time")

plt.ylabel("stock market")

# ---Method B - using vectorization---

# ---Generate random steps using vectorization---

steps = np.random.choice ([-1, 1], size = time_series_length-1)

# --- calculate the comulative sum---

brownian_motion_vec = np.insert(np.cumsum(steps), 0, 0)

# ---convert to a pandas series---

time_series_vec = pd.Series(brownian_motion_vec)

# --- plot---

plt.figure(figsize= (10,4))

plt.plot (time_series_vec)

plt.xlabel ("time")

plt.ylabel("stock market")

Expand full comment
1 more comment...

No posts