??本主題使用邏輯回歸與svm預(yù)測股票漲跌,效果不好或南,與拋硬幣效果差不多古劲。
??主要記錄下其中的特征工程對特征的處理方式揪胃。
主要內(nèi)容:
??1. 股票數(shù)據(jù)的特征處理;
??2. K-線的概念氛琢;
??3. 使用matplotlib繪制K-線喊递;
一、數(shù)據(jù)獲取與特征工程
- 使用tushare提供的深滬股市交易數(shù)據(jù)阳似;
- 并使用連續(xù)一周的收盤價作為機(jī)器學(xué)習(xí)特征數(shù)據(jù)骚勘;
- 使用的package
import pandas as pd
import numpy as np
import tushare as ts
import sklearn
from sklearn.linear_model import LogisticRegression # 訓(xùn)練模型
from sklearn.preprocessing import scale # 數(shù)據(jù)預(yù)處理:標(biāo)準(zhǔn)化
- 獲取k線數(shù)據(jù)
- tushare提供如下幾個函數(shù)獲取交易k線數(shù)據(jù)。
# 獲取指定上市代碼的公司的K線交易信息
# 數(shù)據(jù)返回格式:index(['date', 'open', 'close', 'high', 'low', 'volume', 'code'], dtype='object')
k_data = ts.get_k_data('600848', start='1988-01-01', end='', ktype='D') #訓(xùn)練集數(shù)據(jù)
# data.columns
k_data[0:4]
- 增加股價變動
k_data['result'] = k_data['close'].pct_change()
k_data[0:4]
- 刪除NaN值
k_data.dropna(inplace=True) # 在原來數(shù)據(jù)集上刪除
k_data[0:4]
- 訓(xùn)練特征數(shù)據(jù)定義
# 定義訓(xùn)練的數(shù)據(jù)特征(核心是收盤價)
feature_data = pd.DataFrame()
feature_data['close'] = k_data['close'] # 取收盤價預(yù)測
feature_data['result'] = k_data['result'] # 股價漲跌撮奏,后面用來生成標(biāo)簽
feature_data[0:4]
- 使用連續(xù)一周的收盤價作為特征數(shù)據(jù)
# 特征工程:使用收盤價俏讹,連續(xù)一周作為一個特征訓(xùn)練輸入
for i in range(1,8,1):
feature_data['close - ' + str(i) + 'd'] = k_data['close'].shift(i)
feature_data[0:10]
- 刪除調(diào)整數(shù)據(jù)中NaN值
feature_data.dropna(inplace=True) # 在原來數(shù)據(jù)集上刪除
feature_data[0:4]
- 訓(xùn)練標(biāo)簽
- 使用下一天的漲跌作為標(biāo)簽
train_label = np.sign(feature_data['result'].shift(-1))
train_label[0:5]
8 -1.0
9 -1.0
10 -1.0
11 -1.0
12 1.0
Name: result, dtype: float64
- 刪除股價變動列
feature_data.drop(['result'], axis=1, inplace=True)
feature_data[0:4]
- 數(shù)據(jù)標(biāo)準(zhǔn)化
train_data = sklearn.preprocessing.scale(feature_data)
train_data[0:2]
array([[-0.26602226, -0.20240527, -0.14993246, -0.18011299, -0.11017521,
-0.05842557, 0.04566276, -0.0245463 ],
[-0.30894573, -0.26566062, -0.20198489, -0.14945344, -0.17967086,
-0.10968345, -0.05790754, 0.04626196]])
train_label[-2:]
5680 -1.0
5681 NaN
Name: result, dtype: float64
- 缺失值處理
- 最后一行數(shù)據(jù)應(yīng)該是NaN,處理為0
train_label.replace(to_replace= np.NaN, value = 0, inplace = True)
train_label[-2:]
5680 -1.0
5681 0.0
Name: result, dtype: float64
二畜吊、數(shù)據(jù)訓(xùn)練-邏輯回歸
- 使用sklearn的線性模型
classifier = LogisticRegression(C=1000, solver='lbfgs', multi_class='auto', penalty='l2', max_iter=100000)
- 訓(xùn)練
classifier.fit(train_data, train_label)
LogisticRegression(C=1000, class_weight=None, dual=False, fit_intercept=True,
intercept_scaling=1, l1_ratio=None, max_iter=100000,
multi_class='auto', n_jobs=None, penalty='l2',
random_state=None, solver='lbfgs', tol=0.0001, verbose=0,
warm_start=False)
- score評分
classifier.score(train_data, train_label)
0.5082833979555869
- 預(yù)測
predict = classifier.predict(train_data)
correct_num = (predict == train_label).sum()
correct_num
2884
三泽疆、數(shù)據(jù)訓(xùn)練-svm
- 使用SVM模型
from sklearn.svm import SVC
svc_classifier = SVC(kernel = 'rbf')
- 訓(xùn)練
svc_classifier.fit(train_data, train_label)
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape='ovr', degree=3, gamma='auto_deprecated',
kernel='rbf', max_iter=-1, probability=False, random_state=None,
shrinking=True, tol=0.001, verbose=False)
- score
svc_classifier.score(train_data, train_label)
0.5029961226647868
- 預(yù)測
predict = svc_classifier.predict(train_data)
correct_num = (predict == train_label).sum()
correct_num
2854
四、附錄:相關(guān)tushare函數(shù)說明
4.1. ts包幫助說明
- bond (package)
- 投資參考數(shù)據(jù)接口:
bounds.py
- 投資參考數(shù)據(jù)接口:
- coins (package)
- 數(shù)字貨幣行情數(shù)據(jù):
market.py
- 數(shù)字貨幣行情數(shù)據(jù):
- data (package)
- (無)
- fund (package)
- 獲取基金凈值數(shù)據(jù)接口:
nav.py
- 獲取基金凈值數(shù)據(jù)接口:
- futures (package)
- 國內(nèi)期貨:
domestic.py
- 國際期貨:
intlfutures.py
- 國內(nèi)期貨:
- internet (package)
- 電影票房:
boxoffice.py
- 財(cái)新網(wǎng)新聞數(shù)據(jù)檢索下載:
caixinnews.py
- 電影票房:
- pro (package)
- 新的更好的接口玲献,需要指定token殉疼,有的需要積分的:
data_pro.py
- 新的更好的接口玲献,需要指定token殉疼,有的需要積分的:
- stock (package)
- 龍虎榜數(shù)據(jù):
billboard.py
- 獲取股票分類數(shù)據(jù)接口 :
classifying.py
- 基本面數(shù)據(jù)接口:
fundamental.py
- 全球市場:
globals.py
- 股票技術(shù)指標(biāo)接口:
indictor.py
- 宏觀經(jīng)濟(jì)數(shù)據(jù)接口:
macro.py
- 新聞事件數(shù)據(jù)接口:
newsevent.py
- 投資參考數(shù)據(jù)接口:
reference.py
- 上海銀行間同業(yè)拆放利率(Shibor)數(shù)據(jù)接口:
shibor.py
- 交易數(shù)據(jù)接口:
trading.py
- 龍虎榜數(shù)據(jù):
- trader (package)
- 股票實(shí)盤交易接口:
trader.py
- 股票實(shí)盤交易接口:
- util (package)
- 工具,比如:日期時間工具捌年。
- 說明:
- 所有包下的接口都使用別名瓢娜,在tushare包下直接使用。
"""
for trading data
"""
from tushare.stock.trading import (get_hist_data, get_tick_data,
get_today_all, get_realtime_quotes,
get_h_data, get_today_ticks,
get_index, get_hists,
get_k_data, get_day_all,
get_sina_dd, bar, tick,
get_markets, quotes,
get_instrument, reset_instrument)
help(ts)
Help on package tushare:
NAME
tushare - # -*- coding:utf-8 -*-
PACKAGE CONTENTS
bond (package)
coins (package)
data (package)
fund (package)
futures (package)
internet (package)
pro (package)
stock (package)
trader (package)
util (package)
DATA
__warningregistry__ = {'version': 2757, ("unclosed file <_io.TextIOWra...
VERSION
1.2.17
AUTHOR
Jimmy Liu
FILE
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tushare/__init__.py
4.2. 函數(shù)幫助說明
- 常用的函數(shù)可以直接從官網(wǎng)獲取礼预。
- 部分函數(shù)在官網(wǎng)沒有說明的眠砾,直接使用help獲取幫助。
help(ts.get_k_data)
Help on function get_k_data in module tushare.stock.trading:
get_k_data(code=None, start='', end='', ktype='D', autype='qfq', index=False, retry_count=3, pause=0.001)
獲取k線數(shù)據(jù)
---------
Parameters:
code:string
股票代碼 e.g. 600848
start:string
開始日期 format:YYYY-MM-DD 為空時取上市首日
end:string
結(jié)束日期 format:YYYY-MM-DD 為空時取最近一個交易日
autype:string
復(fù)權(quán)類型逆瑞,qfq-前復(fù)權(quán) hfq-后復(fù)權(quán) None-不復(fù)權(quán)荠藤,默認(rèn)為qfq
ktype:string
數(shù)據(jù)類型,D=日k線 W=周 M=月 5=5分鐘 15=15分鐘 30=30分鐘 60=60分鐘获高,默認(rèn)為D
retry_count : int, 默認(rèn) 3
如遇網(wǎng)絡(luò)等問題重復(fù)執(zhí)行的次數(shù)
pause : int, 默認(rèn) 0
重復(fù)請求數(shù)據(jù)過程中暫停的秒數(shù)哈肖,防止請求間隔時間太短出現(xiàn)的問題
return
-------
DataFrame
date 交易日期 (index)
open 開盤價
high 最高價
close 收盤價
low 最低價
volume 成交量
amount 成交額
turnoverratio 換手率
code 股票代碼
4.3. k-線
- 來自百度百科
4.3.1. 來源
??K線圖這種圖表源處于日本德川幕府時代,被當(dāng)時日本米市的商人用來記錄米市的行情與價格波動念秧,后因其細(xì)膩獨(dú)到的標(biāo)畫方式而被引入到股市及期貨市場淤井。目前,這種圖表分析法在我國以至整個東南亞地區(qū)均尤為流行摊趾。由于用這種方法繪制出來的圖表形狀頗似一根根蠟燭币狠,加上這些蠟燭有黑白之分,因而也叫陰陽線圖表砾层。通過K線圖漩绵,我們能夠把每日或某一周期的市況表現(xiàn)完全記錄下來,股價經(jīng)過一段時間的盤檔后肛炮,在圖上即形成一種特殊區(qū)域或形態(tài)止吐,不同的形態(tài)顯示出不同意義宝踪。我們可以從這些形態(tài)的變化中摸索出一些有規(guī)律的東西出來。K線圖形態(tài)可分為反轉(zhuǎn)形態(tài)碍扔、整理形態(tài)及缺口和趨向線等瘩燥。
??那么,為什么叫“K線”呢不同?實(shí)際上厉膀,在日本的“K”并不是寫成“K”字,而是寫做“罫”(日本音讀kei)二拐,K線是“罫線”的讀音服鹅,K線圖稱為“罫線”,西方以其英文首字母“K”直譯為“K”線卓鹿,由此發(fā)展而來菱魔。
4.3.2. k-線說明
??首先我們找到該日或某一周期的最高和最低價,垂直地連成一條直線吟孙;
??然后再找出當(dāng)日或某一周期的開市和收市價,把這二個價位連接成一條狹長的長方柱體聚蝶。
????|- 1. 假如當(dāng)日或某一周期的收市價較開市價為高(即低開高收)杰妓,我們便以紅色來表示,或是在柱體上留白碘勉,這種柱體就稱之為“陽線”巷挥。
????|- 2. 如果當(dāng)日或某一周期的收市價較開市價為低(即高開低收),我們則以綠色表示验靡,又或是在柱上涂黑色倍宾,這柱體就是“陰線”了。
??根據(jù)K線的計(jì)算周期可將其分為日K線胜嗓,周K線高职,月K線,年K線辞州。
- 注意:
- 很多軟件都可以用彩色實(shí)體來表示陰線和陽線怔锌,在國內(nèi)股票和期貨市場 ,通常用紅色表示陽線变过,綠色表示陰線埃元。
- 但涉及到歐美股票及外匯市場的投資者應(yīng)該注意:在這些市場上通常用綠色代表陽線,紅色代表陰線媚狰,和國內(nèi)習(xí)慣剛好相反岛杀。
4.3.3. k-繪制
- 繪制k-線當(dāng)然使用第三方模塊。
1. 安裝matplotlib.finance
- matplotlib2以上版本已經(jīng)把mpl_finance模塊移除了,所以需要先安裝才能使用.
-
安裝指令:
pip install mpl-finance
-
下載鏈接:
- github下載模塊文件:
https://github.com/matplotlib/mpl_finance
- github下載模塊文件:
%matplotlib inline
import mpl_finance as mpf
2. k線繪制函數(shù)說明
candlestick_ohlc(ax, quotes, width=0.2, colorup='k', colordown='r', alpha=1.0)
# |- ax : `Axes`
# Axes對象
# |- quotes : sequence of (time, open, high, low, close, ...) sequences
# K-線數(shù)據(jù)崭孤,其中time必須是float格式类嗤。使用date2num函數(shù)轉(zhuǎn)換糊肠。
# |- width : float
# fraction of a day for the rectangle width
# |- colorup : color
# the color of the rectangle where close >= open
# |- colordown : color
# the color of the rectangle where close < open
# |- alpha : float
# the rectangle alpha level
#返回
# 返回 (lines, patches)
- 可以使用
help(mpf.candlestick_ohlc)
獲取官方幫助
3. 繪制實(shí)現(xiàn)
%matplotlib inline
import mpl_finance as mpf
import tushare as ts
import matplotlib.pyplot as plt
from matplotlib.pylab import date2num
import pandas as pd
# 加載數(shù)據(jù):index(['date', 'open', 'close', 'high', 'low', 'volume', 'code'], dtype='object')
k_data = ts.get_k_data('000010', start='2019-04-26', end='', ktype='D')
k_data['date'] = pd.to_datetime(k_data['date'], format="%Y-%m-%d") # 1994-03-24
# 把k-data轉(zhuǎn)換為candlestick_ohlc函數(shù)需要的類型。
mpf_data = []
for _, row in k_data.iterrows():
date_ = row[0: 1]
open_, close_, high_, low_ = row[1: 5]
mpf_data.append((date2num(date_), open_, high_, low_, close_))
# 創(chuàng)建坐標(biāo)系
figure = plt.figure(figsize=(8, 6))
ax = figure.add_axes([0.1, 0.1, 0.8, 0.8])
ax.xaxis_date() # x軸自動轉(zhuǎn)換為日期時間
plt.xticks(rotation=45) # 坐標(biāo)刻度標(biāo)簽旋轉(zhuǎn)45度
plt.yticks()
plt.title("600848:k-線圖(最近兩個月)") # 標(biāo)題
plt.xlabel("時間") # x-軸
plt.ylabel("股價(元)") # y-軸
mpf.candlestick_ohlc(ax, mpf_data, width=0.5, colorup=(1, 0, 0, 1), colordown=(0, 1, 0, 1))
# ax.plot(k_data['date'], k_data['close'])
plt.show()