This project is a loose implementation of paper "Algorithmic Financial Trading with Deep Convolutional Neural Networks: Time Series to Image Conversion Approach"

Overview

Stock Market Buy/Sell/Hold prediction Using convolutional Neural Network

This repo is an attempt to implement the research paper titled "Algorithmic Financial Trading with Deep Convolutional Neural Networks: Time Series to Image Conversion Approach" which can be found on the internet.

Reference: Sezer, Omer & Ozbayoglu, Murat. (2018). Algorithmic Financial Trading with Deep Convolutional Neural Networks: Time Series to Image Conversion Approach. Applied Soft Computing. 70. 10.1016/j.asoc.2018.04.024.

This paper was shared to me by someone and it immediately caught my attention. The paper in itself may not be the best one out there but the idea seemed quite intriguing. The idea is to calculate technical indicators for each day with varying window sizes, then convert each day's indicators to image and feed it to a Convolutional Neural Network to train. Labeling alogrithm used here is the same as the one used by the authors. One thing to be noted here is that this project is not an exact implementation of the paper. There were some portions where authors were not clear about implementation of certain things e.g. they had mentioned a technical indicator in the paper which only calculated for window size = 14 and not varying window sizes. Or may be it wasn't apparent to my peasant mind. Anyways, in such cases I have used my own judgement. For more details/explanation read my blog here.

