avatar

目录
linear regression实战(股票预测)

从quandl获取股票数据(Open:开盘价Close:收盘价High:最高价Low:最低价Volume:成交量),留下有用的feature

python
1
2
3
4
5
6
7
8
import pandas as pd
import quandl
df =quandl.get("WIKI/GOOGL")
df =df[['Adj. Open', 'Adj. High', 'Adj. Low', 'Adj. Close', 'Adj. Volume']]
df['HL_PCT'] = (df['Adj. High'] - df['Adj. Low']) / df['Adj. Close'] * 100.0
df['PCT_change']=(df['Adj. Close'] - df['Adj. Open']) / df['Adj. Open'] * 100.0
df = df[['Adj. Close', 'HL_PCT', 'PCT_change', 'Adj. Volume']]
print(df.head())
        Adj. Close    HL_PCT  PCT_change  Adj. Volume

Date
2004-08-19 50.322842 8.072956 0.324968 44659000.0
2004-08-20 54.322689 7.921706 7.227007 22834300.0
2004-08-23 54.869377 4.049360 -1.227880 18256100.0
2004-08-24 52.597363 7.657099 -5.726357 15247300.0

fillna() 函数:有一个inplace参数,默认为false,不会对原来dataframe中进行替换,为True时候会修改原来的

python
1
2
3
4
5
6
7
forecast_col='Adj.Close'
df.fillna(value=-9999,inplace=true)
forecast_out = int(math.ceil(0.01 * len(df)))#比如现在有100天的数据,去预测未来一天的

x=np.array(df.drop(['lable',1]) #当你要删除某一行或者某一列时,用drop函数,它不改变原有的df中的数据,而是返回另一个dataframe来存放删除后的数据
y=np..array(df['labble'])
X=preprocessing.scale(X) #特征在[-1,1]

Fit(): Method calculates the parameters μ and σ and saves them as internal objects.
解释:简单来说,就是求得训练集X的均值啊,方差啊,最大值啊,最小值啊这些训练集X固有的属性。可以理解为一个训练过程

Transform(): Method using these calculated parameters apply the transformation to a particular dataset.
解释:在Fit的基础上,进行标准化,降维,归一化等操作(看具体用的是哪个工具,如PCA,StandardScaler等)。

Fit_transform(): joins the fit() and transform() method for transformation of dataset.
解释:fit_transform是fit和transform的组合,既包括了训练又包含了转换。

python
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
X_lately = X[-forecast_out:]
X_lately=X[-forecast_out:]
y = np.array(df['label'])
print(len(X), len(y))
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.2)
clf = svm.SVR()#kernel='poly'
clf.fit(X_train, y_train)
confidence = clf.score(X_test, y_test)
forecast_set = clf.predict(X_lately)
print(confidence,forecast_set)
df['Forecast'] = np.nan

last_date = df.iloc[-1].name #iloc,loc:https://www.jianshu.com/p/f430d4f1b33f
last_unix = last_date.timestamp() #转化为时间戳
one_day = 86400
next_unix = last_unix + one_day

for i in forecast_set:
next_date = datetime.datetime.fromtimestamp(next_unix)
next_unix += 86400
df.loc[next_date]= [np.nan for _ in range(len(df.columns)-1)]+[i]

df['Adj. Close'].plot()
df['Forecast'].plot()
plt.legend(loc=4)
plt.xlabel('Date')
plt.ylabel('Price')
plt.show()
文章作者: Sunxin
文章链接: https://sunxin18.github.io/2020/01/14/machine-learning/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 lalala
打赏
  • 微信
    微信
  • 支付宝
    支付宝

评论