• Stars
    star
    153
  • Rank 243,368 (Top 5 %)
  • Language
    MATLAB
  • License
    Other
  • Created almost 5 years ago
  • Updated 9 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

MATLAB example on how to use Reinforcement Learning for developing a financial trading model

Reinforcement Learning For Financial Trading ๐Ÿ“ˆ

How to use Reinforcement learning for financial trading using Simulated Stock Data using MATLAB.

Setup

To run:

  1. Open RL_trading_demo.prj
  2. Open workflow.mlx (MATLAB Live Script preferred) or workflow.m (MATLAB script viewable in GitHub)
  3. Run workflow.mlx

Environment and Reward can be found in: myStepFunction.m

Requires

Overview

The goal of the Reinforcement Learning agent is simple. Learn how to trade the financial markets without ever losing money.

Note, this is different from learn how to trade the market and make the most money possible.

Reinforcement Learning for Financial Trading

Lets apply some of the terminology and concepts of teaching a reinforcement learning agent to trade.

  • The agent in this case study is the computer.
  • It will observe financial market indicators (states).
  • The financial market is the environment.
  • The actions it can take are buy, hold sell.
  • It needs to learn which action to take and when (policy).
  • It learns by understanding what is a good trade or a bad trade via rewards.

Case Study

Our environment consists of 3 stocks, $20000 cash & 15 years of historical data:

Stocks are:

Actions (buy, sell ,hold) for 3 stocks = 27 total actions

The States being observed are:

  • Stocks Owned
  • Price Different when Bought
  • Cash In Hand
  • Price change from yesterday
  • % Price change from 2 days ago
  • % Price change from 7 days ago
  • % Price change from average price of 7 days ago

Strategy

  • Given 3 stocks
  • Try to find the best time to buy, sell, or hold each stock
  • If selling a stock, sell all of it.
  • If buying a stock, buy the maximum allowed given cash in hand.

Reward

The reward system was what took the most time to develop and required several iterations.

The details are listed, but to simplify

A good reward is given when a trade results in a profit and a stock is bought/held/sold at the right time. For example buying a stock on the way up.

The reverse goes for giving a penalty except for one thing.

A large penalty is given if ANY trade of the 3 stocks is determined as a bad trade. WHY? In the first iteration of the reward system, this was not there. What was observed is that the agent quickly learnt the best of the 3 stocks to trade and ignored the other 2.

  • A good reward is given when
    • A selling trade results in profit
    • A selling trade occurs with momentum
      • I.e. selling when prices start to fall -Holding a stock results in the portfolio value increasing
  • A bad reward is given when
    • Selling results in a negative profit
    • A selling trade occurs against momentum
      • I.e. selling when prices are increasing, buying when prices are falling
    • Holding a stock results in the portfolio value decreasing
    • A good reward is overwritten to be bad if any illogical trade occurs
      • I.e. sell a stock you donโ€™t have or buy when you donโ€™t had cash

Training

  • Based 12years of data
  • 3000 episodes
  • ~80hrs to train

Here is an overview of how long it took to learn. You might think 80hrs is a long time. But remember, how long do you think it takes a human to learn how to trade successfully over 12 years?

Results

Highlights

  • 100 Simulations of 3 years:
    • Average profit - ~$30k
    • 0 simulations returned negative
    • But most did not outperform individual stocks

Histogram of 100 Simulations

Best Simulation

Worst Simulation

The histogram shows that for 100 simulations, not once did the agent ever lose money. So the goal was achieved!

However, you can see that the range varies quite a bit. If you inspect the plots on the right, just buying and holding 1 stock would returned a profit just as good if not better than the agent.

BUT โ€“ Itโ€™s easy to judge retrospectively. The agent was trading each day as it occurred. None of the simulations resulted in a loss.

Further Improvements

The case study did ignore some common things to consider when trading the market. Here a few areas that could improve the performance, and make the trained agent more robust:

  • Include Transaction costs
  • Cover the Hi/Lo spread
  • Refined reward system
  • Compare different agents

