I'm working on a simple statistics problem with Pandas
and sklearn
. I'm aware that my code is ugly, but how can I improve it?
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime
from sklearn.metrics import mean_squared_error
from sklearn.linear_model import LinearRegression
df = pd.read_csv("sphist.csv")
df["Date"] = pd.to_datetime(df["Date"])
df.sort_values(["Date"], inplace=True)
df["day_5"] = np.nan
df["day_30"] = np.nan
df["std_5"] = np.nan
for i in range(30, len(df)):
last_5 = df.iloc[i-5:i, 4]
last_30 = df.iloc[i-30:i, 4]
df.iloc[i, -3] = last_5.mean()
df.iloc[i, -2] = last_30.mean()
df.iloc[i, -1] = last_5.std()
df = df.iloc[30:]
df.dropna(axis=0, inplace=True)
train = df[df["Date"] < datetime(2013, 1, 1)]
test = df[df["Date"] >= datetime(2013, 1, 1)]
# print(train.head(), test.head())
X_cols = ["day_5", "day_30", "std_5"]
y_col = "Close"
lr = LinearRegression()
lr.fit(train[X_cols], train[y_col])
yhat = lr.predict(test[X_cols])
mse = mean_squared_error(yhat, test[y_col])
rmse = mse/len(yhat)
score = lr.score(test[X_cols], test[y_col])
print(rmse, score)
plt.scatter(yhat, test[y_col], c="k", s=1)
plt.plot([.95*yhat.min(), 1.05*yhat.max()], [.95*yhat.min(), 1.05*yhat.max()], c="r")
plt.show()
- It relies on hard-code iloc indices, which is hard to read or maintain. How can I change it to column names/row names?
- The codes look messy. Any advice to improve it?