### Install hawkeslib via pip Source: https://hawkeslib.readthedocs.io/en/latest/intro.html Install the required dependencies and the library itself using pip. ```bash $ pip install -U Cython numpy $ pip install hawkeslib ``` -------------------------------- ### Importing dependencies Source: https://hawkeslib.readthedocs.io/en/latest/example.html Initial imports for data handling, web requests, and visualization. ```python %matplotlib inline import requests from lxml import html from datetime import datetime as dt import numpy as np from matplotlib import pyplot as plt ``` -------------------------------- ### Sampling from the model Source: https://hawkeslib.readthedocs.io/en/latest/example.html Generates samples from the fitted model to estimate the distribution of tremors over a 24-hour period. ```python nr_shocks_sample = [len(uv.sample(24)) for x in range(100000)] _ = plt.hist(nr_shocks_sample, bins=20) ``` -------------------------------- ### Fitting the Hawkes model Source: https://hawkeslib.readthedocs.io/en/latest/example.html Initializes and fits the UnivariateExpHawkesProcess to the earthquake data. ```python %%time from hawkeslib import UnivariateExpHawkesProcess as UVHP uv = UVHP() uv.fit(t) print uv.get_params() ``` -------------------------------- ### Sample posterior distribution for Hawkes process Source: https://hawkeslib.readthedocs.io/en/latest/example.html Initializes the Bayesian univariate exponential Hawkes process model and samples from the posterior distribution of parameters. ```python from hawkeslib import BayesianUVExpHawkesProcess as BUVHP buv = BUVHP(mu_hyp=(1., 10.), alpha_hyp=(1., 1.), theta_hyp=(1., 10.)) trace = buv.sample_posterior(t, T=t[-1], n_samp=50000) ``` -------------------------------- ### Visualize a Counting Process Source: https://hawkeslib.readthedocs.io/en/latest/tutorial.html Generates a set of random points following a Poisson distribution and visualizes them as a step function representing a counting process. ```python ar_pp = sorted(np.random.rand(np.random.poisson(20)) * 100) f = plt.figure(figsize=(15,2)) plt.step(ar_pp, np.cumsum(np.ones_like(ar_pp))) plt.ylabel("$N(t)$") plt.xlabel('$t$') _ = plt.plot(ar_pp, np.zeros_like(ar_pp), 'k.') ``` -------------------------------- ### Visualize Brownian Motion Source: https://hawkeslib.readthedocs.io/en/latest/tutorial.html Generates and plots a realization of a Brownian motion process using NumPy and Matplotlib. ```python ar_bm = np.cumsum(np.random.randn(1000) * 0.5**2) plt.figure(figsize=(15,2)) plt.title("Brownian Motion") _ = plt.plot(ar_bm, 'g-') ``` -------------------------------- ### Simulate a Homogeneous Poisson Process Source: https://hawkeslib.readthedocs.io/en/latest/tutorial.html Generates samples from a Poisson process with a constant intensity function λ(t)=3. ```python a = np.linspace(0, 100, 10000) lt = np.ones_like(a) * 3 plt.figure(figsize=(15, 2)) plt.plot(a, lt, 'b-') plt.yticks([]) for k in range(3): count = np.random.poisson(3 * 100) smp = np.random.rand(count) * 100 plt.plot(smp, np.ones_like(smp) * -1 * k, 'k.') ``` -------------------------------- ### Load and display financial event timestamps Source: https://hawkeslib.readthedocs.io/en/latest/tutorial.html Imports necessary libraries and reads event timestamps from a CSV file for analysis. ```python %matplotlib inline import numpy as np import pandas as pd from matplotlib import pyplot as plt # here are the "timestamps" df = pd.read_csv("example_data_top4.csv", header=None) ar = np.array(df.loc[:, 1]) print ar ``` ```text [ 56 56 59 ... 8199797 8199798 8199984] ``` -------------------------------- ### Simulate and Plot a Univariate Exponential Hawkes Process Source: https://hawkeslib.readthedocs.io/en/latest/tutorial.html Uses the hawkeslib library to generate samples from a univariate exponential Hawkes process and visualize the conditional intensity function over time. ```python from hawkeslib import UnivariateExpHawkesProcess mu, alpha, beta = .1, .2, .1 uv = UnivariateExpHawkesProcess() uv.set_params(mu, alpha, beta) smp = uv.sample(100) lda_ar = [mu + np.sum(alpha * beta * np.exp(-beta * (x - smp[smp < x]))) \ for x in np.arange(0, 100, .1)] plt.figure(figsize=(15,2)) plt.ylabel("$\lambda^*(t)$") plt.xlabel("$t$") plt.plot(smp, np.ones_like(smp) * .1, 'k.') _ = plt.plot(np.arange(0, 100, .1), lda_ar, 'b-') ``` -------------------------------- ### Simulate a Non-Homogeneous Poisson Process Source: https://hawkeslib.readthedocs.io/en/latest/tutorial.html Generates samples from a Poisson process with a time-varying intensity function λ(t)=exp(sin(t)). ```python a = np.linspace(0, 100, 10000) lt = np.exp(np.sin(a)) plt.figure(figsize=(15, 2)) plt.plot(a, lt, 'b-') plt.yticks([]) for k in range(3): count = np.random.poisson(3 * 100) smp = [x for x in sorted(np.random.rand(count) * 100) if np.random.rand() * 3 < np.exp(np.sin(x))] plt.plot(smp, np.ones_like(smp) * -1 * k, 'k.') ``` -------------------------------- ### Model output Source: https://hawkeslib.readthedocs.io/en/latest/example.html The resulting parameters from the model fit. ```text (0.04930555306217892, 0.30548369162341404, 5.150339498582191) CPU times: user 1.48 ms, sys: 0 ns, total: 1.48 ms Wall time: 1.44 ms ``` -------------------------------- ### Visualizing earthquake timeline Source: https://hawkeslib.readthedocs.io/en/latest/example.html Plots the occurrence times of earthquakes with jitter to visualize temporal clustering. ```python plt.figure(figsize=(15,2)) plt.ylim([-5, 5]) plt.yticks([]) _ = plt.plot(t, np.random.rand(len(t)), 'k.') ``` -------------------------------- ### Aggregate timestamps into time-series plot Source: https://hawkeslib.readthedocs.io/en/latest/tutorial.html Bins event timestamps into 1-second intervals and visualizes the frequency of events over time. ```python # here is the "aggregated" time series plot bc = np.bincount(np.floor(ar / 1000.).astype(int)) plt.figure(figsize=(15,2)) plt.title("Number of Price Jumps, by 1sec intervals") plt.xlabel("seconds") _ = plt.plot(bc[:100], 'k-') ``` -------------------------------- ### Scraping earthquake data Source: https://hawkeslib.readthedocs.io/en/latest/example.html Fetches recent earthquake reports from the Kandilli Observatory and processes timestamps into relative hours. ```python res = requests.get("http://www.koeri.boun.edu.tr/scripts/lst9.asp") tx = html.fromstring(res.content).xpath("//pre/text()")[0] lines = tx.splitlines()[7:] # get rid of the headers # take out timestamps and convert them to "hours since first event" timestamps = [dt.strptime(l[:19], "%Y.%m.%d %H:%M:%S") for l in lines if "ISTANBUL" in l] t = np.array([(x - ts[-1]).total_seconds() / 3600 for x in timestamps])[::-1] ``` -------------------------------- ### Compute Bayesian credible intervals Source: https://hawkeslib.readthedocs.io/en/latest/example.html Calculates and prints the 2.5th and 97.5th percentiles for the alpha and theta parameters from the trace. ```python # compute the BCIs print pm.stats.quantiles(trace["alpha"], [2.5, 97.5]) print pm.stats.quantiles(trace["theta"], [2.5, 97.5]) ``` -------------------------------- ### Visualize raw event occurrences Source: https://hawkeslib.readthedocs.io/en/latest/tutorial.html Plots individual event timestamps as points to avoid information loss from time-grid discretization. ```python plt.figure(figsize=(15,2)) plt.title("Price jumps") plt.xlabel("milliseconds") _ = plt.plot(ar[:100], np.ones(100), 'k.') ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.