Conclusion

The aim of this example was to show:

  • What reinforcement learning is
  • How it can be applied to trading the financial markets
  • Leave a starting point for financial professionals to use and enhance using their own domain expertise.

For more information on Reinforcement Learning in MATLAB:

Free Reinforcement Learning Onramp - No downloads, or installation, just your browser and you!

Download a free trial

Getting Started with Reinforcement Learning (YouTube series)

Copyright 2020 The MathWorks, Inc.

View Reinforcement Learning for Financial Trading on File Exchange

More Repositories

1

MATLAB-Deep-Learning-Model-Hub

Discover pretrained models for deep learning in MATLAB
MATLAB
447
star
2

transformer-models

Deep Learning Transformer models in MATLAB
MATLAB
199
star
3

llms-with-matlab

Connect MATLAB to LLM APIs, including OpenAIยฎ Chat Completions, Azureยฎ OpenAI Services, and Ollamaโ„ข
MATLAB
104
star
4

Fault-Detection-Using-Deep-Learning-Classification

This demo shows how to prepare, model, and deploy a deep learning LSTM based classification algorithm to identify the condition or output of a mechanical air compressor.
C++
75
star
5

Image-Classification-in-MATLAB-Using-TensorFlow

This example shows how to call a TensorFlow model from MATLAB using co-execution with Python.
MATLAB
49
star
6

Abnormal-EEG-Signal-Classification-Using-CNNs

This example shows how to build and train a convolutional neural network (CNN) from scratch to perform a classification task with an EEG dataset.
MATLAB
47
star
7

pretrained-yolo-v4

Object detection and transfer learning using pretrained YOLO v4 models in MATLAB.
MATLAB
46
star
8

rl-agent-based-traffic-control

Develop agent-based traffic management system by model-free reinforcement learning
MATLAB
45
star
9

Industrial-Machinery-Anomaly-Detection

Extract features and detect anomalies in industrial machinery vibration data using a biLSTM autoencoder
MATLAB
44
star
10

pose-estimation-3d-with-stereo-camera

This demo uses a deep neural network and two generic cameras to perform 3D pose estimation.
MATLAB
43
star
11

constrained-deep-learning

Constrained deep learning is an advanced approach to training deep neural networks by incorporating domain-specific constraints into the learning process.
MATLAB
36
star
12

Object-Detection-Using-YOLO-v2-Deep-Learning

MATLAB example of deep learning based object detection using Yolo v2 with ResNet50 Base Network
Cuda
35
star
13

playing-Pong-with-deep-reinforcement-learning

Train a reinforcement learning agent to play a variation of Pongยฎ
MATLAB
34
star
14

Explore-Deep-Network-Explainability-Using-an-App

This repository provides an app for exploring the predictions of an image classification network using several deep learning visualization techniques. Using the app, you can: explore network predictions with occlusion sensitivity, Grad-CAM, and gradient attribution methods, investigate misclassifications using confusion and t-SNE plots, visualize layer activations, and many more techniques to help you understand and explain your deep networkโ€™s predictions.
MATLAB
34
star
15

Brain-MRI-Age-Classification-using-Deep-Learning

MATLAB example using deep learning to classify chronological age from brain MRI images
MATLAB
33
star
16

transformer-networks-for-time-series-prediction

Deep Learning in Quantitative Finance: Transformer Networks for Time Series Prediction
MATLAB
33
star
17

Inverse-Problems-using-Physics-Informed-Neural-Networks-PINNs

MATLAB
32
star
18

COVID19-Face-Mask-Detection-using-deep-learning

The entire workflow of developing deep learning model for detecting face mask.
MATLAB
30
star
19

mask-rcnn

Mask-RCNN training and prediction in MATLAB for Instance Segmentation
MATLAB
29
star
20

pix2pix

Image to Image Translation Using Generative Adversarial Networks
MATLAB
28
star
21

Human-Pose-Estimation-with-Deep-Learning

