Skip to main content

Logo

Documentation Software tests Coverage

python License

Introduction

Backtest trading strategies or train reinforcement learning agents with tradingenv, an event-driven market simulator that implements the OpenAI/gym protocol.

Installation

tradingenv supports Python 3.9 or newer versions. The following command line will install the latest software version.

pip install tradingenv

Notebooks, software tests and building the documentation require extra dependencies that can be installed with

pip install tradingenv[extra]

Examples

Reinforcement Learning

The package is built upon the industry-standard gym and therefore can be used in conjunction with popular reinforcement learning frameworks including rllib, stable-baselines3 and ElegantRL.

from tradingenv.env import TradingEnvXY
import yfinance

# Load data from Yahoo Finance.
tickers = yfinance.Tickers(['SPY', 'TLT', 'TBIL', '^IRX'])
data = tickers.history(period="12mo", progress=False)['Close'].tz_localize(None)
Y = data[['SPY', 'TLT']]
X = Y.rolling(12).mean() - Y.rolling(26).mean()

# Instance the trading environment.
env = TradingEnvXY(
    X=X,                      # Use moving averages crossover as features
    Y=Y,                      # to trade SPY and TLT ETFs.
    transformer='z-score',    # Features are standardised to N(0, 1).
    reward='logret',          # Reward is the log return of the portfolio at each step,
    cash=1000000,             # starting with $1M.
    spread=0.0002,            # Transaction costs include a 0.02% spread,
    markup=0.005,             # a 0.5% broker markup on deposit rate,
    fee=0.0002,               # a 0.02% dealing fee of traded notional
    fixed=1,                  # and a $1 fixed fee per trade.
    margin=0.02,              # Do not trade if trade size is smaller than 2% of the portfolio.
    rate=data['^IRX'] / 100,  # Rate used to compute the yield on idle cash and cost of leverage.
    latency=0,                # Trades are implemented with no latency
    steps_delay=1,            # but a delay of one day.
    window=1,                 # The observation is the current state of the market,
    clip=5.,                  # clipped between -5 and +5 standard deviations.
    max_long=1.5,             # The maximum long position is 150% of the portfolio,
    max_short=-1.,            # the maximum short position is 100% of the portfolio.
    calendar='NYSE',          # Use the NYSE calendar to schedule trading days.
)

# OpenAI/gym protocol. Run an episode in the environment.
obs = env.reset()
done = False
while not done:
    action = env.action_space.sample()
    obs, reward, done, info = env.step(action)

Backtesting

Thanks to the event-driven design, tradingenv is agnostic with respect to the type and time-frequency of the events. This means that you can run simulations either using irregularly sampled trade and quotes data, daily closing prices, monthly economic data or alternative data. Financial instruments supported include stocks, ETF and futures.

from tradingenv.policy import AbstractPolicy


class Portfolio6040(AbstractPolicy):
    """Implement logic of your investment strategy or RL agent here."""

    def act(self, state):
        """Invest 60% of the portfolio in SPY ETF and 40% in TLT ETF."""
        return [0.6, 0.4]

# Run the backtest.
track_record = env.backtest(
    policy=Portfolio6040(),
    risk_free=data['TBIL'],
    benchmark=data['SPY'],
)

# The track_record object stores the results of your backtest.
track_record.tearsheet()

track_record.fig_net_liquidation_value()

Relevant projects

  • btgym: is an OpenAI Gym-compatible environment for
  • backtrader backtesting/trading library, designed to provide gym-integrated framework for running reinforcement learning experiments in [close to] real world algorithmic trading environments.
  • gym: A toolkit for developing and comparing reinforcement learning algorithms.
  • qlib: Qlib provides a strong infrastructure to support quant research.
  • rllib: open-source library for reinforcement learning.
  • stable-baselines3: is a set of reliable implementations of reinforcement learning algorithms in PyTorch.

Developers

You are welcome to contribute features, examples and documentation or issues.

You can run the software tests typing pytest in the command line, assuming that the folder \tests is in the current working directory.

To refresh and build the documentation:

pytest tests/notebooks
sphinx-apidoc -f -o docs/source tradingenv
cd docs
make clean
make html

Release files for tradingenv 0.1.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for tradingenv 0.1.3
File Size Uploaded
tradingenv-0.1.3.tar.gz 118.7 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for tradingenv 0.1.3
File Interpreter ABI Platform
tradingenv-0.1.3-py3-none-any.whl Python 3 none any Details

Total release size: 252.0 kB

Release files / tradingenv-0.1.3.tar.gz

Download URL tradingenv-0.1.3.tar.gz
Size 118.7 kB
Tags Source
SHA-256 checksum
How to use checksums
0fe7d42e3631fb56d712bb4812043034f85faf9cbb6012bf7fff85ddba18c2fd
BLAKE2b-256 checksum
How to use checksums
30c65d01dd621ad37f03c2eb4f76482cfe54725c96297a986cd43c220a46ed4d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.12.3

Release files / tradingenv-0.1.3-py3-none-any.whl

Download URL tradingenv-0.1.3-py3-none-any.whl
Size 133.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c8a5d4ede0686039026233b7e8af2570de605f83875a93ee8693580b329f6df8
BLAKE2b-256 checksum
How to use checksums
509cee86a53e1f3aca21d2869e398ee5bc39ee4e0c0031c95e2decb0d634cc34
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.12.3

Release history Release notifications | RSS feed

This release

0.1.3 This release

2 release files

0.1.2

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page