1
+ #
2
+ # RIDGE Regression Example (for temporary reference during development)
3
+ # • NB: for python, `alpha` is the ordinary lambda tuning parameter
4
+ #
5
+
6
+ df = pd .read_csv ("https://raw.githubusercontent.com/Statology/Python-Guides/main/mtcars.csv" )[['mpg' , 'wt' , 'drat' , 'qsec' , 'hp' ]];
7
+
8
+ # Define covariates (X) and response (Y)
9
+ # For stock trading:
10
+ # • df_X = Factors that contribute to / affect the closing price of a stock
11
+ # • df_Y = Closing price of a stock
12
+ df_X = df [['mpg' , 'wt' , 'drat' , 'qsec' ]];
13
+ df_Y = df ['hp' ];
14
+
15
+ # Perform 10-fold cross validation three times
16
+ # For stock trading:
17
+ # • This can probably stay the same
18
+ xval = RepeatedKFold (n_splits = 10 , n_repeats = 3 , random_state = 1 );
19
+
20
+ # Define model and fit to training data
21
+ # For stock trading:
22
+ # • This can probably stay the same
23
+ model = RidgeCV (alphas = np .arange (.01 , 1 , .01 ), cv = xval , scoring = 'neg_mean_absolute_error' );
24
+ model .fit (df_X , df_Y );
25
+
26
+ print ('Tuning parameter (lambda) corresponding to lowest test MSE: {}' .format (model .alpha_ ));
27
+
28
+ # Prediction with RIDGE Model
29
+ # For stock trading:
30
+ # • Update the df_new to contain the future values of the covariates from df_X
31
+ df_new = pd .DataFrame ({'mpg' :[24 ], 'wt' :[2.5 ], 'drat' :[3.5 ], 'qsec' :[18.5 ]});
32
+ df_predicted = model .predict (df_new );
33
+
34
+ print (f'Predicted HP: { df_predicted [0 ]} ' );
0 commit comments