Files
strategy-lab/to_explore/pyquantnews/27_Decomposition.ipynb
David Brazda e3da60c647 daily update
2024-10-21 20:57:56 +02:00

4.8 KiB

No description has been provided for this image

This code retrieves and analyzes unemployment data, focusing on trends and seasonality. It uses the OpenBB SDK to fetch unemployment data from 2010 to 2019. The data is then processed to calculate rolling statistics and visualized. Seasonal decomposition and STL decomposition are applied to understand the seasonal and trend components. Additionally, the Hodrick-Prescott filter is used to separate the cyclical and trend components of the data.

In [ ]:
import pandas as pd
In [ ]:
from statsmodels.tsa.seasonal import seasonal_decompose, STL
from statsmodels.tsa.filters.hp_filter import hpfilter
from openbb_terminal.sdk import openbb

Retrieve unemployment data from OpenBB SDK for the period starting 2010

In [ ]:
df = openbb.economy.unemp(2010)

Set the index to the 'date' column, filter up to 2019-12-31, and sort by date

In [ ]:
df = df.set_index("date")[:"2019-12-31"].sort_index()

Calculate rolling mean and standard deviation with a 12-month window

In [ ]:
df["rolling_mean"] = df["unemp"].rolling(window=12).mean()
df["rolling_std"] = df["unemp"].rolling(window=12).std()

Plot the unemployment rate with rolling mean and standard deviation

In [ ]:
df.plot(title="Unemployment rate")

Perform seasonal decomposition of the unemployment data using an additive model and plot results

In [ ]:
decomposition_results = seasonal_decompose(
    df["unemp"], 
    model="additive"
).plot()

Apply STL decomposition to the unemployment data and plot the results

In [ ]:
stl_decomposition = STL(df[["unemp"]]).fit()
stl_decomposition.plot().suptitle("STL Decomposition");

Apply Hodrick-Prescott filter to decompose the unemployment data into cycle and trend components and plot results

In [ ]:
hp_df = df[["unemp"]].copy()
hp_df["cycle"], hp_df["trend"] = hpfilter(hp_df["unemp"], 129600)
hp_df.plot(subplots=True, title="Hodrick-Prescott filter");

PyQuant News is where finance practitioners level up with Python for quant finance, algorithmic trading, and market data analysis. Looking to get started? Check out the fastest growing, top-selling course to get started with Python for quant finance. For educational purposes. Not investment advise. Use at your own risk.