-
Notifications
You must be signed in to change notification settings - Fork 1
/
price_linear_regression_ex.py
52 lines (40 loc) · 1.6 KB
/
price_linear_regression_ex.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import numpy as np
import pandas as pd
import extract
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardScaler
from sklearn import preprocessing
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.kernel_ridge import KernelRidge
def main():
d = extract.get_data()
d = extract.clean_data(d)
usecols = ['yield', 'state', 'issuesize', 'issuetype', 'issuesource', 'coupon', 'maturity', 'rtg', 'price']
d = d.loc[:, usecols]
#drop rows with missing values for existing data
d = d.dropna()
price = d.pop('price')
#categorical variables are state, issuetype, issuesource
le_state = preprocessing.LabelEncoder().fit(d.state)
d.state = le_state.transform(d.state)
le_issuetype = preprocessing.LabelEncoder().fit(d.issuetype)
d.issuetype = le_issuetype.transform(d.issuetype)
le_issuesource = preprocessing.LabelEncoder().fit(d.issuesource)
d.issuesource = le_issuesource.transform(d.issuesource)
#scale variables
d = StandardScaler().fit_transform(d)
#split into test and training parts
d_train, d_test, p_train, p_test = train_test_split(d, price, test_size=0.20, random_state=13)
print("starting regression...")
#Regression Part:
regr = LinearRegression()
regr.fit(d_train, p_train)
# The coefficients
print "Coefficients: \n", regr.coef_
# The mean squared error
print("Mean squared error: {}".format(np.mean((regr.predict(d_test) - p_test)**2)))
# Explained variance score: 1 is perfect prediction
print('Variance score: {}'.format(regr.score(d_test, p_test)))
if __name__ == "__main__":
main()