MATLAB example of deep learning based human pose estimation.
HTML
27
star
22

mtcnn-face-detection

Face detection and alignment using deep learning
HTML
26
star
23

resnet-50

Repo for ResNet-50
MATLAB
26
star
24

pretrained-spatial-CNN

Spatial-CNN for lane detection in MATLAB.
MATLAB
24
star
25

Pretrained-YOLOX-Network-For-Object-Detection

YOLOX inference in MATLAB for Object Detection with yolox_s, yolox_m & yolox_l networks
24
star
26

Pretrained-YOLOv8-Network-For-Object-Detection

YOLO v8 training and inference in MATLAB for Object Detection with yolov8n, yolov8s, yolov8m, yolov8l, yolov8x, networks
MATLAB
24
star
27

pretrained-deeplabv3plus

DeepLabv3+ inference and training in MATLAB for Semantic Segmentation
MATLAB
23
star
28

googlenet

Repo for GoogLeNet
MATLAB
22
star
29

deep-sudoku-solver

Find and solve sudoku puzzles in images using deep learning and computer vision
MATLAB
22
star
30

Lidar-object-detection-using-complex-yolov4

Object detection and transfer learning on point clouds using pretrained Complex-YOLOv4 models in MATLAB
MATLAB
21
star
31

2D-Differentiable-Rendering-Example

MATLAB
18
star
32

resnet-18

Repo for ResNet-18
MATLAB
17
star
33

Object-Detection-Using-Pretrained-YOLO-v2

YOLO v2 prediction and training in MATLAB for Object Detection with darknet19 & tinyYOLOv2 base networks
17
star
34

Image-domain-conversion-using-CycleGAN

MATLAB example of deep learning for image domain conversion
MATLAB
16
star
35

fourier-neural-operator

MATLAB
15
star
36

Hyperparameter-Tuning-in-MATLAB-using-Experiment-Manager-and-TensorFlow

This example shows how to use MATLAB to train a TensorFlow model and tune it's hyperparameters using co-execution with Python.
MATLAB
15
star
37

pretrained-efficientdet-d0

Object detection and transfer learning using pretrained EfficientDet-D0 model in MATLAB.
MATLAB
15
star
38

pretrained-salsanext

Semantic segmentation and transfer learning using pretrained SalsaNext model in MATLAB
MATLAB
14
star
39

Social-Distancing-Monitoring-System

