# 手把手：用Python搭建机器学习模型预测黄金价格

GLD 是最大的以黄金进行直接投资的ETF交易基金。

# LinearRegression is a machine learning libraryforlinear regression

from sklearn.linear_modelimportLinearRegression

# pandas and numpy are used for data manipulation

importpandas as pd

importnumpy as np

# matplotlib and seaborn are used for plotting graphs

importmatplotlib.pyplot as plt

importseaborn

# fix_yahoo_finance is used to fetch dataimportfix_yahoo_finance as yf

# Only keep close columns

Df=Df[['Close']]

# Drop rows with missing values

Df= Df.dropna()

# Plot the closing price of GLD

Df.Close.plot(figsize=(10,5))

plt.ylabel("Gold ETF Prices")

plt.show()

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']

2008-02-0891.000000

2008-02-1191.330002

2008-02-1289.330002

2008-02-1389.440002

2008-02-1489.709999

Name: Close, dtype: float64

X_train 和y_train是训练数据集。

X_test & y_test是测试数据集。

t=.8

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:]

Y = m1 * X1 + m2 * X2 + CGold ETF price = m1 *3days moving average + m2 *15days moving average + c

linear = LinearRegression().fit(X_train,y_train)

print"Gold ETF Price =", round(linear.coef_[],2), \

"* 3 Days Moving Average", round(linear.coef_[1],2), \

"* 9 Days Moving Average +", round(linear.intercept_,2)

predicted_price = linear.predict(X_test)

predicted_price = pd.DataFrame(predicted_price,index=y_test.index,columns = ['price'])

predicted_price.plot(figsize=(10,5))

y_test.plot()

plt.legend(['predicted_price','actual_price'])

plt.ylabel("Gold ETF Price")

plt.show()

r2_score = linear.score(X[t:],y[t:])*100

float("".format(r2_score))

https://www.quantinsti.com/blog/gold-price-prediction-using-machine-learning-python/

【今日机器学习概念】

Have a Great Definition

• 发表于:
• 原文链接http://kuaibao.qq.com/s/20180216A0CG9K00?refer=cp_1026
• 腾讯「云+社区」是腾讯内容开放平台帐号（企鹅号）传播渠道之一，根据《腾讯内容开放平台服务协议》转载发布内容。
• 如有侵权，请联系 yunjia_community@tencent.com 删除。

2020-10-30

2020-10-30

2020-10-30

2020-10-30

2020-10-30

2020-10-30

2018-06-28

2018-06-01

2018-04-17

2018-04-12

2020-10-30

2020-10-30