介 紹在本教程中,我們將介紹神經(jīng)網(wǎng)絡(luò)的原型,該模型將使我們能夠使用Keras和Tensorflow作為我們的主要clarvoyance工具來估計未來的加密貨幣
介 紹
在本教程中,我們將介紹神經(jīng)網(wǎng)絡(luò)的原型,該模型將使我們能夠使用Keras和Tensorflow作為我們的主要clarvoyance工具來估計未來的加密貨幣價格(作為二進制分類問題)。
然這很可能不是解決問題的最佳方法(畢竟投資銀行在開發(fā)這種算法上投入了數(shù)十億美元),但如果我們能夠在55%以上的時間里把問題解決好,我們就有錢了!
我們要做什么
1. 使用Binance API下載數(shù)據(jù)
2. 預(yù)處理數(shù)據(jù)
3. 訓(xùn)練我們的模型
4. 特征工程
5. 評估性能最佳的模型
使用Binance API下載數(shù)據(jù)
對于此示例,我們將下載單個調(diào)用中可獲取的最大數(shù)據(jù)量。如果您想訓(xùn)練更多更好的東西并在現(xiàn)實世界中使用它(不建議這樣做,那么您可能會浪費真錢),我建議您使用多次調(diào)用收集更多數(shù)據(jù)。
import requests
import json
import pandas as pd
import datetime as dt
START_DATE = '2019-01-01'
END_DATE = '2019-10-01'
INTERVAL = '15m'
def parse_date(x):
return str(int(dt.datetime.fromisoformat(x).timestamp()))
def get_bars(symbol, interval):
root_url = 'https://api.binance.com/api/v1/klines'
url = root_url + '?symbol=' + symbol + '&interval=' + interval + '&startTime=' + parse_date(START_DATE) + '&limit=1000'
data = json.loads(requests.get(url).text)
df = pd.DataFrame(data)
df.columns = ['open_time',
'o', 'h', 'l', 'c', 'v',
'close_time', 'qav', 'num_trades',
'taker_base_vol', 'taker_quote_vol', 'ignore']
df.drop(['ignore', 'close_time'], axis=1, inplace=True)
return df
ethusdt = get_bars('ETHUSDT', INTERVAL)
ethusdt.to_csv('./data.csv', index=False)
在這段簡單的代碼中,我們需要必要的程序包,設(shè)置幾個參數(shù)(我選擇了15分鐘的時間間隔,但是您可以選擇更精細的時間間隔以進行更高頻率的交易)并設(shè)置一些方便的函數(shù),然后將數(shù)據(jù)保存到csv以供將來重用。這應(yīng)該是不言而喻的,但如果有什么事情讓你困惑,請隨時留下評論,要求澄清:)
數(shù)據(jù)預(yù)處理
由于價格是順序數(shù)據(jù)的一種形式,因此我們將使用LSTM層(長期短期記憶)作為我們網(wǎng)絡(luò)中的第一層。我們希望將數(shù)據(jù)提供為一系列事件,這些事件將預(yù)測時間t + n處的價格,其中t是當(dāng)前時間,n定義我們要預(yù)測的未來時間,為此,我們將數(shù)據(jù)作為 w長度的時間窗口。查看代碼后,一切將變得更加清晰,讓我們開始導(dǎo)入所需的軟件包。
import pandas as pd
import numpy as np
import seaborn as sns
import random
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM, Dropout
from tensorflow.keras.callbacks import TensorBoard
import time
import matplotlib.pyplot as plt
這將導(dǎo)入Pandas,Numpy,我們訓(xùn)練模型所需的所有Tensorflow函數(shù)以及其他一些有用的軟件包。
接下來,我們要定義一些常量,并從csv加載我們的數(shù)據(jù)(以防您在其他文件上編寫訓(xùn)練代碼:
WINDOW = 10 # how many time units we are going to use to evaluate
the future value, in our case each time unit is 15 minutes so we
are going to look at 15 * 10 = 150 minutes trading data
LOOKAHEAD = 5 # how far ahead we want to estimate if the future
prices is going to be higher or lower? In this case is 5 * 15 = 75
minutes in the future
VALIDATION_SAMPLES = 100 # We want to validate our model on data
that wasn't used for the training, we are establishing how many
data point we are going to use here.
data = pd.read_csv('./data.csv')
data['future_value'] = data['c'].shift(-LOOKAHEAD) # This allows us to
define a new column future_value with as the value of c 5 time units
in the future
data.drop([
'open_time'
], axis=1, inplace=True) # we don't care about the timestamp for
predicting future prices
讓我們定義一個函數(shù),該函數(shù)使我們可以定義將來的價格是高于還是低于當(dāng)前收盤價:
def define_output(last, future):
if future > last:
return 1
else:
return 0
如果價格低于或等于當(dāng)前收盤價,只需將目標(biāo)設(shè)置為0,如果價格高于或高于當(dāng)前收盤價,則將其設(shè)置為1。 現(xiàn)在讓我們定義一個函數(shù),該函數(shù)使我們能夠創(chuàng)建需要輸入神經(jīng)網(wǎng)絡(luò)的移動時間窗口:
def sequelize(x):
data = x.copy()
buys = []
sells = []
holds = []
data_length = len(data)
for index, row in data.iterrows():
if index <= data_length - WINDOW:
last_index = index + WINDOW -1
rowset = data[index : index + WINDOW]
row_stats = rowset.describe().transpose()
last_close = rowset['c'][last_index]
future_close = rowset['future_value'][last_index]
rowset = 2 * (rowset - row_stats['min']) / (row_stats['max'] - row_stats['min']) - 1
rowset.drop(['future_value'], axis=1, inplace=True)
rowset.fillna(0, inplace=True)
category = define_output(last_close, future_close)
if category == 1:
buys.append([rowset, category])
elif category == 0:
sells.append([rowset, category])
min_len = min(len(sells), len(buys))
results = sells[:min_len] + buys[:min_len]
return results
sequences = sequelize(data)
哦,好吧,這里有很多東西。讓我們一點一點地看:
data = x.copy() # let's copy the dataframe, just in case
buys = []
sells = []
holds = []
data_length = len(data)
在這里,我們正在做一些初步的工作,復(fù)制數(shù)據(jù)框以確保我們不覆蓋它(例如如果您使用Jupyter Notebook可能會很煩人),并設(shè)置用于買賣的數(shù)組,我們將使用它們來平衡數(shù)據(jù)。
for index, row in data.iterrows():
if index <= data_length - WINDOW:
last_index = index + WINDOW -1
rowset = data[index : index + WINDOW]
當(dāng)我們迭代數(shù)據(jù)集中的每一行時,如果索引大于我們定義的窗口大小,我們可以創(chuàng)建一個新的數(shù)據(jù)塊,即窗口大小。在將此數(shù)據(jù)存儲到另一個數(shù)組中之前,我們需要使用以下代碼對其進行規(guī)范化:
row_stats = rowset.describe().transpose()
last_close = rowset['c'][last_index]
future_close = rowset['future_value'][last_index] # we'll need to save this separately from the rest of the data
rowset = 2 * (rowset - row_stats['min']) / (row_stats['max'] - row_stats['min']) - 1
而且我們還想從數(shù)據(jù)集中刪除future_value,并用0替換任何可能的NaN(對于我們的目的而言,理想情況還不夠好):
rowset.drop(['future_value'], axis=1, inplace=True)
rowset.fillna(0, inplace=True)
最后我們要確保我們的買賣平衡,如果其中一種發(fā)生的頻率比另一種發(fā)生的頻率高,我們的網(wǎng)絡(luò)將迅速偏向偏斜,并且無法為我們提供可靠的估計:
if category == 1:
buys.append([rowset, category])
elif category == 0:
sells.append([rowset, category])
# the following 2 lines will ensure that we have an equal amount of buys and sells
min_len = min(len(sells), len(buys))
results = sells[:min_len] + buys[:min_len]
return results
最后我們在數(shù)據(jù)序列上運行此函數(shù)= sequelize(data)
隨機化我們的數(shù)據(jù)也是個好主意,這樣我們的模型就不會受到數(shù)據(jù)集排序的精確順序的影響,以下代碼將對數(shù)據(jù)集進行隨機化,將訓(xùn)練數(shù)據(jù)集與測試數(shù)據(jù)集進行拆分,并同時顯示這兩種數(shù)據(jù)中的買入與賣出分布數(shù)據(jù)集。隨時重新運行此代碼段,以確保更均衡地分配購買和出售:
random.shuffle(sequences)
def split_label_and_data(x):
length = len(x)
data_shape = x[0][0].shape
data = np.zeros(shape=(len(x),data_shape[0],data_shape[1]))
labels = np.zeros(shape=(length,))
for index in range(len(x)):
labels[index] = x[index][1]
data[index] = x[index][0]
return data, labels
x_train, y_train = split_label_and_data(sequences[: -VALIDATION_SAMPLES])
x_test, y_test = split_label_and_data(sequences[-VALIDATION_SAMPLES :])
sns.distplot(y_test)
sns.distplot(y_train)
len(y_train)
在運行了一段代碼后,您應(yīng)該得到類似的東西,兩個數(shù)據(jù)集之間的買賣均分(左對右)。
訓(xùn)練模型
現(xiàn)在我們已經(jīng)準(zhǔn)備好訓(xùn)練模型,但是由于我們還沒有探索哪種超參數(shù)最適合我們的模型和數(shù)據(jù),因此我們將嘗試一種稍微復(fù)雜一些的方法。 首先讓我們定義四個超參數(shù)數(shù)組:
DROPOUTS = [
0.1,
0.2,
]
HIDDENS = [
32,
64,
128
]
OPTIMIZERS = [
'rmsprop',
'adam'
]
LOSSES = [
'mse',
'binary_crossentropy'
]
然后,我們將遍歷每個數(shù)組以使用超參數(shù)組合來訓(xùn)練模型,以便以后可以使用TensorBoard比較它們:
for DROPOUT in DROPOUTS:
for HIDDEN in HIDDENS:
for OPTIMIZER in OPTIMIZERS:
for LOSS in LOSSES:
train_model(DROPOUT, HIDDEN, OPTIMIZER, LOSS)
現(xiàn)在我們需要定義train_model函數(shù),該函數(shù)將實際創(chuàng)建和訓(xùn)練模型:
def train_model(DROPOUT, HIDDEN, OPTIMIZER, LOSS):
NAME = f"{HIDDEN} - Dropout {DROPOUT} - Optimizer {OPTIMIZER} - Loss {LOSS} - {int(time.time())}"
tensorboard = TensorBoard(log_dir=f"logs/{NAME}", histogram_freq=1)
model = Sequential([
LSTM(HIDDEN, activation='relu', input_shape=x_train[0].shape),
Dropout(DROPOUT),
Dense(HIDDEN, activation='relu'),
Dropout(DROPOUT),
Dense(1, activation='sigmoid')
])
model.compile(
optimizer=OPTIMIZER,
loss=LOSS,
metrics=['accuracy']
)
model.fit(
x_train,
y_train,
epochs=60,
batch_size=64,
verbose=1,
validation_data=(x_test, y_test),
callbacks=[
tensorboard
]
)
目前,這是一個非常簡單的模型,其中的LSTM層為第一層,一個Dense中間層,一個Dense輸出層,其大小為1,且為S型激活。該層將輸出概率(從0到1),在LOOKAHEAD間隔之后,特定大小的WINDOW序列將跟隨較高的收盤價,其中0是較低的收盤價的高概率,1是較高的更高的收盤價。
我們還添加了一個Tensorboard回調(diào),這將使我們能夠看到每種模型在每個訓(xùn)練周期(EPOCH)的表現(xiàn)。
隨意運行此代碼,然后在終端tensorboard --logdir = logs中運行Tensorboard
特征工程
最好的模型在驗證數(shù)據(jù)上的準(zhǔn)確性應(yīng)該高于60%,這已經(jīng)相當(dāng)不錯了。但是我們可以通過從現(xiàn)有數(shù)據(jù)集中提取更多數(shù)據(jù)來快速改進模型。從現(xiàn)有要素中提取新要素的過程稱為要素工程。特征工程的示例是從數(shù)據(jù)中提取周末布爾值列,或從坐標(biāo)對中提取國家/地區(qū)。在我們的案例中,我們將技術(shù)分析數(shù)據(jù)添加到我們的OHLC數(shù)據(jù)集中。
在筆記本或文件的頂部,添加ta包:from ta import *。
從csv加載數(shù)據(jù)后,添加以下行,它將以新列的形式將TA數(shù)據(jù)追加到我們現(xiàn)有的數(shù)據(jù)集中
data = pd.read_csv('./data.csv')
#add the following line
add_all_ta_features(data, "o", "h", "l", "c", "v", fillna=True)
data['future_value'] = data['c'].shift(-LOOKAHEAD)
就是這樣,在幾行中我們極大地豐富了我們的數(shù)據(jù)集。 現(xiàn)在我們可以運行模型生成器循環(huán)來弄清楚我們的模型如何使用新的數(shù)據(jù)集,這將花費更長的時間,但值得等待。
有意義的數(shù)據(jù)集應(yīng)確保模型更準(zhǔn)確,在上圖中,我們可以清楚地看到豐富數(shù)據(jù)集的性能比簡單數(shù)據(jù)集更好,驗證準(zhǔn)確性徘徊在80%左右!
評估性能最佳的模型
現(xiàn)在我們有了一些看起來在紙面上表現(xiàn)不錯的模型,我們?nèi)绾卧u估假設(shè)的交易系統(tǒng)中應(yīng)該使用哪個模型?
這可能是非常主觀的,但我認(rèn)為一種好的方法是從已知的驗證標(biāo)簽分別查看買賣,并繪制相應(yīng)預(yù)測的分布。希望于所有購買,我們的模型都可以預(yù)測購買,而不是很多出售,反之亦然。
讓我們定義一個顯示每個模型的圖表的函數(shù):
def display_results(NAME, y_test, predictions):
plt.figure()
buys = []
sells = []
for index in range(len(y_test)):
if y_test[index] == 0:
sells.append(predictions[index])
elif y_test[index] == 1:
buys.append(predictions[index])
sns.distplot(buys, bins=10, color='green').set_title(NAME)
sns.distplot(sells, bins=10, color='red')
plt.show()
現(xiàn)在讓我們在每次完成模型訓(xùn)練時都調(diào)用此函數(shù):
model.fit(
x_train,
y_train,
epochs=60,
batch_size=64,
verbose=0,
validation_data=(x_test, y_test),
callbacks=[
tensorboard
]
)
# after the model.fit call, add the following 2 lines.
predictions = model.predict(x_test)
display_results(NAME, y_test, predictions)
隨著不同模型的訓(xùn)練,我們現(xiàn)在應(yīng)該看到類似于下圖的圖像,其中買入以綠色繪制(并且我們希望它們在右端,聚集在1值附近),賣出以紅色繪制(聚集在 左側(cè)為0個值)。這些應(yīng)有助于我們確定哪種模型可以提供更可靠的未來價格估算。(鏈三豐)
就是這樣,我們現(xiàn)在有一些原型可以使用,它們可以對未來的價格提供合理的估計。作為練習(xí),請嘗試以下操作:
1. 如果增加網(wǎng)絡(luò)的隱藏層數(shù)會怎樣?
2. 如果您的數(shù)據(jù)集不平衡會怎樣?
3. 如果增加DROPOUT值會怎樣?
4. 如果您在新數(shù)據(jù)上測試最佳模型會怎樣?(例如通過從幣安獲取不同的時間戳記?)
關(guān)鍵詞: Keras Tensorflow 加密貨幣價格