欢迎光临
我们一直在努力

python sklearn预测黄金GLD 价格

from sklearn.linear_model import LinearRegression
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn
import fix_yahoo_finance as yf

#df = yf.download(‘GLD’,start=’2009-02-15′, end=’2019-02-15′)
# Only keep close columns
#print(type(df))
#df.to_excel(‘gold_price_2009-2019.xlsx’)
# print(df[‘Date’])
# print(df[‘Close’])
# print(len(df), type(df))
# df=df.dropna()
# print(len(df), type(df))

#plt.plot(df[‘Date’], df[‘Close’], ‘b-‘)
def get_data():
df = pd.read_excel(‘gold_price_2009-2019.xlsx’)
df = df.dropna()
return df
df = get_data()
#plt.plot(df[‘Date’], df[‘Close’], ‘b-‘)

df[‘S_3’] = df[‘Close’].shift(1).rolling(window=3).mean()

df[‘S_9’]= df[‘Close’].shift(1).rolling(window=9).mean()
df= df.dropna()

X = df[[‘S_3′,’S_9’]]
y = df[‘Close’]

t=.98

t = int(t*len(df))

# Train dataset

X_train = X[:t]

y_train = y[:t]

# Test dataset

X_test = X[t:]

y_test = y[t:]
X_train, y_train
linear = LinearRegression().fit(X_train,y_train)
print(type(linear))
print(linear.coef_[0], linear.coef_[1], linear.intercept_)

def linear_preprocess(a, b):
return linear.coef_[0]*a + linear.coef_[1]*b + linear.intercept_
X_test_list = [[row[‘S_3’], row[‘S_9’]] for i, row in X_test.iterrows()]
print(X_test_list)
predicted_price = linear.predict(X_test)
plt.figure(figsize=(100,50))
plt.plot(y_test.index, predicted_price, ‘b-‘, y_test.index, y_test, ‘r–‘)

上面的shift(1)是因为要用前多少天的平均值,所以需要去除当天的数据,毕竟是预测嘛,肯定是没有当天的数据喽。

赞(0) 打赏
未经允许不得转载:乌西塔 » python sklearn预测黄金GLD 价格

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

微信扫一扫打赏