PGPortfolio: Policy Gradient Portfolio, the source code of "A Deep Reinforcement Learning Framework for the Financial Portfolio Management Problem"(https://arxiv.org/pdf/1706.10059.pdf).

Overview

This is the original implementation of our paper, A Deep Reinforcement Learning Framework for the Financial Portfolio Management Problem (arXiv:1706.10059), together with a toolkit of portfolio management research.

  • The deep reinforcement learning framework is the core part of the library. The method is basically the policy gradient on immediate reward. One can configurate the topology, training method or input data in a separate json file. The training process will be recorded and user can visualize the training using tensorboard. Result summary and parallel training are allowed for better hyper-parameters optimization.
  • The financial-model-based portfolio management algorithms are also embedded in this library for comparision purpose, whose implementation is based on Li and Hoi's toolkit OLPS.

Differences from the article version

Note that this library is a part of our main project, and it is several versions ahead of the article.

  • In this version, some technical bugs are fixed and improvements in hyper-parameter tuning and engineering are made.
    • The most important bug in the arxiv v2 article is that the test time-span mentioned is about 30% shorter than the actual experiment. Thus the volumn-observation interval (for asset selection) overlapped with the backtest data in the paper.
  • With new hyper-parameters, users can train the models with smaller time durations.(less than 30 mins)
  • All updates will be incorporated into future versions of the paper.
  • Original versioning history, and internal discussions, including some in-code comments, are removed in this open-sourced edition. These contains our unimplemented ideas, some of which will very likely become the foundations of our future publications

Platform Support

Python 3.5+ in windows and Python 2.7+/3.5+ in linux are supported.

Dependencies

Install Dependencies via pip install -r requirements.txt

  • tensorflow (>= 1.0.0)
  • tflearn
  • pandas
  • ...

User Guide

Please check out User Guide

Acknowledgement

This project would not have been finished without using the codes from the following open source projects:

Community Contribution

We welcome contributions from the community, including but not limited to:

  • Bug fixing
  • Interfacing to other markets such as stock, futures, options
  • Adding broker API (under marketdata)
  • More backtest strategies (under tdagent)

Risk Disclaimer (for Live-trading)

There is always risk of loss in trading. All trading strategies are used at your own risk

The volumes of many cryptocurrency markets are still low. Market impact and slippage may badly affect the results during live trading.

Donation

If you have made some profits because of this project or you just love reading our codes, please consider making a small donation to our ongoing projects via the following BTC or ETH address. All donations will be used as student stipends.

Comments
  • Question about reward function and `__pack_samples`

    Question about reward function and `__pack_samples`

    I'm having trouble reconciling what I read in the paper and what I read in the code.

    The reward function in a single period in the paper (Eq. (10)) is \log(\mu_t y_t \cdot w_{t-1}). But in the code, it seems that the reward is instead \log(mu_t y_{t+1} \cdot w_{t}). Am I correct?

    Because __pack_samples (in datamatrices.py) makes the price tensor X using M[..., :-1] and the relative price vector y using M[...,-1]/M[...,-2], so y is one period ahead of X.

    opened by ziofil 14
  • ValueError during training

    ValueError during training

    Running on Python 3.4.3, after I call python3 main.py --mode=train --processes=1, I get the following error:

    ValueError: the length of selected coins 0 is not equal to expected 11

    Perhaps this an issue with my version of Python?

    opened by jpa99 10
  • online training

    online training

    Hello

    Thanks for the wonderful work, i read your paper and almost studied most of the code. However, i don't get the concept of append_experience and agent train in the rolling_train method I have some questions if i may ask 1- what is the format of the saved experience and how does it affect the model ? 2- how is that different from training the model directly using self._agent.train() ? 3- is the experience mentioned here the same as the mini-batches mentioned in the paper for online learning section 5.3 for example ?

    thanks in advance Sarah Ahmed

    opened by zingomaster 8
  • working config

    working config

    Im trying reproduce result plotted in User Guide (10^2), but with default config getting much worse results. Which config was used in example? Thanks!

    opened by laci84 8
  • ConvLayer Filters

    ConvLayer Filters

    Figure 2 in Paper (Attached image): Shouldn't the convolutional filters be 3 dimensional? I mean, in the original convolution how do we go from 3 feature maps to 2 feature maps. I believe this would make sense if the filter was of dimension 2x1x3 (same as described but with additional depth of 2). And then the second convolution would be 2x48 to get the 20 11x1 feature maps.

    net_config.json: In ConvLayer, I don't understand how {"filter_shape":[1,2],"filter_number":3} corresponds to the filters outlined in the paper as described in my above question. (Excuse my ignorance of tflearn, but the params to conv2d() are not well explained in the documentation)

    image

    opened by LinuxIsCool 7
  • reversed_USDT vs BTC

    reversed_USDT vs BTC

    Hello,

    In the code, i don't understand what is the difference between reversed_USDT and the cash (BTC).

    I supposed (USDT_BTC) which is actually BTC/USD is a mapping to just holding some weight in BTC

    Am i wrong ?

    opened by AhmMontasser 7
  • Backtest trade by strategy, check fees vs coin value update

    Backtest trade by strategy, check fees vs coin value update

    In BackTest, "omega" seems to be the vector wT storing the recommended new portfolio distribution at each step, "_last_omega" the latest/previous portfolio screenhost wT-1. So the system assumes to be able to sell at each step all the current coins of the portfolio and buy all "omega" reco, or at least the delta between omega & last_omega. This strong hypothesis (slippage/liquidity) is in your paper but shouldn't it check at least whether any coin qty adjustment would not cost more transaction fees than the expected value adjustment ?

    opened by doxav 7
  • Poloniex API no longer accessible programmatically

    Poloniex API no longer accessible programmatically

    Looks like the Poloniex API is no longer accessible programmatically. I'll look into alternative APIs and will try to follow up with a pull request for this.

    opened by ielashi 7
  • updated Readme and User Guide

    updated Readme and User Guide

    Hey @ZhengyaoJiang I've updated the readme and user guide to reflect the current version of the library. Please have a look and let me know if I missed anything or if there are other things that need improvement.

    I mostly simplified the explanation and made it clearer where I thought there were ambiguities.

    opened by ghego 6
  • ForwardTest class

    ForwardTest class

    Hi, thank you for your excellent work, this is very interesting stuff.

    I am eager to test this on the live market, but having trouble moving from backtesting to forwardtesting. Any chance that an update with a ForwardTest class is on the way, or that you could advise on how to implement it? I understand it roughly, i.e. the generate_history_matrix( ) function needs to update the datamatrix with the newest market data (with "online" = True in the config file), and return that. And the trade_by_strategy( ) clearly needs a slight rewriting compared to BackTest as we don't know the future price. Any help on how to correctly return the newest market data would be appreciated.

    opened by einarbmag 6
  • Learning procedure

    Learning procedure

    Hello again!

    May I ask here for more details about learning procedure, because I'm not really in shape to understand all the code, may be with your guides here I'll go through it again with more success.

    1. During training phase how many times CNN learns on the same batch? Do you use epochs to learn or CNN passes through the data only once?
    2. During CV and Test phases rolling learning is used. On what data do CNN weights get updated? After all orders have been completed in current period we add price history into local DB. Do we select N periods before current period into learning batch? Or we update weights only using last price window?

    Sorry if it's newbie questions, I just want to understand how this magic works.

    opened by lytkarinskiy 6
  • KeyError: 'BTS_BTC'

    KeyError: 'BTS_BTC'

    Hi,

    I've tried several configurations of my anaconda environment, at first, I managed to make the python main.py --mode=download_data part work, but then I ran into the issues with the update of pandas mentioned in other issues. Trying to fix that I cannot come back to my initial progress even though I've made a new environment and forked the repo once again.

    The error I get is:

    Traceback (most recent call last): File "C:\Users\Alexander.S.Dahlberg\source\repos\PGPortfolio\main.py", line 132, in main() File "C:\Users\Alexander.S.Dahlberg\source\repos\PGPortfolio\main.py", line 71, in main DataMatrices(start=start, File "C:\Users\Alexander.S.Dahlberg\source\repos\PGPortfolio\pgportfolio\marketdata\datamatrices.py", line 44, in init self.__history_manager = gdm.HistoryManager(coin_number=coin_filter, end=self.__end, File "C:\Users\Alexander.S.Dahlberg\source\repos\PGPortfolio\pgportfolio\marketdata\globaldatamatrix.py", line 24, in init self._coin_list = CoinList(end, volume_average_days, volume_forward) File "C:\Users\Alexander.S.Dahlberg\source\repos\PGPortfolio\pgportfolio\marketdata\coinlist.py", line 35, in init prices.append(1.0 / float(ticker[k]['last'])) KeyError: 'BTS_BTC'

    I've no clue how to solve this. Have any others experienced the issue?

    Thanks

    opened by dalle244 4
  • How to run this agent

    How to run this agent

    Hi! i am trying to run your code on Visual Studio 2017, I have downloaded and installed all necessary libraries and dependencies. I attach the main.py file and run it and a console window opens, which I will attach below. I am not native to python so some step by step procedure would be extremely helpful.

    output
    opened by UmairKhalidKhan 0
  • Problem of dtype arguments

    Problem of dtype arguments

    Hello,

    When I run this code:

    python main.py --mode=train --processes=1

    I get this error: TypeError: init() got multiple values for argument 'dtype'

    I changed only the start and end times in the configuration file. Are there any recommendations?

    Here's the logfile:

    INFO:root:select coin online from 2021-10-12 00:00 to 2021-11-11 00:00 DEBUG:root:Selected coins are: ['reversed_USDT', 'reversed_USDC', 'ETH', 'LTC', 'XRP', 'SRM', 'DOGE', 'XMR', 'BCH', 'DOT', 'EOS'] INFO:root:fill SRM data from 2021-03-26 00:00 to 2021-06-24 11:59 INFO:root:fill SRM data from 2021-06-24 12:00 to 2021-09-22 23:59 INFO:root:fill SRM data from 2021-09-23 00:00 to 2021-12-01 00:00 INFO:root:fill DOT data from 2021-03-26 00:00 to 2021-06-24 11:59 INFO:root:fill DOT data from 2021-06-24 12:00 to 2021-09-22 23:59 INFO:root:fill DOT data from 2021-09-23 00:00 to 2021-12-01 00:00 INFO:root:fill EOS data from 2021-11-30 23:00 to 2021-12-01 00:00 INFO:root:feature type list is ['close', 'high', 'low'] DEBUG:root:buffer_bias is 0.000050 INFO:root:the number of training examples is 11008, of test examples is 929 DEBUG:root:the training set is from 0 to 11007 DEBUG:root:the test set is from 11040 to 12000

    Thanks.

    opened by duodenum96 0
  • Normalization on open price

    Normalization on open price

    when you already know I think normalization on open price is incorrect for this task. In real life, you can not buy on open price, when you already know high and low, from my point of view for real testing you should normalize for the close price (open for next candle) - if you do this - results will be significant worst. Have I made a mistake in my reasoning?

    opened by i7p9h9 1
  • Fix: train_summary.csv not generated

    Fix: train_summary.csv not generated

    Hello,

    I was not getting error in train phase however train_summary.csv not generated either. However, when i backtest i was getting error "train_summary.csv not found".

    I found the solution. The problem is related to indentation in tradertrainer.py(__log_result_csv method). At the end of the method replace the lines with indented ones as attached.

    That will produce the necessary csv file. train_summarycsvFIX

    opened by Busy2045 0
Releases(v1.0)
Owner
Zhengyao Jiang
PhD student at UCL, Interested in Deep Learning, Neuro-Symbolic Methods and Reinforcement learning
Zhengyao Jiang
This repo provides the official code for TransBTS: Multimodal Brain Tumor Segmentation Using Transformer (https://arxiv.org/pdf/2103.04430.pdf).

TransBTS: Multimodal Brain Tumor Segmentation Using Transformer This repo is the official implementation for TransBTS: Multimodal Brain Tumor Segmenta

Raymond 247 Dec 28, 2022
The official implementation of NeMo: Neural Mesh Models of Contrastive Features for Robust 3D Pose Estimation [ICLR-2021]. https://arxiv.org/pdf/2101.12378.pdf

NeMo: Neural Mesh Models of Contrastive Features for Robust 3D Pose Estimation [ICLR-2021] Release Notes The offical PyTorch implementation of NeMo, p

Angtian Wang 76 Nov 23, 2022
Pytorch implementation of Distributed Proximal Policy Optimization: https://arxiv.org/abs/1707.02286

Pytorch-DPPO Pytorch implementation of Distributed Proximal Policy Optimization: https://arxiv.org/abs/1707.02286 Using PPO with clip loss (from https

Alexis David Jacq 163 Dec 26, 2022
Source code for models described in the paper "AudioCLIP: Extending CLIP to Image, Text and Audio" (https://arxiv.org/abs/2106.13043)

AudioCLIP Extending CLIP to Image, Text and Audio This repository contains implementation of the models described in the paper arXiv:2106.13043. This

null 458 Jan 2, 2023
source code for https://arxiv.org/abs/2005.11248 "Accelerating Antimicrobial Discovery with Controllable Deep Generative Models and Molecular Dynamics"

Accelerating Antimicrobial Discovery with Controllable Deep Generative Models and Molecular Dynamics This work will be published in Nature Biomedical

International Business Machines 71 Nov 15, 2022
This repository contains the code used for Predicting Patient Outcomes with Graph Representation Learning (https://arxiv.org/abs/2101.03940).

Predicting Patient Outcomes with Graph Representation Learning This repository contains the code used for Predicting Patient Outcomes with Graph Repre

Emma Rocheteau 76 Dec 22, 2022
Supplementary code for the paper "Meta-Solver for Neural Ordinary Differential Equations" https://arxiv.org/abs/2103.08561

Meta-Solver for Neural Ordinary Differential Equations Towards robust neural ODEs using parametrized solvers. Main idea Each Runge-Kutta (RK) solver w

Julia Gusak 25 Aug 12, 2021
Code for paper "A Critical Assessment of State-of-the-Art in Entity Alignment" (https://arxiv.org/abs/2010.16314)

A Critical Assessment of State-of-the-Art in Entity Alignment This repository contains the source code for the paper A Critical Assessment of State-of

Max Berrendorf 16 Oct 14, 2022
Code for the paper: Learning Adversarially Robust Representations via Worst-Case Mutual Information Maximization (https://arxiv.org/abs/2002.11798)

Representation Robustness Evaluations Our implementation is based on code from MadryLab's robustness package and Devon Hjelm's Deep InfoMax. For all t

Sicheng 19 Dec 7, 2022
Official repository with code and data accompanying the NAACL 2021 paper "Hurdles to Progress in Long-form Question Answering" (https://arxiv.org/abs/2103.06332).

Hurdles to Progress in Long-form Question Answering This repository contains the official scripts and datasets accompanying our NAACL 2021 paper, "Hur

Kalpesh Krishna 41 Nov 8, 2022
Official implementation of the paper Image Generators with Conditionally-Independent Pixel Synthesis https://arxiv.org/abs/2011.13775

CIPS -- Official Pytorch Implementation of the paper Image Generators with Conditionally-Independent Pixel Synthesis Requirements pip install -r requi

Multimodal Lab @ Samsung AI Center Moscow 201 Dec 21, 2022
Pytorch implementation of Each Part Matters: Local Patterns Facilitate Cross-view Geo-localization https://arxiv.org/abs/2008.11646

[TCSVT] Each Part Matters: Local Patterns Facilitate Cross-view Geo-localization LPN [Paper] NEWs Prerequisites Python 3.6 GPU Memory >= 8G Numpy > 1.

null 46 Dec 14, 2022
https://arxiv.org/abs/2102.11005

LogME LogME: Practical Assessment of Pre-trained Models for Transfer Learning How to use Just feed the features f and labels y to the function, and yo

THUML: Machine Learning Group @ THSS 149 Dec 19, 2022
[PyTorch] Official implementation of CVPR2021 paper "PointDSC: Robust Point Cloud Registration using Deep Spatial Consistency". https://arxiv.org/abs/2103.05465

PointDSC repository PyTorch implementation of PointDSC for CVPR'2021 paper "PointDSC: Robust Point Cloud Registration using Deep Spatial Consistency",

null 153 Dec 14, 2022
Official Implementation for "ReStyle: A Residual-Based StyleGAN Encoder via Iterative Refinement" https://arxiv.org/abs/2104.02699

ReStyle: A Residual-Based StyleGAN Encoder via Iterative Refinement Recently, the power of unconditional image synthesis has significantly advanced th

null 967 Jan 4, 2023
This is an official implementation of our CVPR 2021 paper "Bottom-Up Human Pose Estimation Via Disentangled Keypoint Regression" (https://arxiv.org/abs/2104.02300)

Bottom-Up Human Pose Estimation Via Disentangled Keypoint Regression Introduction In this paper, we are interested in the bottom-up paradigm of estima

HRNet 367 Dec 27, 2022
ISTR: End-to-End Instance Segmentation with Transformers (https://arxiv.org/abs/2105.00637)

This is the project page for the paper: ISTR: End-to-End Instance Segmentation via Transformers, Jie Hu, Liujuan Cao, Yao Lu, ShengChuan Zhang, Yan Wa

Jie Hu 182 Dec 19, 2022
Non-Official Pytorch implementation of "Face Identity Disentanglement via Latent Space Mapping" https://arxiv.org/abs/2005.07728 Using StyleGAN2 instead of StyleGAN

Face Identity Disentanglement via Latent Space Mapping - Implement in pytorch with StyleGAN 2 Description Pytorch implementation of the paper Face Ide

Daniel Roich 58 Dec 24, 2022