Skip to content

Instantly share code, notes, and snippets.

import cudf
import cuml
import cupy
conda install -c rapidsai -c nvidia -c conda-forge -c defaults rapids=0.21 python=3.10
conda activate rapids
conda create -n rapids python=3.10
# Summary statistics for the Buy-and-Hold strategy
pf.create_simple_tear_sheet(plot_data['buy_hold_cum_rets'].pct_change().dropna())
# Summary statistics for the 4-day SMA strategy
pf.create_simple_tear_sheet(plot_data['basic_stra_cum_rets'].pct_change().dropna())
# Summary statistics for the HMM-DC based 4-day SMA strategy
pf.create_simple_tear_sheet(plot_data['hmm_dc_stra_cum_rets'].pct_change().dropna())
# Set the figure size
plt.figure(figsize=(15,7))
# Plot both the Buy-and-hold, SMA and HMM-DC-based strategy cumulative returns
plt.plot(plot_data.index, plot_data['buy_hold_cum_rets'], label = "Buy and Hold Returns")
plt.plot(plot_data.index, plot_data['basic_stra_cum_rets'], label = "SMA Strategy Returns", color='g')
plt.plot(plot_data.index, plot_data['hmm_dc_stra_cum_rets'], label = "HMM-DC-based Strategy Returns", color='r')
#plt.plot(plot_data.index, plot_data['hmm_stra_cum_rets'], label = "HMM-based Strategy Returns", color='y')
# Set the title of the graph
# Compute the Buy-and-Hold cumulative returns
plot_data['buy_hold_cum_rets'] = np.exp(plot_data['returns'].cumsum())
# Compute the simple 4-day moving average strategy returns
plot_data['basic_stra_rets'] = plot_data['returns']*plot_data['signal'].shift(1)
# Compute the simple 4-day moving average strategy cumulative returns
plot_data['basic_stra_cum_rets'] = np.exp(plot_data['basic_stra_rets'].cumsum())
# Compute the HMM-DC-based strategy returns
# Subset the data for plotting
plot_data = data.loc['2018':]
# Count the number of days in which we face different leverages
plot_data['dc_leverage'].value_counts()
# Set the initial day to start the trading backtesting loop
initial_t = data.index.get_loc(data.loc['2018':].index[0])
# Print the initial day
initial_t
# Create the backtesting loop
for t in range(initial_t, (len(data.index)-1)):
# Create a data sample to be used for the trading computations
data_sample = data[['R','returns']].iloc[:(t+1)]
# Create an HMM model object
dc_model = hmm.GaussianHMM(n_components = 2, covariance_type = "diag", n_iter = 200, random_state = 100)
# Create the array input to be used for the HMM model
dc_X = data_sample[['R']].values