Обсуждение статьи "Использование ONNX-моделей в MQL5" - страница 3

 

Обзоры по приложениям (объекты, модели и инструменты)

1. Survey on the application of deep learning in algorithmic trading (2021)

Algorithmic trading is one of the most concerned directions in financial applications.

Compared with traditional trading strategies, algorithmic trading applications perform forecasting and arbitrage with higher efficiency and more stable performance.

Numerous studies on algorithmic trading models using deep learning have been conducted to perform trading forecasting and analysis.

In this article, we firstly summarize several deep learning methods that have shown good performance in algorithmic trading applications, and briefly introduce some applications of deep learning in algorithmic trading.

We then try to provide the latest snapshot application for algorithmic trading based on deep learning technology, and show the different implementations of the developed algorithmic trading model.

Finally, some possible research issues are suggested in the future.

The prime objectives of this paper are to provide a comprehensive research progress of deep learning applications in algorithmic trading, and benefit for subsequent research of computer program trading systems.


2. Deep Learning for Financial Applications : A Survey (2020)

Computational intelligence in finance has been a very popular topic for both academia and financial industry in the last few decades.

Numerous studies have been published resulting in various models. Meanwhile, within the Machine Learning (ML) field, Deep Learning (DL) started getting a lot of attention recently, mostly due to its outperformance over the classical models.

Lots of different implementations of DL exist today, and the broad interest is continuing. Finance is one particular area where DL models started getting traction, however, the playfield is wide open, a lot of research opportunities still exist.

In this paper, we tried to provide a state-of-the-art snapshot of the developed DL models for financial applications, as of today.

We not only categorized the works according to their intended subfield in finance but also analyzed them based on their DL models.

In addition, we also aimed at identifying possible future implementations and highlighted the pathway for the ongoing research within the field.

 


 

 

 

 

 




3. Financial Time Series Forecasting with Deep Learning : A Systematic Literature Review: 2005-2019 (2019)

Financial time series forecasting is, without a doubt, the top choice of computational intelligence for finance researchers from both academia and financial industry due to its broad implementation areas and substantial impact.

Machine Learning (ML) researchers came up with various models and a vast number of studies have been published accordingly.

As such, a significant amount of surveys exist covering ML for financial time series forecasting studies.

Lately, Deep Learning (DL) models started appearing within the field, with results that significantly outperform traditional ML counterparts.

Even though there is a growing interest in developing models for financial time series forecasting research, there is a lack of review papers that were solely focused on DL for finance.

Hence, our motivation in this paper is to provide a comprehensive literature review on DL studies for financial time series forecasting implementations.

We not only categorized the studies according to their intended forecasting implementation areas, such as index, forex, commodity forecasting, but also grouped them based on their DL model choices, such as Convolutional Neural Networks (CNNs), Deep Belief Networks (DBNs), Long-Short Term Memory (LSTM).

We also tried to envision the future for the field by highlighting the possible setbacks and opportunities, so the interested researchers can benefit





 

Нейронная сеть CNN LSTM созданная CHATGPT

# Import necessary libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM, Dropout, Conv1D, MaxPooling1D, Flatten

# Load the dataset
df = pd.read_csv('https://query1.finance.yahoo.com/v7/finance/download/AAPL?period1=1411958400&period2=1636521600&interval=1d&events=history&includeAdjustedClose=true')

# Preprocess the data
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(df['Close'].values.reshape(-1, 1))

# Split the data into training and testing sets
training_size = int(len(scaled_data) * 0.7)
testing_size = len(scaled_data) - training_size
training_data = scaled_data[0:training_size, :]
testing_data = scaled_data[training_size:len(scaled_data), :]

# Function to create input features and labels for model
def create_dataset(dataset, look_back):
    data_X, data_Y = [], []
    for i in range(len(dataset)-look_back-1):
        a = dataset[i:(i+look_back), 0]
        data_X.append(a)
        data_Y.append(dataset[i + look_back, 0])
    return np.array(data_X), np.array(data_Y)

# Create input features and labels for training and testing sets
look_back = 60
X_train, y_train = create_dataset(training_data, look_back)
X_test, y_test = create_dataset(testing_data, look_back)

# Reshape the input data for CNN-LSTM model
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))

# Define and compile the CNN-LSTM model
model = Sequential()

model.add(Conv1D(filters=32, kernel_size=5, activation='relu', input_shape=(look_back, 1)))
model.add(MaxPooling1D(pool_size=2))
model.add(Dropout(0.2))

model.add(Conv1D(filters=64, kernel_size=5, activation='relu'))
model.add(MaxPooling1D(pool_size=2))
model.add(Dropout(0.2))

