缘由:好友开发了一个程序化交易虚拟货币的助手软件。卖的火热(想购买的朋友请加微信: endpang )。出于对土豪的敬意,抽时间做一个时序预测的东西。
财富自由之路开始。。。。
首先得获得实时的价格数据,
火币网的接口:https://github.com/huobiapi/API_Docs/wiki/REST_introduction
websocket 获得实时数据并将价格写入文本文件
from websocket import create_connection import gzip import time import json if __name__ == '__main__': while(1): try: ws = create_connection("wss://api.huobipro.com/ws") break except: print('connect ws error,retry...') time.sleep(5) # 订阅 KLine 数据 tradeStr="""{"sub": "market.ethusdt.kline.1min","id": "id10"}""" # 请求 KLine 数据 # tradeStr="""{"req": "market.ethusdt.kline.1min","id": "id10", "from": 1513391453, "to": 1513392453}""" #订阅 Market Depth 数据 # tradeStr="""{"sub": "market.ethusdt.depth.step5", "id": "id10"}""" #请求 Market Depth 数据 # tradeStr="""{"req": "market.ethusdt.depth.step5", "id": "id10"}""" #订阅 Trade Detail 数据 # tradeStr="""{"sub": "market.ethusdt.trade.detail", "id": "id10"}""" #请求 Trade Detail 数据 # tradeStr="""{"req": "market.ethusdt.trade.detail", "id": "id10"}""" #请求 Market Detail 数据 # tradeStr="""{"req": "market.ethusdt.detail", "id": "id12"}""" ws.send(tradeStr) old = {"vol": 0,"count":0,"close":0} i = 0 with open('test_csv.csv',"w") as csv: #csv.write("lines\n") while(1): compressData=ws.recv() result=gzip.decompress(compressData).decode('utf-8') if result[:7] == '{"ping"': ts=result[8:21] pong='{"pong":'+ts+'}' ws.send(pong) ws.send(tradeStr) elif result[:5] == '{"ch"': arr = json.loads(result) #print("arr",arr) if arr['tick']['count'] < old["count"]: i = i+1 csv.write(format(old['close'])+"\n") print('count',old) else: delta = arr['tick']['vol'] - old['vol'] print("delta:",delta) if delta > 0: deltap = arr['tick']['close'] - old["close"] print("deltap",deltap) old = arr['tick']
基于tensorflow lstm 的预测模型。
import lstm import time import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt def plot_results(predicted_data, true_data): fig = plt.figure(facecolor='white') ax = fig.add_subplot(111) ax.plot(true_data, label='True Data') plt.plot(predicted_data, label='Prediction') plt.legend() plt.show() def plot_results_multiple(predicted_data, true_data, prediction_len): fig = plt.figure(facecolor='white') ax = fig.add_subplot(111) ax.plot(true_data, label='True Data') #Pad the list of predictions to shift it in the graph to it's correct start for i, data in enumerate(predicted_data): padding = [None for p in range(i * prediction_len)] plt.plot(padding + data, label='Prediction') plt.legend() plt.show() #Main Run Thread if __name__=='__main__': global_start_time = time.time() epochs = 1 seq_len = 50 print('> Loading data... ') X_train, y_train, X_test, y_test = lstm.load_data('test_csv.csv', seq_len, True) print('> Data Loaded. Compiling...') model = lstm.build_model([1, 50, 100, 1]) model.fit( X_train, y_train, batch_size=512, nb_epoch=epochs, validation_split=0.05) predictions = lstm.predict_sequences_multiple(model, X_test, seq_len, 50) #predicted = lstm.predict_sequence_full(model, X_test, seq_len) #predicted = lstm.predict_point_by_point(model, X_test) print('Training duration (s) : ', time.time() - global_start_time) plot_results_multiple(predictions, y_test, 50)
市场有风险,交易需谨慎。不准莫怪我,预测准的,写出来也不会开放代码的。。。 : P