Skip to content

Instantly share code, notes, and snippets.

@SajidLhessani
Created October 8, 2021 07:29
Show Gist options
  • Save SajidLhessani/f3a76255ded4aef558ac15e4d62ee337 to your computer and use it in GitHub Desktop.
Save SajidLhessani/f3a76255ded4aef558ac15e4d62ee337 to your computer and use it in GitHub Desktop.
# Use drop method to drop the columns
X = df.drop(['Close', 'Signal', 'High',
'Low', 'Volume', 'Ret'], axis=1)
# Create a variable which contains all the 'Signal' values
y = df['Signal']
# Test variables for 'c' and 'g'
c = [10, 100, 1000, 10000]
g = [1e-2, 1e-1, 1e0]
# Intialise the parameters
parameters = {'svc__C': c,
'svc__gamma': g,
'svc__kernel': ['rbf']
}
# Create the 'steps' variable with the pipeline functions
steps = [('scaler', StandardScaler()), ('svc', SVC())]
# Pass the 'steps' to the Pipeline function
pipeline = Pipeline(steps)
# Call the RandomizedSearchCV function and pass the parameters
rcv = RandomizedSearchCV(pipeline, parameters, cv=TimeSeriesSplit(n_splits=2))
# Call the 'fit' method of rcv and pass the train data to it
rcv.fit(X.iloc[:split], y.iloc[:split])
# Call the 'best_params_' method to obtain the best parameters of C
best_C = rcv.best_params_['svc__C']
# Call the 'best_params_' method to obtain the best parameters of kernel
best_kernel = rcv.best_params_['svc__kernel']
# Call the 'best_params_' method to obtain the best parameters of gamma
best_gamma = rcv.best_params_['svc__gamma']
# Create a new SVC classifier
cls = SVC(C=best_C, kernel=best_kernel, gamma=best_gamma)
# Instantiate the StandardScaler
ss1 = StandardScaler()
# Pass the scaled train data to the SVC classifier
cls.fit(ss1.fit_transform(X.iloc[:split]), y.iloc[:split])
# Pass the test data to the predict function and store the values into 'y_predict'
y_predict = cls.predict(ss1.transform(X.iloc[split:]))
# Initiate a column by name, 'Pred_Signal' and assign 0 to it
df['Pred_Signal'] = 0
# Save the predicted values for the train data
df.iloc[:split, df.columns.get_loc('Pred_Signal')] = pd.Series(
cls.predict(ss1.transform(X.iloc[:split])).tolist())
# Save the predicted values for the test data
df.iloc[split:, df.columns.get_loc('Pred_Signal')] = y_predict
# Calculate strategy returns and store them in 'Ret1' column
df['Ret1'] = df['Ret']*df['Pred_Signal']
# Calculate the confusion matrix
cm = confusion_matrix(y[split:], y_predict)
cm
# Calculate the classification report
cr = classification_report(y[split:], y_predict)
print(cr)
#declare figure
fig = go.Figure()
#Set up traces
fig.add_trace(go.Scatter(x=df.index, y= (df['Ret'][split:]+1).cumprod(),line=dict(color='royalblue', width=.8), name = 'stock_returns'))
fig.add_trace(go.Scatter(x=df.index, y= (df['Ret1'][split:]+1).cumprod(),line=dict(color='orange', width=.8), name = 'strategy_returns'))
# Add titles
fig.update_layout(
title='Support Vector Machine Strategy',
yaxis_title='Stock return (% Return)')
fig.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment