Skip to content

Instantly share code, notes, and snippets.

View quantra-go-algo's full-sized avatar

Algorithmic Trading quantra-go-algo

View GitHub Profile
# Create an HMM object with two hidden states
model = hmm.GaussianHMM(n_components = 2, covariance_type = "diag", n_iter = 100, random_state = 42)
# Create an array input for the HMM model
X = data[['R']].values
# Estimate the HMM model
results = model.fit(X)
# Use the Viterbi algorithm to find the fitted hidden states
# Count number of downward and upward events
data['Event'].value_counts()
# Set the figure size
plt.figure(figsize=(15,7))
# Plot the R indicator
plt.plot(data.index, data['R'], label = "R")
# Set the title of the graph
plt.title('Time-Adjusted Return of DC', fontsize=16)
# Set the x- and y- axis labels and ticks sizes
# Compute the DC indicators
data = directional_change_events(data, theta=0.004)
# Drop NaN values
data.dropna(inplace=True)
# Present the data
data
# Download the GBPUSD data from 2003 to 2013
data = yf.download('GBPUSD=X', start='2003-12-01', end='2023-10-06', auto_adjust=True)
# Compute the log returns
data['returns'] = np.log(data['Close']/data['Close'].shift(1))
# Print the data
data
# Function to create the DC indicators provided by Chen and Tsang (2021)
def directional_change_events(data, theta=0.2):
# Copy the dataframe
data = data.copy()
# Create the necessary columns and variables
data["Event"] = 0.0
# Set the initial event variable value
# For data manipulation
import numpy as np
import pandas as pd
import yfinance as yf
import pyfolio as pf
from hmmlearn import hmm
from sklearn.utils import check_random_state
# For data visualization
import matplotlib.pyplot as plt
# Set the figure size
plt.figure(figsize=(15,7))
# Plot the residuals
plt.plot(arfima_residuals.index, arfima_residuals, label = "Best d ARFIMA Residuals")
# Set the title of the graph
plt.title('Residuals from the Best d ARFIMA model', fontsize=16)
# Set the x- and y- axis labels and ticks sizes
# Estimate ARFIMA residuals with optimal d
arfima_residuals = fracDiff_FFD(np.log(data['Close']),d)
# Get the optimal ARFIMA d parameter
d = optimal_d(data, 0.04, 0, 1)