|
| 1 | +import numpy as np |
| 2 | +import plotly.graph_objects as go |
| 3 | + |
| 4 | + |
| 5 | +def plot_acf(acf_data: dict, save_path_html: str, save_path_pdf: str, n_obs: int): |
| 6 | + """Plot the manually computed ACF using Plotly with confidence bands. |
| 7 | +
|
| 8 | + Args: |
| 9 | + acf_data (dict): Dictionary containing "acf" values and "lags". |
| 10 | + save_path_html (str): Path to save the interactive HTML plot. |
| 11 | + save_path_pdf (str): Path to save the static PDF plot. |
| 12 | + n_obs (int): Number of observations in the time series (for confidence bands). |
| 13 | +
|
| 14 | + Returns: |
| 15 | + None: Saves plots in the specified paths. |
| 16 | + """ |
| 17 | + max_lags = 200 |
| 18 | + lags = acf_data["lags"][:max_lags] |
| 19 | + acf_values = acf_data["acf"][:max_lags] |
| 20 | + |
| 21 | + confidence_band = 1.96 / np.sqrt(n_obs) |
| 22 | + |
| 23 | + fig = go.Figure() |
| 24 | + |
| 25 | + fig.add_trace( |
| 26 | + go.Bar( |
| 27 | + x=lags, y=acf_values, marker={"color": "rgba(0, 0, 255, 0.8)"}, name="ACF" |
| 28 | + ) |
| 29 | + ) |
| 30 | + |
| 31 | + fig.add_trace( |
| 32 | + go.Scatter( |
| 33 | + x=lags, |
| 34 | + y=[confidence_band] * len(lags), |
| 35 | + mode="lines", |
| 36 | + line={"color": "red", "dash": "dash"}, |
| 37 | + name="95% Confidence Interval", |
| 38 | + ) |
| 39 | + ) |
| 40 | + |
| 41 | + fig.add_trace( |
| 42 | + go.Scatter( |
| 43 | + x=lags, |
| 44 | + y=[-confidence_band] * len(lags), |
| 45 | + mode="lines", |
| 46 | + line={"color": "red", "dash": "dash"}, |
| 47 | + showlegend=False, |
| 48 | + ) |
| 49 | + ) |
| 50 | + |
| 51 | + fig.update_layout( |
| 52 | + title="Autocorrelation Function (ACF) with Confidence Bands", |
| 53 | + xaxis_title="Lag", |
| 54 | + yaxis_title="ACF Value", |
| 55 | + template="plotly_white", |
| 56 | + yaxis={"range": [-0.15, 0.3]}, |
| 57 | + plot_bgcolor="whitesmoke", |
| 58 | + xaxis={"gridcolor": "lightgray"}, |
| 59 | + ) |
| 60 | + |
| 61 | + fig.write_html(save_path_html) |
| 62 | + fig.write_image(save_path_pdf) |
0 commit comments