AI-enabled social distancing detection tool that can detect if people are keeping a safe distance from each other by analyzing real-time video streams from the camera. - Idea Credit : Landing AI (https://landing.ai/)
MATLAB
14
star
40

mobilenet-v2

Repo for MobileNet-v2
MATLAB
13
star
41

Text-Detection-using-Deep-Learning

Text Detection using Pretrained CRAFT model in MATLAB
12
star
42

Image-Classification-in-MATLAB-Using-Converted-TensorFlow-Model

This repository shows how to import a pretrained TensorFlow model in the SavedModel format, and use the imported network to classify an image.
MATLAB
12
star
43

Automate-Labeling-in-Image-Labeler-using-a-Pretrained-TensorFlow-Object-Detector

This example shows how to automate object labeling in the Image Labeler app using a TensorFlow object detector model trained in Python.
MATLAB
12
star
44

resnet-101

Repo for ResNet-101 model
MATLAB
11
star
45

compare-PyTorch-models-from-MATLAB

Compare PyTorch models from MATLAB using co-execution
MATLAB
11
star
46

Quantized-Deep-Neural-Network-on-Jetson-AGX-Xavier

How to create, train and quantize network, then integrate it into pre/post image processing and generate CUDA C++ code for targeting Jetson AGX Xavier
MATLAB
11
star
47

Hamiltonian-Neural-Network

MATLAB
10
star
48

pillQC

A pill quality control dataset and associated anomaly detection example
MATLAB
10
star
49

CSINet-Channel-Compression-in-MATLAB-Using-Keras

This example shows how to co-execute MATLAB and Python to simulate the effect of channel estimate compression on precoding in a MIMO OFDM channel.
MATLAB
10
star
50

neuron-coverage-for-deep-learning

Compute the neuron coverage of a deep learning network in MATLAB.
MATLAB
9
star
51

quantization-aware-training

This example shows how to perform quantization aware training for transfer learned MobileNet-v2 network.
HTML
9
star
52

nerf

NeRF - Neural Radiance Fileds in MATLAB
MATLAB
9
star
53

stride-measurement-of-runner

This sample script is to measure the stride of a runner in video by using pretrained deep learning model and simple signal processing.
MATLAB
9
star
54

coexecution_speech_command

PyTorch and TensorFlow Co-Execution for Speech Command Recognition
Python
8
star
55

Classification-of-SARS-COVID-19-and-Other-Lung-Infections-from-Chest-X-Ray-Scan-Images-with-DenseNet

This example shows how to train a deep neural network to classify SARS COVID-19 and other lung infections using chest X-ray (CXR) images.
MATLAB
8
star
56

Physical-Concepts-Scinet

This repository provides implementation of SciNet network described in arXiv:1807.10300v3
MATLAB
7
star
57

deepspeech

This repo provides the pretrained DeepSpeech model in MATLAB. The model is compatible with transfer learning and C/C++ code generation.
MATLAB
7
star
58

Seven-Segment-Digit-Recognition

Seven Segment Digit Recognition in MATLAB
6
star
59

Deep_Learning_Poker_Player_using_MATLAB_and_Raspberry_Pi

This example shows how to use automatic code generation to deploy a deep learning model from MATLAB to Raspberry Pi
MATLAB
6
star
60

wav2vec-2.0

This repo provides the pretrained baseline 960 hours wav2vec 2.0 model in MATLAB.
6
star
61

convmixer-patches-are-all-you-need

ConvMixer - Patches Are All You Need?
MATLAB
6
star
62

artistic-style-transfer

Artistic fast style transfer with a webcam
MATLAB
5
star
63

Biomass-Estimation-Starter-Code

5
star
64

speech-based-information-retrieval

Retrieve answers from a knowledge base via speech recognition and information retrieval.
MATLAB
5
star
65

Graph-Neural-Network-for-Heat-Transfer-Problem

5
star
66

Use-a-Python-Speech-Command-Recognition-System-to-MATLAB

Use a Python speech command recognition system in MATLAB
MATLAB
5
star
67

satellite-image-semantic-segmentation

Semantic Segmentation of Large Satellite Images with blockedImage Datastores
MATLAB
5
star
68

compare-gradient-attribution-maps

Sanity checks for comparing gradient attribution maps
MATLAB
4
star
69

Pretrained-RESA-Network-For-Road-Boundary-Detection

Pretrained RESA model for road boundary detection in MATLAB
MATLAB
3
star
70

Physics-Informed-Neural-Networks-for-Heat-Transfer

3
star
71

Pretrained-Yolov9-Network-For-Object-Detection

YOLO v9 inference in MATLAB for Object Detection with yolov9t, yolov9s, yolov9m, yolov9c and yolov9e networks
MATLAB
3
star
72

pretrained-dlCHOMP

Pretrained networks for Deep-Learning-Based Covariant Hamiltonian Optimization for Motion Planning (DLCHOMP) of robotic manipulators for MATLABยฎ
MATLAB
2
star
73

Animated-Adaptive-Linear-Neuron

Animating how Adaline classification works by minimizing cost. Showing comparison of three kinds of gradient descent.
MATLAB
2
star
74

object-detection-and-explainability-for-tensorflow-and-pytorch-models

MATLAB
2
star
75

Convert-librosa-Audio-Feature-Extraction-To-MATLAB

Convert librosa Audio Feature Extraction To MATLAB
MATLAB
2
star
76

physics-informed-neural-networks-with-matlab-live-coding-session

Solve mass spring damper system with phyics-informed neural networks in MATLAB
MATLAB
2
star