model.add(LSTM(50, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(50))
model.add(Dropout(0.2))

model.add(Dense(1))

model.compile(loss='mean_squared_error', optimizer='adam')

# Train the model on the training data
model.fit(X_train, y_train, epochs=100, batch_size=32)

# Use the model to make predictions on the testing data
y_pred = model.predict(X_test)

# Rescale the data back to original values
y_pred = scaler.inverse_transform(y_pred)
y_test = scaler.inverse_transform(y_test.reshape(-1, 1))

# Plot the original and forecasted values
plt.plot(y_test, label='Actual')
plt.plot(y_pred, label='Predicted')
plt.xlabel('Time')
plt.ylabel('Close Price')
plt.title('AAPL Stock Price Forecast')
plt.legend()
plt.show()

Результат выполнения в Jupyter Notebook
 
Ожидали чего то другого? Только через собственный опыт и знания может быть результат.
 
Vladimir Perervenko #:
Ожидали чего то другого? Только через собственный опыт и знания может быть результат.

Скорее не ожидал что такое сейчас возможно, технологии впечатляют. Согласен, что даже с такими инструментами требуется серьезный труд, и опыт сын ошибок трудных...

 
Vladimir Perervenko #:

Перенести препроцессинг в МТ не проблема, очень хочется протестировать систему в МТ тестере, в питоне/R нужно свой тестер писать, чревато ошибками.

 
Vladimir Perervenko #:

Любой проект машинного обучения состоит из трех этапов:

  • препроцессинг (очень много чего)
  • выбор модели, обучение, оптимизация и т.п. 
  • внедрение

Использование ONNX моделей в мкл решает вопрос с внедрением. Правда не всех моделей и не совсем просто.

Обучение и оптимизация моделей решается отдельным процессом в Питоне.

Но из всех вышеперечисленных, первый этап - самый трудоемкий, сильно творческий и самый важный. И как раз его на мкл реализовать пока  невозможно. Не считаем же примитивное шкалирование за препроцессинг. А народная мудрость гласит: "Мусор на входе - мусор на выходе". Слишком много нужно дополнительно разработать и внедрить в МКЛ для полноценного использования МО только на МКЛ. Нельзя объять необъятное, тем более, что оно постоянно расширяется...

Неужели всё так плохо? Ведь куча статей уже написана про нейросети. И даже есть такие, где всё "просто"...

 
Vladimir Perervenko #:

Любой проект машинного обучения состоит из трех этапов:

  • препроцессинг (очень много чего)

Но из всех вышеперечисленных, первый этап - самый трудоемкий, сильно творческий и самый важный. И как раз его на мкл реализовать пока  невозможно.

Насколько я понимаю, речь идет о трудностях расчета неких функций цены, которые выступают как features сети.

Можете привести пример, возможно здесь найдутся те, кто представит реализацию этих вещей.

 
Denis Kirichenko #:

Неужели всё так плохо? Ведь куча статей уже написана про нейросети. И даже есть такие, где всё "просто"...

Да не плохо. Все в очень зачаточном состоянии по сравнению с современным развитием функционала препроцессинга. 

Я занимаюсь программированием на R довольно долго. Питон использую не так давно и основное , на что обратил внимание при изучении проектов (пакетов) машинного обучения на Питоне, практически полное отсутствие препроцессинга. Подход такой - модель все вывезет. Это ни плохо ни хорошо. Это  такой подход который сложился исторически.

В отличии от этого в R огромный арсенал препроцессинга с пониманием того для чего это все.

Хотя в последнее время наблюдается обоюдное заимствование многих полезных наработок.

Я к тому, что нельзя объять необъятное, а разработчики к этому стремятся. Портировать то что написано на С - да, но переписывать все на МКЛ...

Касательно ONNX. Область новая, очень перспективная, быстро развивающаяся и востребованная. Значить будет и возможность загонять в ONNX и препроцессинг. В TensorFlow уже есть слои предобработки, правда простые, но все же. Нужно пробовать, изучать пригодится.

Конечно выглядит более привлекательным использование ONNX в обучении, но это только для Линукс. Может знатоки WSL смогут это как то использовать. 

 
Странно, сеть обучается на часовом периоде, а советник скармливает дневные данные. Ошибка? Или я чего то не понимаю?
 
Vladimir Perervenko #:

Любой проект машинного обучения состоит из трех этапов:

  • препроцессинг (очень много чего)
  • выбор модели, обучение, оптимизация и т.п. 
  • внедрение

Использование ONNX моделей в мкл решает вопрос с внедрением. Правда не всех моделей и не совсем просто.

Обучение и оптимизация моделей решается отдельным процессом в Питоне.

Но из всех вышеперечисленных, первый этап - самый трудоемкий, сильно творческий и самый важный. И как раз его на мкл реализовать пока  невозможно. Не считаем же примитивное шкалирование за препроцессинг. А народная мудрость гласит: "Мусор на входе - мусор на выходе". Слишком много нужно дополнительно разработать и внедрить в МКЛ для полноценного использования МО только на МКЛ. Нельзя объять необъятное, тем более, что оно постоянно расширяется.

Поэтому для выполнения препроцесса либо делать его в другом ЯП (кто какой освоил R/Python/Julia и т.д.) либо пробовать конвертировать и его в ONNX. 

Польза от внедрения ONNX пока только в том, что научимся конвертировать, создавать, упрощать и оптимизировать модели ONNX. Может в будущем пригодится.

Лучше и не скажешь, все точно и по делу

Причина обращения: