Skip to content

Instantly share code, notes, and snippets.

View summary_statistics.py
# 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())
View plot_strategies_cum_rets.py
# 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
View compute_strategies_cum_rets.py
# 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
View count_days_for_each_leverage.py
# 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()
View set_initial_date_iloc.py
# 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
View hmm_dc_sma_based_backtesting_loop.py
# 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
View sma_signal.py
# Create a simple 4-day moving average
data['sma'] = data['Close'].rolling(4).mean()
# Create the strategy signal
data['signal'] = np.where(data['Close']>data['sma'],1.0,-1.0)
# Create the leverage column
data['dc_leverage'] = 0.0
# Create the next state column
View get_rets_volatility_per_regime.py
# Find the returns standard deviation for state 0
state0_vol = data['returns'][data['states']==0].std()*np.sqrt(252)*100
# Find the returns standard deviation for state 1
state1_vol = data['returns'][data['states']==1].std()*np.sqrt(252)*100
# Print the returns volatility for both states
print(f'Volatility for state 0 and 1 are {state0_vol:.2f} and {state1_vol:.2f}, respectively')
View get_r_volatility_per_regime.py
# Find the R mean for state 0
state0_R_vol = data['R'][data['states']==0].mean()
# Find the R mean for state 1
state1_R_vol = data['R'][data['states']==1].mean()
# Print the R volatility for both states
print(f'Volatility for state 0, 1 and 2 are {state0_R_vol:.2f} and {state1_R_vol:.2f}, respectively')
View fit_hmm_to_r_indicator.py
# 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