13.08.2022 Views

advanced-algorithmic-trading

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

296

sample_dict["seed_%s" % i] = np.array(

)

sample_dict["seed_%s" % i]

# Create the "average test MSE" series by averaging the

# test MSE for each degree of the linear regression model,

# across all random samples

sample_dict["avg"] = np.zeros(degrees)

for i in range(1, random_seeds+1):

sample_dict["avg"] += sample_dict["seed_%s" % i]

sample_dict["avg"] /= float(random_seeds)

return sample_dict

def k_fold_cross_val_poly(folds, degrees, X, y):

"""

Use the k-fold cross validation method to create

k separate training test splits over linear

regression models of varying flexibility

"""

# Create the KFold object and

# set the initial fold to zero

n = len(X)

kf = KFold(n, n_folds=folds)

kf_dict = dict(

[("fold_%s" % i,[]) for i in range(1, folds+1)]

)

fold = 0

# Loop over the k-folds

for train_index, test_index in kf:

fold += 1

print("Fold: %s" % fold)

X_train, X_test = X.ix[train_index], X.ix[test_index]

y_train, y_test = y.ix[train_index], y.ix[test_index]

# Increase degree of linear regression polynomial order

for d in range(1, degrees+1):

print("Degree: %s" % d)

# Create the model and fit it

polynomial_features = PolynomialFeatures(

degree=d, include_bias=False

)

linear_regression = LinearRegression()

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!