Time Series Decomposition

Verify the calendar effect of monthly returns

Experiment to see the calendar effect that is said in the streets such as Halloween effect and Sell in May using decompose of stats models


import numpy as np
import pandas as pd

import statsmodels.api as sm
import pandas_datareader.data as web

import warnings
warnings.filterwarnings('ignore')

import matplotlib.pyplot as plt
plt.style.use('seaborn-darkgrid')
plt.rcParams['axes.xmargin'] = 0.01
plt.rcParams['axes.ymargin'] = 0.01

window = 250*3

'''S&P500 data acquisition'''
data1 = web.DataReader("^GSPC", "yahoo", "1980/1/1").dropna()

#Treasury Yield 10 Years Data Acquisition
data2 = web.DataReader("^TNX", "yahoo", "1980/1/1").dropna()

#Daily annual volatility= 10%Leverage adjusted settings
ret = pd.DataFrame(data1['Adj Close'] / data1['Adj Close'].shift(1) - 1)
ret = 0.1 * ret / (ret.rolling(252).std()*np.sqrt(252)).shift(1)
data1 = 100*((1 + ret).cumprod()).dropna(axis=0)

data1_freq = data1.resample('M').last().fillna(method='ffill')
data1_freq['ret1'] = data1_freq['Adj Close']/data1_freq['Adj Close'].shift(1) - 1

#Recreate monthly turns
data1_freq_equity_curve = 100*((1 + data1_freq['ret1']).cumprod()).dropna(axis=0)
data1_freq_equity_curve.index = pd.to_datetime(data1_freq_equity_curve.index)

#10 years for the full year(120 months), 5 years(60 months)
res_all = sm.tsa.seasonal_decompose(data1_freq_equity_curve, freq=12)
res_10Y = sm.tsa.seasonal_decompose(data1_freq_equity_curve[-120:], freq=12)
res_5Y = sm.tsa.seasonal_decompose(data1_freq_equity_curve[-60:], freq=12)

seasonality = pd.concat([res_all.seasonal, 
                         res_10Y.seasonal, 
                         res_5Y.seasonal], axis=1)

seasonality.columns = ['1981-', '10Y', '5Y']
m_seasonality = seasonality.groupby(seasonality.index.month).mean()

# Creat Figure
month = m_seasonality.index
height = m_seasonality * 100

bar_width = 0.3

plt.figure(figsize=(10, 4), dpi=80)
plt.bar(month, height['1981-'], tick_label=month, 
        width=0.3, label='1981-')
plt.bar(month + bar_width, height['10Y'], tick_label=month, 
        width=0.3, label='10Y')
plt.bar(month + 2*bar_width, height['5Y'], tick_label=month, 
        width=0.3, label='5Y')
plt.xticks(month + bar_width, month)
plt.legend()
plt.title("Average Return by Month")
plt.xlabel("Month")
plt.ylabel("Ave.Ret(%)")
plt.show()

Looking at the returns in seasonal

M_ret.png

Decomposition(Trend, Seasonality, Residual)

res_10Y.plot()
plt.show()

Decomp.png

Recommended Posts

Time Series Decomposition
Python time series question
RNN_LSTM1 Time series analysis
Time series analysis 1 Basics
Display TOPIX time series
Time series plot / Matplotlib
Time series analysis related memo
Time series analysis part 4 VAR
Time series analysis Part 3 Forecast
[Python] Plot time series data
Time series analysis Part 1 Autocorrelation
Calculation of time series customer loyalty
Python: Time Series Analysis: Preprocessing Time Series Data
Time series analysis practice sales forecast
Time series plot started ~ python edition ~
About time series data and overfitting
Differentiation of time series data (discrete)
Movement statistics for time series forecasting
Time series analysis 3 Preprocessing of time series data
LSTM (1) for time series forecasting (for beginners)
Forecasting time series data with Simplex Projection
Time series analysis 2 Stationary, ARMA / ARIMA model
Predict time series data with neural network
How to compare time series data-Derivative DTW, DTW-
I tried time series analysis! (AR model)
Time series analysis Part 2 AR / MA / ARMA
[Python] Accelerates loading of time series CSV
Time series analysis 4 Construction of SARIMA model
Time series data anomaly detection for beginners
Time zone
matplotlib Write text to time series graph
How to handle time series data (implementation)
Reading OpenFOAM time series data and sets data
Time series analysis # 6 Spurious regression and cointegration
Python: Time Series Analysis: Building a SARIMA Model
Get time series data from k-db.com in Python
Python: Time Series Analysis: Stationarity, ARMA / ARIMA Model
Kaggle Kernel Method Summary [Table Time Series Data]
Acquisition of time series data (daily) of stock prices
Smoothing of time series and waveform data 3 methods (smoothing)
View details of time series data with Remotte
How to read time series data in PyTorch