<jupyter_start><jupyter_text>Random Forest in TradingIn this code, we will create a Random Forest Classifier and train it to give the daily returns. Importing the Libraries<jupyter_code># Data manipulation
import numpy as np
import pandas as pd

# Technical indicators
import talib as ta

# Plotting graphs
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
plt.style.use('seaborn-darkgrid')

from sklearn import metrics
from sklearn.ensemble import RandomForestClassifier
# The data is stored in the directory 'data_modules'
path = "../data_modules/"

# Read the data
data = pd.read_csv(path + 'JPM_2017_2019.csv', index_col=0)
data.index = pd.to_datetime(data.index)

data.close.plot(figsize=(8,5), color='b')
plt.ylabel('Close Price')
plt.xlabel('Date')
plt.show()<jupyter_output><empty_output><jupyter_text>Creating Input and Output DatasetIn this step, we will use the same target and feature variable as we have taken in the previous chapters.<jupyter_code>import sys
sys.path.append("..")

from data_modules.utility import get_target_features
y, X = get_target_features(data)

split = int(0.8*len(X))
X_train, X_test, y_train, y_test = X[:split], X[split:], \
                                    y[:split], y[split:]<jupyter_output><empty_output><jupyter_text>Training the Machine Learning ModelAll set with the data! Let's train a decision tree classifier model. The `RandomForestClassifier` function from tree is stored in variable `clf`, and then a fit method is called on it with `X_train` and `y_train` dataset as the parameters so that the classifier model can learn the relationship between input and output.<jupyter_code>clf = RandomForestClassifier(random_state=5, max_depth=3, 
                             max_features=3)
# Create the model on train dataset
model = clf.fit(X_train, y_train)
predicted = model.predict(X_test)
confusion_matrix_data = metrics.confusion_matrix(y_test, 
                                                 predicted)
# Plot the data

fig, ax = plt.subplots(figsize=(6, 4))
sns.heatmap(confusion_matrix_data, fmt="d",
            cmap='Blues', cbar=False, annot=True, ax=ax)

# Set the axes labels and the title
ax.set_xlabel('Predicted Labels', fontsize=12)
ax.set_ylabel('Actual Labels', fontsize=12)
ax.set_title('Confusion Matrix', fontsize=14)
ax.xaxis.set_ticklabels(['No Position', 'Long Position'])
ax.yaxis.set_ticklabels(['No Position', 'Long Position'])

# Display the plot
plt.show()

print(metrics.classification_report(y_test, predicted))<jupyter_output><empty_output><jupyter_text>Strategy Returns<jupyter_code># Calculate the percentage change
strategy_data = X_test[['pct_change']].copy()

# Predict the signals
strategy_data['predicted_signal'] = model.predict(X_test)

# Calculate the strategy returns
strategy_data['strategy_returns'] = \
    strategy_data['predicted_signal'].shift(1) * \
    strategy_data['pct_change']

# Drop the missing values
strategy_data.dropna(inplace=True)

strategy_data.head()
from data_modules.utility import get_performance
get_performance(strategy_data)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10029022895840052, 'fraction_numerical': 0.008061915511125443, 'mean_word_length': 5.130434782608695, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '436507', 'license': 'CC0-1.0', 'n_tokens_mistral': 1006, 'n_tokens_neox': 970, 'n_words': 273, 'path': 'Python Codes/Chapter 13 - Random Forest Algorithm.ipynb', 'repo_name': 'quantra-go-algo/ml-trading-ebook', 'size': '3101'}