Skip to content

Instantly share code, notes, and snippets.

@rloredo
Created September 26, 2021 18:29
Show Gist options
  • Save rloredo/8f37d3d510c902d36084691d3046c92b to your computer and use it in GitHub Desktop.
Save rloredo/8f37d3d510c902d36084691d3046c92b to your computer and use it in GitHub Desktop.
Generate time series with poisson distribution
import math
import random
from datetime import datetime, timedelta
def poisson_timeseries_generator(tau, start_time, end_time):
"""
Generates a time series with a poisson distribution
tau: interval lenght i.e. mean of the expected time between events
start_time: starting date of the time series. %Y-%m-%d %H:%M:%S format
end_time: end date of the time series. %Y-%m-%d %H:%M:%S format
"""
time_series = []
time_series.append(datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S'))
while time_series[-1] < datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S'):
time_series.append(time_series[-1] + timedelta(minutes = round(next_event(1/tau))))
return time_series
def next_event(rate_parameter):
"""
Draw the interval between events
"""
return -math.log(1.0 - random.random()) / rate_parameter
if __name__ == "__main__":
import pandas as pd
tau_value = 5
time_series = poisson_timeseries_generator(tau = tau_value, start_time = "2021-01-01 00:00:00", end_time = "2021-01-01 23:59:59")
df = pd.DataFrame({'original': pd.Series(time_series), 'shifted': pd.Series(time_series).shift()})
df['differences'] = (df.original - df.shifted) / pd.Timedelta(minutes = 1)
print(f'Time between events: {df.differences.mean()} \nTau {tau_value}')
print(f'Expected events {(24*60)/tau_value}')
print(f'Simulated events: {df.shape[0]}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment