資源簡介
nulindai.py
代碼片段和文件信息
import?pandas?as?pd
import?numpy?as?np
import?talib?as?ta
import?tushare?as?ts
import?re
import?urllib.request
import?matplotlib.pyplot?as?plt
import?pickle
from?matplotlib.pyplot?import?savefig
import?heapq
def?GetStockcode():??#?獲取股票代碼
????url?=?‘http://biz.finance.sina.com.cn/suggest/lookup_n.php?country=stock&q=%D2%F8%D0%D0‘
????headers?=?{“User-Agent“:?“Mozilla/5.0?(Windows?NT?10.0;?WOW64)“}
????request?=?urllib.request.Request(url=url?headers=headers)
????response?=?urllib.request.urlopen(request)
????content?=?response.read().decode(‘gbk‘)
????pattern?=?re.compile(‘s[hz]\d{6}‘)
????item?=?re.findall(pattern?content)
????item?=?item[::2]??#?取偶
????item?=?item[0:24]
????stockcode?=?[]
????for?i?in?item:??#?去除sz/h
????????stockcode.append(i[2:])
????return?stockcode
‘‘‘def?GetData(stk):
????pkl_file=open(‘%s.pkl‘%stk‘rb‘)
????data=pickle.load(pkl_file)
????pkl_file.close()
????return?data‘‘‘
def?GetDataTus(stk?start?end):??#?獲取交易數據
????data?=?ts.get_k_data(stk?start=start?end=end)
????return?data
def?GetBand(data?timeperiod=20?nbdevup=2?nbdevdn=2?matype=0):
????band?=?pd.Dataframe(index=data.index)
????band[‘date‘]?=?data[‘date‘]
????band[‘close‘]?=?data[‘close‘]
????band[‘upper‘]?band[‘middle‘]?band[‘lower‘]?=?ta.BBANDS(data.close.values?timeperiod=timeperiod?nbdevup=nbdevup
?????????????????????????????????????????????????????????????nbdevdn=nbdevdn?matype=matype)
????band[‘MA20‘]?=?data[‘close‘].rolling(window=20).mean()
????band[‘dev‘]?=?data[‘close‘].rolling(window=20).std()
????band[‘index‘]?=?data.index
????band?=?band.dropna(axis=0?how=‘any‘)??#?清除為空的行
????band?=?band.reset_index()??#?索引重新排序并生成新的列,level_0
????del?band[‘level_0‘]
????band[‘devchange‘]?=?band[‘dev‘]?-?band[‘dev‘].shift(-1)??#?i+1-i
????band?=?band.dropna()
????band?=?band.reset_index()
????del?band[‘level_0‘]
????code?=?data.iloc[1?-1]
????df2?=?ts.get_k_data(code?start=‘2011-01-01‘?end=‘2012-01-01‘)
????df3?=?ts.get_k_data(code?start=‘2012-01-01‘?end=‘2013-01-01‘)
????df4?=?ts.get_k_data(code?start=‘2013-01-01‘?end=‘2014-01-01‘)
????df5?=?ts.get_k_data(code?start=‘2014-01-01‘?end=‘2015-01-01‘)
????df6?=?ts.get_k_data(code?start=‘2015-01-01‘?end=‘2016-01-01‘)
????d2?=?df2.close.rolling(window=20).std()
????d3?=?df3.close.rolling(window=20).std()
????d4?=?df4.close.rolling(window=20).std()
????d5?=?df5.close.rolling(window=20).std()
????d6?=?df6.close.rolling(window=20).std()
????c2?=?[]
????c3?=?[]
????c4?=?[]
????c5?=?[]
????c6?=?[]
????for?i?in?range(20?len(d2)?-?20):
????????c2.append(d2[i]?-?d2[i?-?1])
????data2?=?heapq.nlargest(50?c2)
????for?i?in?range(20?len(d3)?-?20):
????????c3.append(d3[i]?-?d3[i?-?1])
????data3?=?heapq.nlargest(50?c3)
????for?i?in?range(20?len(d4)?-?20):
????????c4.append(d4[i]?-?d4[i?-?1])
????data4?=?heapq.nlargest(50?c4)
????for?i?in?range(20?len(d5)?-?20):
????????c5.append(d5[i]?-?d5[i?-?1])
????data5?=?heapq.nl
評論
共有 條評論