Comments
  • "wr" and "money_flow_index" function not defined

    Hi!

    I am unable to use the utils.py file since the "wr" (line 258) and "money_flow_index" (line 271) functions are not defined anywhere.

    opened by mikkkeldp 3
  • Shuffling Data

    Shuffling Data

    When you're using time series analysis and technical indicators, you can't shuffle your data. Real time series data is not shuffled. Also, shuffling the data leaks historical data, as the technical indicators are calculated based on historical data. Your first indicator should have been your very high accuracy (i.e. if you could accurately predict 85%+ accuracy against the stock market, you'd be a rich man).

    This is a very similar issue with this research: https://www.reddit.com/r/algotrading/comments/cv83yh/overfitting

    opened by ScrapeWithYuri 3
  • Index Error when running the train.py

    Index Error when running the train.py

    running stock_cnn.py ['/content/stock_cnn_blog_pub/src/train.py', 'WMT', 'original'] ../stock_history/WMT ../outputs/fresh_rolling_train ../stock_history/WMT/WMT.csv 1 ) 03-11-2020 13_14_44 MainThread INFO\ Initialized logging at path ../outputs/fresh_rolling_train/logs/log_WMT_original_fresh_rolling_train_03-11-2020_13_14_44.log Tensorflow devices path to company data: ../stock_history/WMT/WMT.csv 2 ) 03-11-2020 13_14_44 MainThread DEBUG\ Data for WMT ready to use 3 ) 03-11-2020 13_14_44 MainThread DEBUG\ Technical indicators already calculated. Loading... 4 ) 03-11-2020 13_14_44 MainThread DEBUG\ Dropped 26 nan rows before label calculation 5 ) 03-11-2020 13_14_44 MainThread DEBUG\ creating label with original paper strategy Calculating labels 0% 0/5260 [00:00<?, ?it/s]

    IndexError Traceback (most recent call last) /content/stock_cnn_blog_pub/src/train.py in () 71 72 start_time = time.time() ---> 73 data_gen = DataGenerator(company_code, PATH_TO_COMPANY_DATA, OUTPUT_PATH, strategy_type, False, logger) 74 # exit here, since training is done with stock_keras.ipynb. 75 # comment sys.exit() if you want to try out rolling window training.

    2 frames /content/stock_cnn_blog_pub/src/data_generator.py in init(self, company_code, data_path, output_path, strategy_type, update, logger) 40 self.end_col = 'eom_26' 41 self.update = update ---> 42 self.download_stock_data() 43 self.df = self.create_features() 44 self.feat_idx = self.feature_selection()

    /content/stock_cnn_blog_pub/src/data_generator.py in create_features(self) 266 267 prev_len = len(df) --> 268 df.dropna(inplace=True) 269 df.reset_index(drop=True, inplace=True) 270 self.logger.append_log("Dropped {0} nan rows after label calculation".format(prev_len - len(df)))

    /content/stock_cnn_blog_pub/src/data_generator.py in create_labels(self, df, col_name, window_size) 142 if max_index == window_middle: 143 labels[window_middle] = 0 --> 144 elif min_index == window_middle: 145 labels[window_middle] = 1 146 else:

    IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices

    I have type casted the window_middle as int but still this error throws up no matter what I try to change.

    opened by akashsmu 1
  • What are the options for

    What are the options for "strategy_type"?

    Hey,

    Thanks so much for sharing your code by the way and all the effort!

    I am setting these options manually in the script. However, I have not figured out what are the options for strategy_type yet. Can you elaborate on this perhaps?

    in train.py, line 45: #company_code = args[1] #strategy_type = args[2] company_code = 'HPQ' strategy_type = ''

    thanks in advance, Alex

    opened by HypergeneticSpacekid 1
  • Differing results in article and ipynb

    Differing results in article and ipynb

    Hello!

    Thanks for you article and repo. I'm really interested in it! Could you explain something?

    At the and of your article https://towardsdatascience.com/stock-market-action-prediction-with-convnet-8689238feae3 you wrote results: https://miro.medium.com/max/403/1*YLKDhlcx6TtzIoVSdJ2xNw.png For example, for class 0: TP 49 FP 195.

    But, in https://www.kaggle.com/darkknight91/predicting-stock-buy-sell-signal-using-cnn/ in the end: [[ 53 0 11] [ 0 50 11] [ 38 53 784]] TP 53 and only 38 FP !!! It's fantastic result!

    I tried all params from your example and I can easily get first result with FP = 4*TP, but didn't get even close to TP =~ FP Val_loss is too big and f1_metric poor (( How did you manage to get second results? This results is really promising!

    Thank you!

    opened by via986 2
  • Early stopping conditioned on metric `val_loss` which is not available

    Early stopping conditioned on metric `val_loss` which is not available

    Hi,

    I am getting the following errors, when executing

    history = model.fit(x_train, y_train, epochs=params['epochs'], verbose=0,
                        batch_size=64, shuffle=True,
                        validation_data=(x_cv, y_cv),
                        callbacks=[es, mcp, rlp]
                        , sample_weight=sample_weights)
    

    returns:

    "WARNING:tensorflow:Early stopping conditioned on metric val_loss which is not available. Available metrics are: WARNING:tensorflow:Can save best model only with val_loss available, skipping. WARNING:tensorflow:Reduce LR on plateau conditioned on metric val_loss which is not available. Available metrics are: lr"

    Do you know why this might be happening?

    best wishes and thanks, Alex

    opened by HypergeneticSpacekid 2
  • I run into a index error when running stock_keras.ipynb first cell.

    I run into a index error when running stock_keras.ipynb first cell.

    When I run the first cell of the notebook stock_keras.ipynb, i got the following error. This is appearing after doing all the labels for every technical indicators except the IBR.

    Here is the context : running stock_cnn.py ['./train.py', 'WMT', 'original'] ../stock_history/WMT ../outputs/fresh_rolling_train ../stock_history/WMT/WMT.csv 1 ) 28-07-2020 16_40_55 MainThread INFO\ Initialized logging at path ../outputs/fresh_rolling_train/logs/log_WMT_original_fresh_rolling_train_28-07-2020_16_40_55.log Tensorflow devices path to company data: ../stock_history/WMT/WMT.csv 2 ) 28-07-2020 16_40_55 MainThread DEBUG\ Data for WMT ready to use 3 ) 28-07-2020 16_40_55 MainThread DEBUG\ Technical indicators already calculated. Loading... 4 ) 28-07-2020 16_40_55 MainThread DEBUG\ Dropped 26 nan rows before label calculation 5 ) 28-07-2020 16_40_55 MainThread DEBUG\ creating label with original paper strategy Calculating labels HBox(children=(IntProgress(value=0, max=5007), HTML(value='')))

    IndexError Traceback (most recent call last) ~/Downloads/stock_cnn_blog_pub-master/src/train.py in 71 72 start_time = time.time() ---> 73 data_gen = DataGenerator(company_code, PATH_TO_COMPANY_DATA, OUTPUT_PATH, strategy_type, False, logger) 74 # exit here, since training is done with stock_keras.ipynb. 75 # comment sys.exit() if you want to try out rolling window training.

    ~/Downloads/stock_cnn_blog_pub-master/src/data_generator.py in init(self, company_code, data_path, output_path, strategy_type, update, logger) 40 self.update = update 41 self.download_stock_data() ---> 42 self.df = self.create_features() 43 self.feat_idx = self.feature_selection() 44 self.one_hot_enc = OneHotEncoder(sparse=False, categories='auto')

    ~/Downloads/stock_cnn_blog_pub-master/src/data_generator.py in create_features(self) 266 short = self.strategy_type.split('')[0] 267 long = self.strategy_type.split('')[1] --> 268 df['labels'] = self.create_label_short_long_ma_crossover(df, 'close', short, long) 269 else: 270 df['labels'] = self.create_labels(df, 'close')

    ~/Downloads/stock_cnn_blog_pub-master/src/data_generator.py in create_labels(self, df, col_name, window_size) 142 143 labels[window_middle] = 1 --> 144 else: 145 146 labels[window_middle] = 2

    IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices

    opened by louis78100 1
Owner
Asutosh Nayak
Deep Learning | Android | Blogger
Asutosh Nayak
This project is the official implementation of our accepted ICLR 2021 paper BiPointNet: Binary Neural Network for Point Clouds.

BiPointNet: Binary Neural Network for Point Clouds Created by Haotong Qin, Zhongang Cai, Mingyuan Zhang, Yifu Ding, Haiyu Zhao, Shuai Yi, Xianglong Li

Haotong Qin 59 Dec 17, 2022
The project is an official implementation of our paper "3D Human Pose Estimation with Spatial and Temporal Transformers".

3D Human Pose Estimation with Spatial and Temporal Transformers This repo is the official implementation for 3D Human Pose Estimation with Spatial and

Ce Zheng 363 Dec 28, 2022
Implementation of experiments in the paper Clockwork Variational Autoencoders (project website) using JAX and Flax

Clockwork VAEs in JAX/Flax Implementation of experiments in the paper Clockwork Variational Autoencoders (project website) using JAX and Flax, ported

Julius Kunze 26 Oct 5, 2022
This is project is the implementation of the DeepShift: Towards Multiplication-Less Neural Networks paper

DeepShift This is project is the implementation of the DeepShift: Towards Multiplication-Less Neural Networks paper, that aims to replace multiplicati

Mostafa Elhoushi 88 Dec 23, 2022
This project is the PyTorch implementation of our CVPR 2022 paper:

Requirements and Dependency Install PyTorch with CUDA (for GPU). (Experiments are validated on python 3.8.11 and pytorch 1.7.0) (For visualization if

Lei Huang 23 Nov 29, 2022
The LaTeX and Python code for generating the paper, experiments' results and visualizations reported in each paper is available (whenever possible) in the paper's directory

This repository contains the software implementation of most algorithms used or developed in my research. The LaTeX and Python code for generating the

João Fonseca 3 Jan 3, 2023
Project Aquarium is a SUSE-sponsored open source project aiming at becoming an easy to use, rock solid storage appliance based on Ceph.

Project Aquarium Project Aquarium is a SUSE-sponsored open source project aiming at becoming an easy to use, rock solid storage appliance based on Cep

Aquarist Labs 73 Jul 21, 2022
This project uses reinforcement learning on stock market and agent tries to learn trading. The goal is to check if the agent can learn to read tape. The project is dedicated to hero in life great Jesse Livermore.

Reinforcement-trading This project uses Reinforcement learning on stock market and agent tries to learn trading. The goal is to check if the agent can

Deepender Singla 1.4k Dec 22, 2022
It's final year project of Diploma Engineering. This project is based on Computer Vision.

Face-Recognition-Based-Attendance-System It's final year project of Diploma Engineering. This project is based on Computer Vision. Brief idea about ou

Neel 10 Nov 2, 2022
Erpnext app for make employee salary on payroll entry based on one or more project with percentage for all project equal 100 %

Project Payroll this app for make payroll for employee based on projects like project on 30 % and project 2 70 % as account dimension it makes genral

Ibrahim Morghim 8 Jan 2, 2023
BC3407-Group-5-Project - BC3407 Group Project With Python

BC3407-Group-5-Project As the world struggles to contain the ever-changing varia

null 1 Jan 26, 2022
UpChecker is a simple opensource project to host it fast on your server and check is server up, view statistic, get messages if it is down. UpChecker - just run file and use project easy

UpChecker UpChecker is a simple opensource project to host it fast on your server and check is server up, view statistic, get messages if it is down.

Yan 4 Apr 7, 2022
Official project website for the CVPR 2021 paper "Exploring intermediate representation for monocular vehicle pose estimation"

EgoNet Official project website for the CVPR 2021 paper "Exploring intermediate representation for monocular vehicle pose estimation". This repo inclu

Shichao Li 138 Dec 9, 2022
Project page for the paper Semi-Supervised Raw-to-Raw Mapping 2021.

Project page for the paper Semi-Supervised Raw-to-Raw Mapping 2021.

Mahmoud Afifi 22 Nov 8, 2022
Project page of the paper 'Analyzing Perception-Distortion Tradeoff using Enhanced Perceptual Super-resolution Network' (ECCVW 2018)

EPSR (Enhanced Perceptual Super-resolution Network) paper This repo provides the test code, pretrained models, and results on benchmark datasets of ou

Subeesh Vasu 78 Nov 19, 2022
Database Reasoning Over Text project for ACL paper

Database Reasoning over Text This repository contains the code for the Database Reasoning Over Text paper, to appear at ACL2021. Work is performed in

Facebook Research 320 Dec 12, 2022
This project is a re-implementation of MASTER: Multi-Aspect Non-local Network for Scene Text Recognition by MMOCR

This project is a re-implementation of MASTER: Multi-Aspect Non-local Network for Scene Text Recognition by MMOCR,which is an open-source toolbox based on PyTorch. The overall architecture will be shown below.

Jianquan Ye 82 Nov 17, 2022
PyTorch Implementation of Realtime Multi-Person Pose Estimation project.

PyTorch Realtime Multi-Person Pose Estimation This is a pytorch version of Realtime_Multi-Person_Pose_Estimation, origin code is here Realtime_Multi-P

Dave Fang 157 Nov 12, 2022