



  

TensorTrade 1.0.3 documentation

[![Logo](_static/logo.jpg)](index.html#document-index)

 stable

 

* [Home](index.html#document-index)

Overview

* [Getting Started](index.html#document-overview/getting_started)

* [Installation](index.html#installation)

* [Docker](index.html#docker)

Examples

* [Code Structure](index.html#document-examples/overview)

* [Setup Environment](index.html#document-examples/setup_environment_tutorial)

* [Train and Evaluate](index.html#document-examples/train_and_evaluate)

* [Renderers and Plotly Chart](index.html#document-examples/renderers_and_plotly_chart)

* [Stochastic Data](index.html#document-examples/use_stochastic_data)

* [Ledger Example](index.html#document-examples/ledger_example)

Tutorials

* [Using Ray with TensorTrade](index.html#document-tutorials/ray)

Components

* [Components](index.html#document-components/components)

* [Action Scheme](index.html#document-components/action_scheme)

* [Reward Scheme](index.html#document-components/reward_scheme)

* [Observer](index.html#document-components/observer)

* [Default](index.html#default)

* [IntradayObserver](index.html#intradayobserver)

* [Stopper](index.html#document-components/stopper)

* [Informer](index.html#document-components/informer)

* [Renderer](index.html#document-components/renderer)

Environments

* [Overview](index.html#document-envs/overview)

* [What if I can’t make a particular environment?](index.html#what-if-i-can-t-make-a-particular-environment)

Feed

* [Overview](index.html#document-feed/overview)

* [What is a `Stream`?](index.html#what-is-a-stream)

* [Using Data Types](index.html#using-data-types)

* [Advanced Usages](index.html#advanced-usages)

Order Management System

* [Overview](index.html#document-oms/overview)

* [Portfolio](index.html#portfolio)

* [Orders](index.html#orders)

Agents

* [Overview](index.html#document-agents/overview)

* [Ray](index.html#ray)

* [Stable Baselines](index.html#stable-baselines)

* [Tensorforce](index.html#tensorforce)

API reference

* [API reference](index.html#document-api/modules)

[TensorTrade](index.html#document-index)

* [Docs](index.html#document-index) »

* TensorTrade 1.0.3 documentation

* [Edit on GitHub](https://github.com/notadamking/tensortrade/blob/70a01d1b6ba0717df58917d1cc435e6487be530e/docs/source/index.rst)

---

/\* CSS overrides for sphinx\_rtd\_theme \*/

/\* 24px margin \*/

.nbinput.nblast.container,

.nboutput.nblast.container {

 margin-bottom: 19px; /\* padding has already 5px \*/

}

/\* ... except between code cells! \*/

.nblast.container + .nbinput.container {

 margin-top: -19px;

}

.admonition > p:before {

 margin-right: 4px; /\* make room for the exclamation icon \*/

}

/\* Fix math alignment, see https://github.com/rtfd/sphinx\_rtd\_theme/pull/686 \*/

.math {

 text-align: unset;

}

TensorTrade[¶](#tensortrade "Permalink to this headline")

=========================================================

![Logo](_images/logo.jpg)

[TensorTrade](https://github.com/notadamking/tensortrade) is an open source Python framework for building,

training, evaluating, and deploying robust trading algorithms using

reinforcement learning. The framework focuses on being highly composable

and extensible, to allow the system to scale from simple trading

strategies on a single CPU, to complex investment strategies run on a

distribution of HPC machines.

Under the hood, the framework uses many of the APIs from existing

machine learning libraries to maintain high quality data pipelines and

learning models. One of the main goals of TensorTrade is to enable fast

experimentation with algorithmic trading strategies, by leveraging the

existing tools and pipelines provided by `numpy`, `pandas`, `gym`,

`keras`, and `tensorflow`.

Every piece of the framework is split up into re-usable components,

allowing you to take advantage of the general use components built by

the community, while keeping your proprietary features private. The aim

is to simplify the process of testing and deploying robust trading

agents using deep reinforcement learning, to allow you and I to focus on

creating profitable strategies.

*The goal of this framework is to enable fast experimentation, while

maintaining production-quality data pipelines.*

Feel free to also walk through the [Medium tutorial](https://medium.com/@notadamking/trade-smarter-w-reinforcement-learning-a5e91163f315).

Guiding principles[¶](#guiding-principles "Permalink to this headline")

=======================================================================

*Inspired by* [Keras’ guiding principles](https://github.com/keras-team/keras).

*User friendliness.* TensorTrade is an API designed for human beings,

not machines. It puts user experience front and center. TensorTrade

follows best practices for reducing cognitive load: it offers consistent

& simple APIs, it minimizes the number of user actions required for

common use cases, and it provides clear and actionable feedback upon

user error.

*Modularity.* A trading environment is a conglomeration of fully

configurable modules that can be plugged together with as few

restrictions as possible. In particular, exchanges, feature pipelines,

action schemes, reward schemes, trading agents, and performance reports

are all standalone modules that you can combine to create new trading

environments.

*Easy extensibility.* New modules are simple to add (as new classes and

functions), and existing modules provide ample examples. To be able to

easily create new modules allows for total expressiveness, making

TensorTrade suitable for advanced research and production use.

Getting Started[¶](#getting-started "Permalink to this headline")

-----------------------------------------------------------------

You can get started testing on Google Colab or your local machine, by viewing our [many examples](https://github.com/tensortrade-org/tensortrade/tree/master/examples)

---

Installation[¶](#installation "Permalink to this headline")

-----------------------------------------------------------

TensorTrade requires Python >= 3.6 for all functionality to work as expected.

You can install the package from PyPi via pip or from the Github repo.

```

pip install tensortrade

```

OR

```

pip install git+https://github.com/tensortrade-org/tensortrade.git

```

Some functionality included in TensorTrade is optional. To install all optional dependencies, run the following command:

```

pip install tensortrade[tf,tensorforce,baselines,ccxt,fbm]

```

OR

```

pip install git+https://github.com/tensortrade-org/tensortrade.git[tf,tensorforce,baselines,ccxt,fbm]

```

Docker[¶](#docker "Permalink to this headline")

-----------------------------------------------

To run the commands below ensure Docker is installed. Visit https://docs.docker.com/install/ for more information

### Run Jupyter Notebooks[¶](#run-jupyter-notebooks "Permalink to this headline")

To run a jupyter notebook execute the following

```

make run-notebook

```

which will generate a link of the form 127.0.0.1:8888/?token=… Paste this link into your browsers and select the notebook you’d like to explore

### Build Documentation[¶](#build-documentation "Permalink to this headline")

To build documentation execute the following

```

make run-docs

```

### Run Test Suite[¶](#run-test-suite "Permalink to this headline")

To run the test suite execute the following

```

make run-tests

```

Code Structure[¶](#code-structure "Permalink to this headline")

---------------------------------------------------------------

The TensorTrade library is modular. The `tensortrade` library usually has a

common setup when using components. If you wish to make a particular class a

component all you need to do is subclass `Component`.

```

class Example(Component):

    """An example component to show how to subclass."""

    def foo(self, arg1, arg2) -> str:

        """A method to return a string."""

        raise NotImplementedError()

    def bar(self, arg1, arg2, \*\*kwargs) -> int:

        """A method to return an integer."""

```

From this abstract base class, more concrete and custom subclasses can be made

that provide the implementation of these methods.

  

**Example of Structure**  

A good example of this structure is the `RewardScheme` component. This component

controls the reward mechanism of a `TradingEnv`.

The beginning of the code in [RewardScheme](https://github.com/tensortrade-org/tensortrade/blob/master/tensortrade/env/generic/components/reward_scheme.py) is seen here.

```

from abc import abstractmethod

from tensortrade.core.component import Component

from tensortrade.core.base import TimeIndexed

class RewardScheme(Component, TimeIndexed):

    """A component to compute the reward at each step of an episode."""

    registered\_name = "rewards"

    @abstractmethod

    def reward(self, env: 'TradingEnv') -> float:

        """Computes the reward for the current step of an episode.

 Parameters

 ----------

 env : `TradingEnv`

 The trading environment

 Returns

 -------

 float

 The computed reward.

 """

        raise NotImplementedError()

    def reset(self) -> None:

        """Resets the reward scheme."""

        pass

```

As you can see above, the [RewardScheme](https://github.com/tensortrade-org/tensortrade/blob/master/tensortrade/env/generic/components/reward_scheme.py) has a majority of the

structural and mechanical details that guide all other representations of that

type of class. When creating a new reward scheme, one needs to add further

details for how information from then environment gets converted into a reward.

Setup Environment[¶](#setup-environment "Permalink to this headline")

---------------------------------------------------------------------

```

import ta

import pandas as pd

import tensortrade.env.default as default

from tensortrade.data.cdd import CryptoDataDownload

from tensortrade.feed.core import Stream, DataFeed, NameSpace

from tensortrade.oms.instruments import USD, BTC, ETH, LTC

from tensortrade.oms.wallets import Wallet, Portfolio

from tensortrade.oms.exchanges import Exchange

from tensortrade.oms.services.execution.simulated import execute\_order

```

  

**Fetch Historical Data**  

```

cdd = CryptoDataDownload()

bitfinex\_data = pd.concat([

    cdd.fetch("Bitfinex", "USD", "BTC", "1h").add\_prefix("BTC:"),

    cdd.fetch("Bitfinex", "USD", "ETH", "1h").add\_prefix("ETH:")

], axis=1)

bitstamp\_data = pd.concat([

    cdd.fetch("Bitstamp", "USD", "BTC", "1h").add\_prefix("BTC:"),

    cdd.fetch("Bitstamp", "USD", "LTC", "1h").add\_prefix("LTC:")

], axis=1)

```

  

**Define Exchanges**  

An exchange needs a name, an execution service, and streams of price data in order to function properly.

The setups supported right now are the simulated execution service using simulated or stochastic data. More execution services will be made available in the future, as well as price streams so that live data and execution can be supported.

```

bitfinex = Exchange("bitfinex", service=execute\_order)(

    Stream.source(list(bitfinex\_data['BTC:close']), dtype="float").rename("USD-BTC"),

    Stream.source(list(bitfinex\_data['ETH:close']), dtype="float").rename("USD-ETH")

)

bitstamp = Exchange("bitstamp", service=execute\_order)(

    Stream.source(list(bitstamp\_data['BTC:close']), dtype="float").rename("USD-BTC"),

    Stream.source(list(bitstamp\_data['LTC:close']), dtype="float").rename("USD-LTC")

)

```

Now that the exchanges have been defined we can define our features that we would like to include, excluding the prices we have provided for the exchanges.

  

**Define External Data Feed**  

Here we will define the feed to use whatever data you would like. From financial indicators to alternative datasets, they will all have to be defined and incorporated into the `DataFeed` provided to the environment.

```

# Add all features for bitstamp BTC & ETH

bitfinex\_btc = bitfinex\_data.loc[:, [name.startswith("BTC") for name in bitfinex\_data.columns]]

bitfinex\_eth = bitfinex\_data.loc[:, [name.startswith("ETH") for name in bitfinex\_data.columns]]

ta.add\_all\_ta\_features(

    bitfinex\_btc,

    colprefix="BTC:",

    \*\*{k: "BTC:" + k for k in ['open', 'high', 'low', 'close', 'volume']}

)

with NameSpace("bitfinex"):

    bitfinex\_streams = [

        Stream.source(list(bitfinex\_btc[c]), dtype="float").rename(c) for c in bitfinex\_btc.columns

    ]

    bitfinex\_streams += [

        Stream.source(list(bitfinex\_eth[c]), dtype="float").rename(c) for c in bitfinex\_eth.columns

    ]

# Add all features for bitstamp BTC & LTC

bitstamp\_btc = bitstamp\_data.loc[:, [name.startswith("BTC") for name in bitstamp\_data.columns]]  

bitstamp\_ltc = bitstamp\_data.loc[:, [name.startswith("LTC") for name in bitstamp\_data.columns]]

ta.add\_all\_ta\_features(

    bitstamp\_ltc,

    colprefix="LTC:",

    \*\*{k: "LTC:" + k for k in ['open', 'high', 'low', 'close', 'volume']}

)

with NameSpace("bitstamp"):

    bitstamp\_streams = [

        Stream.source(list(bitstamp\_btc[c]), dtype="float").rename(c) for c in bitstamp\_btc.columns

    ]

    bitstamp\_streams += [

        Stream.source(list(bitstamp\_ltc[c]), dtype="float").rename(c) for c in bitstamp\_ltc.columns

    ]

feed = DataFeed(bitfinex\_streams + bitstamp\_streams)

```

```

feed.next()

```

```

{'bitfinex:/BTC:date': Timestamp('2017-07-01 11:00:00'),

 'bitfinex:/BTC:open': 2505.56,

 'bitfinex:/BTC:high': 2513.38,

 'bitfinex:/BTC:low': 2495.12,

 'bitfinex:/BTC:close': 2509.17,

 'bitfinex:/BTC:volume': 287000.32,

 'bitfinex:/BTC:volume\_adi': 462887.3781183644,

 'bitfinex:/BTC:volume\_obv': nan,

 'bitfinex:/BTC:volume\_cmf': 0.5388828039430464,

 'bitfinex:/BTC:volume\_fi': nan,

 'bitfinex:/BTC:volume\_em': nan,

 'bitfinex:/BTC:volume\_vpt': -190920.02711825827,

 'bitfinex:/BTC:volume\_nvi': 1000.0,

 'bitfinex:/BTC:volatility\_atr': 85.51648155760596,

 'bitfinex:/BTC:volatility\_bbh': 2509.17,

 'bitfinex:/BTC:volatility\_bbl': 2509.17,

 'bitfinex:/BTC:volatility\_bbm': 2509.17,

 'bitfinex:/BTC:volatility\_bbhi': 0.0,

 'bitfinex:/BTC:volatility\_bbli': 0.0,

 'bitfinex:/BTC:volatility\_kcc': 2505.89,

 'bitfinex:/BTC:volatility\_kch': 2524.15,

 'bitfinex:/BTC:volatility\_kcl': 2487.6299999999997,

 'bitfinex:/BTC:volatility\_kchi': 0.0,

 'bitfinex:/BTC:volatility\_kcli': 0.0,

 'bitfinex:/BTC:volatility\_dch': 2509.17,

 'bitfinex:/BTC:volatility\_dcl': 2509.17,

 'bitfinex:/BTC:volatility\_dchi': 0.0,

 'bitfinex:/BTC:volatility\_dcli': 0.0,

 'bitfinex:/BTC:trend\_macd': nan,

 'bitfinex:/BTC:trend\_macd\_signal': nan,

 'bitfinex:/BTC:trend\_macd\_diff': nan,

 'bitfinex:/BTC:trend\_ema\_fast': nan,

 'bitfinex:/BTC:trend\_ema\_slow': nan,

 'bitfinex:/BTC:trend\_adx': 0.0,

 'bitfinex:/BTC:trend\_adx\_pos': 0.0,

 'bitfinex:/BTC:trend\_adx\_neg': 0.0,

 'bitfinex:/BTC:trend\_vortex\_ind\_pos': nan,

 'bitfinex:/BTC:trend\_vortex\_ind\_neg': nan,

 'bitfinex:/BTC:trend\_vortex\_diff': nan,

 'bitfinex:/BTC:trend\_trix': nan,

 'bitfinex:/BTC:trend\_mass\_index': 0.0,

 'bitfinex:/BTC:trend\_cci': nan,

 'bitfinex:/BTC:trend\_dpo': 4963.073762705523,

 'bitfinex:/BTC:trend\_kst': -664.2012654186367,

 'bitfinex:/BTC:trend\_kst\_sig': -664.2012654186367,

 'bitfinex:/BTC:trend\_kst\_diff': 0.0,

 'bitfinex:/BTC:trend\_ichimoku\_a': 2504.25,

 'bitfinex:/BTC:trend\_ichimoku\_b': 2504.25,

 'bitfinex:/BTC:trend\_visual\_ichimoku\_a': 7460.129960014917,

 'bitfinex:/BTC:trend\_visual\_ichimoku\_b': 7449.72498449202,

 'bitfinex:/BTC:trend\_aroon\_up': 4.0,

 'bitfinex:/BTC:trend\_aroon\_down': 4.0,

 'bitfinex:/BTC:trend\_aroon\_ind': 0.0,

 'bitfinex:/BTC:momentum\_rsi': nan,

 'bitfinex:/BTC:momentum\_mfi': nan,

 'bitfinex:/BTC:momentum\_tsi': -100.0,

 'bitfinex:/BTC:momentum\_uo': 0.2822915537138003,

 'bitfinex:/BTC:momentum\_stoch': 76.94414019715232,

 'bitfinex:/BTC:momentum\_stoch\_signal': 76.94414019715232,

 'bitfinex:/BTC:momentum\_wr': -23.055859802847678,

 'bitfinex:/BTC:momentum\_ao': 0.0,

 'bitfinex:/BTC:momentum\_kama': nan,

 'bitfinex:/BTC:others\_dr': -66.42012654186367,

 'bitfinex:/BTC:others\_dlr': nan,

 'bitfinex:/BTC:others\_cr': 0.0,

 'bitfinex:/ETH:date': Timestamp('2017-07-01 11:00:00'),

 'bitfinex:/ETH:open': 279.98,

 'bitfinex:/ETH:high': 279.99,

 'bitfinex:/ETH:low': 272.1,

 'bitfinex:/ETH:close': 275.01,

 'bitfinex:/ETH:volume': 679358.87,

 'bitstamp:/BTC:date': Timestamp('2017-07-01 11:00:00'),

 'bitstamp:/BTC:open': 2506.5,

 'bitstamp:/BTC:high': 2510.62,

 'bitstamp:/BTC:low': 2495.5,

 'bitstamp:/BTC:close': 2500.0,

 'bitstamp:/BTC:volume': 521903.7,

 'bitstamp:/LTC:date': Timestamp('2017-07-01 11:00:00'),

 'bitstamp:/LTC:open': 39.67,

 'bitstamp:/LTC:high': 39.67,

 'bitstamp:/LTC:low': 39.32,

 'bitstamp:/LTC:close': 39.45,

 'bitstamp:/LTC:volume': 1957.48,

 'bitstamp:/LTC:volume\_adi': 5133.608444728016,

 'bitstamp:/LTC:volume\_obv': nan,

 'bitstamp:/LTC:volume\_cmf': -0.2571428571428455,

 'bitstamp:/LTC:volume\_fi': nan,

 'bitstamp:/LTC:volume\_em': nan,

 'bitstamp:/LTC:volume\_vpt': -895.4321955984681,

 'bitstamp:/LTC:volume\_nvi': 1000.0,

 'bitstamp:/LTC:volatility\_atr': 1.4838450097847482,

 'bitstamp:/LTC:volatility\_bbh': 39.45,

 'bitstamp:/LTC:volatility\_bbl': 39.45,

 'bitstamp:/LTC:volatility\_bbm': 39.45,

 'bitstamp:/LTC:volatility\_bbhi': 0.0,

 'bitstamp:/LTC:volatility\_bbli': 0.0,

 'bitstamp:/LTC:volatility\_kcc': 39.480000000000004,

 'bitstamp:/LTC:volatility\_kch': 39.830000000000005,

 'bitstamp:/LTC:volatility\_kcl': 39.13,

 'bitstamp:/LTC:volatility\_kchi': 0.0,

 'bitstamp:/LTC:volatility\_kcli': 0.0,

 'bitstamp:/LTC:volatility\_dch': 39.45,

 'bitstamp:/LTC:volatility\_dcl': 39.45,

 'bitstamp:/LTC:volatility\_dchi': 0.0,

 'bitstamp:/LTC:volatility\_dcli': 0.0,

 'bitstamp:/LTC:trend\_macd': nan,

 'bitstamp:/LTC:trend\_macd\_signal': nan,

 'bitstamp:/LTC:trend\_macd\_diff': nan,

 'bitstamp:/LTC:trend\_ema\_fast': nan,

 'bitstamp:/LTC:trend\_ema\_slow': nan,

 'bitstamp:/LTC:trend\_adx': 0.0,

 'bitstamp:/LTC:trend\_adx\_pos': 0.0,

 'bitstamp:/LTC:trend\_adx\_neg': 0.0,

 'bitstamp:/LTC:trend\_vortex\_ind\_pos': nan,

 'bitstamp:/LTC:trend\_vortex\_ind\_neg': nan,

 'bitstamp:/LTC:trend\_vortex\_diff': nan,

 'bitstamp:/LTC:trend\_trix': nan,

 'bitstamp:/LTC:trend\_mass\_index': 0.0,

 'bitstamp:/LTC:trend\_cci': nan,

 'bitstamp:/LTC:trend\_dpo': 41.511479785526944,

 'bitstamp:/LTC:trend\_kst': -512.7312383060929,

 'bitstamp:/LTC:trend\_kst\_sig': -512.7312383060929,

 'bitstamp:/LTC:trend\_kst\_diff': 0.0,

 'bitstamp:/LTC:trend\_ichimoku\_a': 39.495000000000005,

 'bitstamp:/LTC:trend\_ichimoku\_b': 39.495000000000005,

 'bitstamp:/LTC:trend\_visual\_ichimoku\_a': 80.84515204884308,

 'bitstamp:/LTC:trend\_visual\_ichimoku\_b': 80.77039939728148,

 'bitstamp:/LTC:trend\_aroon\_up': 4.0,

 'bitstamp:/LTC:trend\_aroon\_down': 4.0,

 'bitstamp:/LTC:trend\_aroon\_ind': 0.0,

 'bitstamp:/LTC:momentum\_rsi': nan,

 'bitstamp:/LTC:momentum\_mfi': nan,

 'bitstamp:/LTC:momentum\_tsi': -100.0,

 'bitstamp:/LTC:momentum\_uo': 0.31218871344045224,

 'bitstamp:/LTC:momentum\_stoch': 37.14285714285772,

 'bitstamp:/LTC:momentum\_stoch\_signal': 37.14285714285772,

 'bitstamp:/LTC:momentum\_wr': -62.85714285714228,

 'bitstamp:/LTC:momentum\_ao': 0.0,

 'bitstamp:/LTC:momentum\_kama': nan,

 'bitstamp:/LTC:others\_dr': -51.27312383060929,

 'bitstamp:/LTC:others\_dlr': nan,

 'bitstamp:/LTC:others\_cr': 0.0}

```

  

**Portfolio**  

Make the portfolio using the any combinations of exchanges and intruments that the exchange supports

```

portfolio = Portfolio(USD, [

    Wallet(bitfinex, 10000 \* USD),

    Wallet(bitfinex, 10 \* BTC),

    Wallet(bitfinex, 5 \* ETH),

    Wallet(bitstamp, 1000 \* USD),

    Wallet(bitstamp, 5 \* BTC),

    Wallet(bitstamp, 3 \* LTC),

])

```

  

**Environment**  

```

env = default.create(

    portfolio=portfolio,

    action\_scheme="managed-risk",

    reward\_scheme="simple",

    feed=feed,

    window\_size=15,

    enable\_logger=False

)

```

```

env.observer.feed.next()

```

```

{'internal': {'bitfinex:/USD-BTC': 2509.17,

  'bitfinex:/USD-ETH': 275.01,

  'bitfinex:/USD:/free': 10000.0,

  'bitfinex:/USD:/locked': 0.0,

  'bitfinex:/USD:/total': 10000.0,

  'bitfinex:/BTC:/free': 10.0,

  'bitfinex:/BTC:/locked': 0.0,

  'bitfinex:/BTC:/total': 10.0,

  'bitfinex:/BTC:/worth': 25091.7,

  'bitfinex:/ETH:/free': 5.0,

  'bitfinex:/ETH:/locked': 0.0,

  'bitfinex:/ETH:/total': 5.0,

  'bitfinex:/ETH:/worth': 1375.05,

  'bitstamp:/USD-BTC': 2500.0,

  'bitstamp:/USD-LTC': 39.45,

  'bitstamp:/USD:/free': 1000.0,

  'bitstamp:/USD:/locked': 0.0,

  'bitstamp:/USD:/total': 1000.0,

  'bitstamp:/BTC:/free': 5.0,

  'bitstamp:/BTC:/locked': 0.0,

  'bitstamp:/BTC:/total': 5.0,

  'bitstamp:/BTC:/worth': 12500.0,

  'bitstamp:/LTC:/free': 3.0,

  'bitstamp:/LTC:/locked': 0.0,

  'bitstamp:/LTC:/total': 3.0,

  'bitstamp:/LTC:/worth': 118.35000000000001,

  'net\_worth': 50085.1},

 'external': {'bitfinex:/BTC:date': Timestamp('2017-07-01 11:00:00'),

  'bitfinex:/BTC:open': 2505.56,

  'bitfinex:/BTC:high': 2513.38,

  'bitfinex:/BTC:low': 2495.12,

  'bitfinex:/BTC:close': 2509.17,

  'bitfinex:/BTC:volume': 287000.32,

  'bitfinex:/BTC:volume\_adi': 462887.3781183644,

  'bitfinex:/BTC:volume\_obv': nan,

  'bitfinex:/BTC:volume\_cmf': 0.5388828039430464,

  'bitfinex:/BTC:volume\_fi': nan,

  'bitfinex:/BTC:volume\_em': nan,

  'bitfinex:/BTC:volume\_vpt': -190920.02711825827,

  'bitfinex:/BTC:volume\_nvi': 1000.0,

  'bitfinex:/BTC:volatility\_atr': 85.51648155760596,

  'bitfinex:/BTC:volatility\_bbh': 2509.17,

  'bitfinex:/BTC:volatility\_bbl': 2509.17,

  'bitfinex:/BTC:volatility\_bbm': 2509.17,

  'bitfinex:/BTC:volatility\_bbhi': 0.0,

  'bitfinex:/BTC:volatility\_bbli': 0.0,

  'bitfinex:/BTC:volatility\_kcc': 2505.89,

  'bitfinex:/BTC:volatility\_kch': 2524.15,

  'bitfinex:/BTC:volatility\_kcl': 2487.6299999999997,

  'bitfinex:/BTC:volatility\_kchi': 0.0,

  'bitfinex:/BTC:volatility\_kcli': 0.0,

  'bitfinex:/BTC:volatility\_dch': 2509.17,

  'bitfinex:/BTC:volatility\_dcl': 2509.17,

  'bitfinex:/BTC:volatility\_dchi': 0.0,

  'bitfinex:/BTC:volatility\_dcli': 0.0,

  'bitfinex:/BTC:trend\_macd': nan,

  'bitfinex:/BTC:trend\_macd\_signal': nan,

  'bitfinex:/BTC:trend\_macd\_diff': nan,

  'bitfinex:/BTC:trend\_ema\_fast': nan,

  'bitfinex:/BTC:trend\_ema\_slow': nan,

  'bitfinex:/BTC:trend\_adx': 0.0,

  'bitfinex:/BTC:trend\_adx\_pos': 0.0,

  'bitfinex:/BTC:trend\_adx\_neg': 0.0,

  'bitfinex:/BTC:trend\_vortex\_ind\_pos': nan,

  'bitfinex:/BTC:trend\_vortex\_ind\_neg': nan,

  'bitfinex:/BTC:trend\_vortex\_diff': nan,

  'bitfinex:/BTC:trend\_trix': nan,

  'bitfinex:/BTC:trend\_mass\_index': 0.0,

  'bitfinex:/BTC:trend\_cci': nan,

  'bitfinex:/BTC:trend\_dpo': 4963.073762705523,

  'bitfinex:/BTC:trend\_kst': -664.2012654186367,

  'bitfinex:/BTC:trend\_kst\_sig': -664.2012654186367,

  'bitfinex:/BTC:trend\_kst\_diff': 0.0,

  'bitfinex:/BTC:trend\_ichimoku\_a': 2504.25,

  'bitfinex:/BTC:trend\_ichimoku\_b': 2504.25,

  'bitfinex:/BTC:trend\_visual\_ichimoku\_a': 7460.129960014917,

  'bitfinex:/BTC:trend\_visual\_ichimoku\_b': 7449.72498449202,

  'bitfinex:/BTC:trend\_aroon\_up': 4.0,

  'bitfinex:/BTC:trend\_aroon\_down': 4.0,

  'bitfinex:/BTC:trend\_aroon\_ind': 0.0,

  'bitfinex:/BTC:momentum\_rsi': nan,

  'bitfinex:/BTC:momentum\_mfi': nan,

  'bitfinex:/BTC:momentum\_tsi': -100.0,

  'bitfinex:/BTC:momentum\_uo': 0.2822915537138003,

  'bitfinex:/BTC:momentum\_stoch': 76.94414019715232,

  'bitfinex:/BTC:momentum\_stoch\_signal': 76.94414019715232,

  'bitfinex:/BTC:momentum\_wr': -23.055859802847678,

  'bitfinex:/BTC:momentum\_ao': 0.0,

  'bitfinex:/BTC:momentum\_kama': nan,

  'bitfinex:/BTC:others\_dr': -66.42012654186367,

  'bitfinex:/BTC:others\_dlr': nan,

  'bitfinex:/BTC:others\_cr': 0.0,

  'bitfinex:/ETH:date': Timestamp('2017-07-01 11:00:00'),

  'bitfinex:/ETH:open': 279.98,

  'bitfinex:/ETH:high': 279.99,

  'bitfinex:/ETH:low': 272.1,

  'bitfinex:/ETH:close': 275.01,

  'bitfinex:/ETH:volume': 679358.87,

  'bitstamp:/BTC:date': Timestamp('2017-07-01 11:00:00'),

  'bitstamp:/BTC:open': 2506.5,

  'bitstamp:/BTC:high': 2510.62,

  'bitstamp:/BTC:low': 2495.5,

  'bitstamp:/BTC:close': 2500.0,

  'bitstamp:/BTC:volume': 521903.7,

  'bitstamp:/LTC:date': Timestamp('2017-07-01 11:00:00'),

  'bitstamp:/LTC:open': 39.67,

  'bitstamp:/LTC:high': 39.67,

  'bitstamp:/LTC:low': 39.32,

  'bitstamp:/LTC:close': 39.45,

  'bitstamp:/LTC:volume': 1957.48,

  'bitstamp:/LTC:volume\_adi': 5133.608444728016,

  'bitstamp:/LTC:volume\_obv': nan,

  'bitstamp:/LTC:volume\_cmf': -0.2571428571428455,

  'bitstamp:/LTC:volume\_fi': nan,

  'bitstamp:/LTC:volume\_em': nan,

  'bitstamp:/LTC:volume\_vpt': -895.4321955984681,

  'bitstamp:/LTC:volume\_nvi': 1000.0,

  'bitstamp:/LTC:volatility\_atr': 1.4838450097847482,

  'bitstamp:/LTC:volatility\_bbh': 39.45,

  'bitstamp:/LTC:volatility\_bbl': 39.45,

  'bitstamp:/LTC:volatility\_bbm': 39.45,

  'bitstamp:/LTC:volatility\_bbhi': 0.0,

  'bitstamp:/LTC:volatility\_bbli': 0.0,

  'bitstamp:/LTC:volatility\_kcc': 39.480000000000004,

  'bitstamp:/LTC:volatility\_kch': 39.830000000000005,

  'bitstamp:/LTC:volatility\_kcl': 39.13,

  'bitstamp:/LTC:volatility\_kchi': 0.0,

  'bitstamp:/LTC:volatility\_kcli': 0.0,

  'bitstamp:/LTC:volatility\_dch': 39.45,

  'bitstamp:/LTC:volatility\_dcl': 39.45,

  'bitstamp:/LTC:volatility\_dchi': 0.0,

  'bitstamp:/LTC:volatility\_dcli': 0.0,

  'bitstamp:/LTC:trend\_macd': nan,

  'bitstamp:/LTC:trend\_macd\_signal': nan,

  'bitstamp:/LTC:trend\_macd\_diff': nan,

  'bitstamp:/LTC:trend\_ema\_fast': nan,

  'bitstamp:/LTC:trend\_ema\_slow': nan,

  'bitstamp:/LTC:trend\_adx': 0.0,

  'bitstamp:/LTC:trend\_adx\_pos': 0.0,

  'bitstamp:/LTC:trend\_adx\_neg': 0.0,

  'bitstamp:/LTC:trend\_vortex\_ind\_pos': nan,

  'bitstamp:/LTC:trend\_vortex\_ind\_neg': nan,

  'bitstamp:/LTC:trend\_vortex\_diff': nan,

  'bitstamp:/LTC:trend\_trix': nan,

  'bitstamp:/LTC:trend\_mass\_index': 0.0,

  'bitstamp:/LTC:trend\_cci': nan,

  'bitstamp:/LTC:trend\_dpo': 41.511479785526944,

  'bitstamp:/LTC:trend\_kst': -512.7312383060929,

  'bitstamp:/LTC:trend\_kst\_sig': -512.7312383060929,

  'bitstamp:/LTC:trend\_kst\_diff': 0.0,

  'bitstamp:/LTC:trend\_ichimoku\_a': 39.495000000000005,

  'bitstamp:/LTC:trend\_ichimoku\_b': 39.495000000000005,

  'bitstamp:/LTC:trend\_visual\_ichimoku\_a': 80.84515204884308,

  'bitstamp:/LTC:trend\_visual\_ichimoku\_b': 80.77039939728148,

  'bitstamp:/LTC:trend\_aroon\_up': 4.0,

  'bitstamp:/LTC:trend\_aroon\_down': 4.0,

  'bitstamp:/LTC:trend\_aroon\_ind': 0.0,

  'bitstamp:/LTC:momentum\_rsi': nan,

  'bitstamp:/LTC:momentum\_mfi': nan,

  'bitstamp:/LTC:momentum\_tsi': -100.0,

  'bitstamp:/LTC:momentum\_uo': 0.31218871344045224,

  'bitstamp:/LTC:momentum\_stoch': 37.14285714285772,

  'bitstamp:/LTC:momentum\_stoch\_signal': 37.14285714285772,

  'bitstamp:/LTC:momentum\_wr': -62.85714285714228,

  'bitstamp:/LTC:momentum\_ao': 0.0,

  'bitstamp:/LTC:momentum\_kama': nan,

  'bitstamp:/LTC:others\_dr': -51.27312383060929,

  'bitstamp:/LTC:others\_dlr': nan,

  'bitstamp:/LTC:others\_cr': 0.0}}

```

Train and Evaluate[¶](#train-and-evaluate "Permalink to this headline")

-----------------------------------------------------------------------

```

!python3 -m pip install git+https://github.com/tensortrade-org/tensortrade.git

```

  

**Setup Data Fetching**  

```

import pandas as pd

import tensortrade.env.default as default

from tensortrade.data.cdd import CryptoDataDownload

from tensortrade.feed.core import Stream, DataFeed

from tensortrade.oms.exchanges import Exchange

from tensortrade.oms.services.execution.simulated import execute\_order

from tensortrade.oms.instruments import USD, BTC, ETH

from tensortrade.oms.wallets import Wallet, Portfolio

from tensortrade.agents import DQNAgent

%matplotlib inline

```

```

cdd = CryptoDataDownload()

data = cdd.fetch("Bitfinex", "USD", "BTC", "1h")

```

  

**Create features with the feed module**  

```

def rsi(price: Stream[float], period: float) -> Stream[float]:

    r = price.diff()

    upside = r.clamp\_min(0).abs()

    downside = r.clamp\_max(0).abs()

    rs = upside.ewm(alpha=1 / period).mean() / downside.ewm(alpha=1 / period).mean()

    return 100\*(1 - (1 + rs) \*\* -1)

def macd(price: Stream[float], fast: float, slow: float, signal: float) -> Stream[float]:

    fm = price.ewm(span=fast, adjust=False).mean()

    sm = price.ewm(span=slow, adjust=False).mean()

    md = fm - sm

    signal = md - md.ewm(span=signal, adjust=False).mean()

    return signal

features = []

for c in data.columns[1:]:

    s = Stream.source(list(data[c]), dtype="float").rename(data[c].name)

    features += [s]

cp = Stream.select(features, lambda s: s.name == "close")

features = [

    cp.log().diff().rename("lr"),

    rsi(cp, period=20).rename("rsi"),

    macd(cp, fast=10, slow=50, signal=5).rename("macd")

]

feed = DataFeed(features)

feed.compile()

```

```

for i in range(5):

    print(feed.next())

```

```

{'lr': nan, 'rsi': nan, 'macd': 0.0}

{'lr': -0.008300031641449657, 'rsi': 0.0, 'macd': -1.9717171717171975}

{'lr': -0.01375743446296962, 'rsi': 0.0, 'macd': -6.082702245269603}

{'lr': 0.0020025323250756344, 'rsi': 8.795475693113076, 'macd': -7.287625162566419}

{'lr': 0.00344213459739251, 'rsi': 21.34663357024277, 'macd': -6.522181201739986}

```

  

**Setup Trading Environment**  

```

bitfinex = Exchange("bitfinex", service=execute\_order)(

    Stream.source(list(data["close"]), dtype="float").rename("USD-BTC")

)

portfolio = Portfolio(USD, [

    Wallet(bitfinex, 10000 \* USD),

    Wallet(bitfinex, 10 \* BTC)

])

renderer\_feed = DataFeed([

    Stream.source(list(data["date"])).rename("date"),

    Stream.source(list(data["open"]), dtype="float").rename("open"),

    Stream.source(list(data["high"]), dtype="float").rename("high"),

    Stream.source(list(data["low"]), dtype="float").rename("low"),

    Stream.source(list(data["close"]), dtype="float").rename("close"),

    Stream.source(list(data["volume"]), dtype="float").rename("volume")

])

env = default.create(

    portfolio=portfolio,

    action\_scheme="managed-risk",

    reward\_scheme="risk-adjusted",

    feed=feed,

    renderer\_feed=renderer\_feed,

    renderer=default.renderers.PlotlyTradingChart(),

    window\_size=20

)

```

```

env.observer.feed.next()

```

```

{'internal': {'bitfinex:/USD-BTC': 2509.17,

  'bitfinex:/USD:/free': 10000.0,

  'bitfinex:/USD:/locked': 0.0,

  'bitfinex:/USD:/total': 10000.0,

  'bitfinex:/BTC:/free': 10.0,

  'bitfinex:/BTC:/locked': 0.0,

  'bitfinex:/BTC:/total': 10.0,

  'bitfinex:/BTC:/worth': 25091.7,

  'net\_worth': 35091.7},

 'external': {'lr': nan, 'rsi': nan, 'macd': 0.0},

 'renderer': {'date': Timestamp('2017-07-01 11:00:00'),

  'open': 2505.56,

  'high': 2513.38,

  'low': 2495.12,

  'close': 2509.17,

  'volume': 287000.32}}

```

  

**Setup and Train DQN Agent**  

```

agent = DQNAgent(env)

agent.train(n\_steps=200, n\_episodes=2, save\_path="agents/")

```

Renderers and Plotly Chart[¶](#renderers-and-plotly-chart "Permalink to this headline")

---------------------------------------------------------------------------------------

  

**Data Loading Function**  

```

# ipywidgets is required to run Plotly in Jupyter Notebook.

# Uncomment and run the following line to install it if required.

!pip install ipywidgets

```

```

import ta

import pandas as pd

from tensortrade.feed.core import Stream, DataFeed, NameSpace

from tensortrade.oms.exchanges import Exchange

from tensortrade.oms.services.execution.simulated import execute\_order

from tensortrade.oms.instruments import USD, BTC

from tensortrade.oms.wallets import Wallet, Portfolio

%matplotlib inline

```

```

def load\_csv(filename):

    df = pd.read\_csv('data/' + filename, skiprows=1)

    df.drop(columns=['symbol', 'volume\_btc'], inplace=True)

    # Fix timestamp form "2019-10-17 09-AM" to "2019-10-17 09-00-00 AM"

    df['date'] = df['date'].str[:14] + '00-00 ' + df['date'].str[-2:]

    # Convert the date column type from string to datetime for proper sorting.

    df['date'] = pd.to\_datetime(df['date'])

    # Make sure historical prices are sorted chronologically, oldest first.

    df.sort\_values(by='date', ascending=True, inplace=True)

    df.reset\_index(drop=True, inplace=True)

    # Format timestamps as you want them to appear on the chart buy/sell marks.

    df['date'] = df['date'].dt.strftime('%Y-%m-%d %I:%M %p')

    return df

```

```

df = load\_csv('Bitfinex\_BTCUSD\_1h.csv')

df.head()

```

  

**Data Preparation**  

```

dataset = ta.add\_all\_ta\_features(df, 'open', 'high', 'low', 'close', 'volume', fillna=True)

dataset.head(3)

```

Note: It is recommended to create the chart data *after* creating and cleaning the dataset to ensure one-to-one mapping between the historical prices data and the dataset.

```

price\_history = dataset[['date', 'open', 'high', 'low', 'close', 'volume']]  # chart data

display(price\_history.head(3))

dataset.drop(columns=['date', 'open', 'high', 'low', 'close', 'volume'], inplace=True)

```

  

**Setup Trading Environment**  

```

bitfinex = Exchange("bitfinex", service=execute\_order)(

    Stream.source(price\_history['close'].tolist(), dtype="float").rename("USD-BTC")

)

portfolio = Portfolio(USD, [

    Wallet(bitfinex, 10000 \* USD),

    Wallet(bitfinex, 10 \* BTC),

])

with NameSpace("bitfinex"):

    streams = [Stream.source(dataset[c].tolist(), dtype="float").rename(c) for c in dataset.columns]

feed = DataFeed(streams)

feed.next()

```

```

{'bitfinex:/volume\_adi': 503274.35945218964,

 'bitfinex:/volume\_obv': 0.0,

 'bitfinex:/volume\_cmf': 0.5388828039430464,

 'bitfinex:/volume\_fi': 0.0,

 'bitfinex:/volume\_em': 0.0,

 'bitfinex:/volume\_vpt': -187039.68188942864,

 'bitfinex:/volume\_nvi': 1000.0,

 'bitfinex:/volatility\_atr': 88.87448632521046,

 'bitfinex:/volatility\_bbh': 2509.17,

 'bitfinex:/volatility\_bbl': 2509.17,

 'bitfinex:/volatility\_bbm': 2509.17,

 'bitfinex:/volatility\_bbhi': 0.0,

 'bitfinex:/volatility\_bbli': 0.0,

 'bitfinex:/volatility\_kcc': 2505.89,

 'bitfinex:/volatility\_kch': 2524.15,

 'bitfinex:/volatility\_kcl': 2487.6299999999997,

 'bitfinex:/volatility\_kchi': 0.0,

 'bitfinex:/volatility\_kcli': 0.0,

 'bitfinex:/volatility\_dch': 2509.17,

 'bitfinex:/volatility\_dcl': 2509.17,

 'bitfinex:/volatility\_dchi': 0.0,

 'bitfinex:/volatility\_dcli': 0.0,

 'bitfinex:/trend\_macd': 0.0,

 'bitfinex:/trend\_macd\_signal': 0.0,

 'bitfinex:/trend\_macd\_diff': 0.0,

 'bitfinex:/trend\_ema\_fast': 2509.17,

 'bitfinex:/trend\_ema\_slow': 2509.17,

 'bitfinex:/trend\_adx': 0.0,

 'bitfinex:/trend\_adx\_pos': 0.0,

 'bitfinex:/trend\_adx\_neg': 0.0,

 'bitfinex:/trend\_vortex\_ind\_pos': 1.0,

 'bitfinex:/trend\_vortex\_ind\_neg': 1.0,

 'bitfinex:/trend\_vortex\_diff': 0.0,

 'bitfinex:/trend\_trix': -65.01942947444225,

 'bitfinex:/trend\_mass\_index': 1.0,

 'bitfinex:/trend\_cci': 0.0,

 'bitfinex:/trend\_dpo': 4669.658895132072,

 'bitfinex:/trend\_kst': -650.476416605854,

 'bitfinex:/trend\_kst\_sig': -650.476416605854,

 'bitfinex:/trend\_kst\_diff': 0.0,

 'bitfinex:/trend\_ichimoku\_a': 2504.25,

 'bitfinex:/trend\_ichimoku\_b': 2504.25,

 'bitfinex:/trend\_visual\_ichimoku\_a': 7164.427851548871,

 'bitfinex:/trend\_visual\_ichimoku\_b': 7151.343258415852,

 'bitfinex:/trend\_aroon\_up': 4.0,

 'bitfinex:/trend\_aroon\_down': 4.0,

 'bitfinex:/trend\_aroon\_ind': 0.0,

 'bitfinex:/momentum\_rsi': 50.0,

 'bitfinex:/momentum\_mfi': 50.0,

 'bitfinex:/momentum\_tsi': -100.0,

 'bitfinex:/momentum\_uo': 0.29997594458961346,

 'bitfinex:/momentum\_stoch': 76.94414019715232,

 'bitfinex:/momentum\_stoch\_signal': 76.94414019715232,

 'bitfinex:/momentum\_wr': -23.055859802847678,

 'bitfinex:/momentum\_ao': 0.0,

 'bitfinex:/momentum\_kama': 2509.17,

 'bitfinex:/others\_dr': -65.0476416605854,

 'bitfinex:/others\_dlr': 0.0,

 'bitfinex:/others\_cr': 0.0}

```

  

**Trading Environment Renderers**  

A renderer is a channel for the trading environment to output its current state. One or more renderers can be attached to the environment at the same time. For example, you can let the environment draw a chart and log to a file at the same time.

Notice that while all renderers can technically be used together, you need to select the best combination to avoid undesired results. For example, PlotlyTradingChart can work well with FileLogger but may not display well with ScreenLogger.

Renderer can be set by name (string) or class, single or list. Available renderers are:

* `'screenlog'` or `ScreenLogger`: Shows results on the screen.

* `'filelog'` or `FileLogger`: Logs results to a file.

* `'plotly'` or `PlotlyTradingChart`: A trading chart based on Plotly.

  

**Examples**:  

* renderers = ‘screenlog’ (default)

* renderers = [’screenlog’, ‘filelog’]

* renderers = ScreenLogger()

* renderers = [’screenlog’, `FileLogger()`]

* renderers = [`FileLogger(filename='example.log')`]

Renderers can also be created and configured first then attached to the environment as seen in a following example.

```

import tensortrade.env.default as default

env = default.create(

    portfolio=portfolio,

    action\_scheme="managed-risk",

    reward\_scheme="risk-adjusted",

    feed=feed,

    renderer="screen-log",  # ScreenLogger used with default settings

    window\_size=20

)

```

```

from tensortrade.agents import DQNAgent

agent = DQNAgent(env)

agent.train(n\_episodes=2, n\_steps=200, render\_interval=10)

```

```

====      AGENT ID: b8b6ad1a-c158-4743-8a2d-aab3a26ce82c      ====

[2020-07-29 3:43:06 PM] Episode: 1/2 Step: 131/200

[2020-07-29 3:43:07 PM] Episode: 1/2 Step: 141/200

[2020-07-29 3:43:08 PM] Episode: 1/2 Step: 151/200

[2020-07-29 3:43:09 PM] Episode: 1/2 Step: 161/200

[2020-07-29 3:43:11 PM] Episode: 1/2 Step: 171/200

[2020-07-29 3:43:12 PM] Episode: 1/2 Step: 181/200

[2020-07-29 3:43:13 PM] Episode: 1/2 Step: 191/200

[2020-07-29 3:43:14 PM] Episode: 1/2 Step: 201/200

[2020-07-29 3:43:15 PM] Episode: 2/2 Step: 11/200

[2020-07-29 3:43:16 PM] Episode: 2/2 Step: 21/200

[2020-07-29 3:43:17 PM] Episode: 2/2 Step: 31/200

[2020-07-29 3:43:19 PM] Episode: 2/2 Step: 41/200

[2020-07-29 3:43:20 PM] Episode: 2/2 Step: 51/200

[2020-07-29 3:43:21 PM] Episode: 2/2 Step: 61/200

[2020-07-29 3:43:22 PM] Episode: 2/2 Step: 71/200

[2020-07-29 3:43:23 PM] Episode: 2/2 Step: 81/200

[2020-07-29 3:43:24 PM] Episode: 2/2 Step: 91/200

[2020-07-29 3:43:25 PM] Episode: 2/2 Step: 101/200

[2020-07-29 3:43:26 PM] Episode: 2/2 Step: 111/200

[2020-07-29 3:43:27 PM] Episode: 2/2 Step: 121/200

[2020-07-29 3:43:29 PM] Episode: 2/2 Step: 131/200

[2020-07-29 3:43:30 PM] Episode: 2/2 Step: 141/200

[2020-07-29 3:43:31 PM] Episode: 2/2 Step: 151/200

[2020-07-29 3:43:32 PM] Episode: 2/2 Step: 161/200

[2020-07-29 3:43:33 PM] Episode: 2/2 Step: 171/200

[2020-07-29 3:43:34 PM] Episode: 2/2 Step: 181/200

[2020-07-29 3:43:35 PM] Episode: 2/2 Step: 191/200

[2020-07-29 3:43:36 PM] Episode: 2/2 Step: 201/200

-125697.1219732128

```

  

**Environment with Multiple Renderers**  

Create PlotlyTradingChart and FileLogger renderers. Configuring renderers is optional as they can be used with their default settings.

```

from tensortrade.env.default.renderers import PlotlyTradingChart, FileLogger

chart\_renderer = PlotlyTradingChart(

    display=True,  # show the chart on screen (default)

    height=800,  # affects both displayed and saved file height. None for 100% height.

    save\_format="html",  # save the chart to an HTML file

    auto\_open\_html=True,  # open the saved HTML chart in a new browser tab

)

file\_logger = FileLogger(

    filename="example.log",  # omit or None for automatic file name

    path="training\_logs"  # create a new directory if doesn't exist, None for no directory

)

```

  

**Environement with Multiple Renderers**  

With the plotly renderer you must provide an parameter called `renderer\_feed`. This is a `DataFeed` instance that provides all the information that is required by a renderer to function.

```

renderer\_feed = DataFeed([

    Stream.source(price\_history[c].tolist(), dtype="float").rename(c) for c in price\_history]

)

env = default.create(

    portfolio=portfolio,

    action\_scheme="managed-risk",

    reward\_scheme="risk-adjusted",

    feed=feed,

    window\_size=20,

    renderer\_feed=renderer\_feed,

    renderers=[

        chart\_renderer,

        file\_logger

    ]

)

```

  

**Setup and Train DQN Agent**  

The green and red arrows shown on the chart represent buy and sell trades respectively. The head of each arrow falls at the trade execution price.

```

from tensortrade.agents import DQNAgent

agent = DQNAgent(env)

# Set render\_interval to None to render at episode ends only

agent.train(n\_episodes=2, n\_steps=200, render\_interval=10)

```

```

====      AGENT ID: fec5e2c5-eb35-4ff6-8416-b876f0e8be66      ====

-122271.41943956864

```

  

**Direct Performance and Net Worth Plotting**  

Alternatively, the final performance and net worth can be displayed using pandas via Matplotlib.

```

%matplotlib inline

portfolio.performance.plot()

```

![_images/renderers_and_plotly_chart_21_1.png](_images/renderers_and_plotly_chart_21_1.png)png

```

portfolio.performance.net\_worth.plot()

```

![_images/renderers_and_plotly_chart_22_1.png](_images/renderers_and_plotly_chart_22_1.png)png

Stochastic Data[¶](#stochastic-data "Permalink to this headline")

-----------------------------------------------------------------

  

**Generating Price Data using Stocastic Processes**  

* Geometric Brownian Motion (GBM)

* Fractional Brownian Motion (FBM)

* Heston Stochastic Volatility Model

* Cox Ingersoll Ross (CIR)

* Ornstein Uhlebneck stochastic process

  

**Model Parameters**  

The model parameters class contains all of the parameters used by the following stochastic processes. The parameters have been prefixed with the name of the stochastic process they are used in. Calibration of the stochastic processes would involve looking for the parameter values which best fit some historical data.

* `all\_s0` This is the starting asset value

* `all\_time` This is the amount of time to simulate for

* `all\_delta` This is the delta, the rate of time e.g. 1/252 = daily, 1/12 = monthly

* `all\_sigma` This is the volatility of the stochastic processes

* `gbm\_mu` This is the annual drift factor for geometric brownian motion

* `jumps\_lamda` This is the probability of a jump happening at each point in time

* `jumps\_sigma` This is the volatility of the jump size

* `jumps\_mu` This is the average jump size

* `cir\_a` This is the rate of mean reversion for Cox Ingersoll Ross

* `cir\_mu` This is the long run average interest rate for Cox Ingersoll Ross

* `all\_r0` This is the starting interest rate value

* `cir\_rho` This is the correlation between the wiener processes of the Heston model

* `ou\_a` This is the rate of mean reversion for Ornstein Uhlenbeck

* `ou\_mu` This is the long run average interest rate for Ornstein Uhlenbeck

* `sheston\_a` This is the rate of mean reversion for volatility in the Heston model

* `heston\_mu` This is the long run average volatility for the Heston model

* `heston\_vol0` This is the starting volatility value for the Heston model

```

import random

import tensortrade.stochastic as sp

%matplotlib inline

```

  

**Geometric Brownian Motion**  

```

data = sp.gbm(

    base\_price=100,

    base\_volume=5,

    start\_date="2010-01-01",

    times\_to\_generate=1000,

    time\_frame='1H'

)

data.close.plot()

```

![_images/use_stochastic_data_3_1.png](_images/use_stochastic_data_3_1.png)png

  

**Heston Stochastic Volatility Model**  

```

data = sp.heston(

    base\_price=100,

    base\_volume=5,

    start\_date="2010-01-01",

    times\_to\_generate=1000,

    time\_frame='1H'

)

data.close.plot()

```

![_images/use_stochastic_data_5_1.png](_images/use_stochastic_data_5_1.png)png

  

**Fractional Brownian Motion**  

```

data = sp.fbm(

    base\_price=100,

    base\_volume=5,

    start\_date="2010-01-01",

    times\_to\_generate=1000,

    time\_frame='1H'

)

data.close.plot()

```

![_images/use_stochastic_data_7_1.png](_images/use_stochastic_data_7_1.png)png

  

**Cox Ingersoll Ross (CIR)**  

```

data = sp.cox(

    base\_price=100,

    base\_volume=5,

    start\_date="2010-01-01",

    times\_to\_generate=1000,

    time\_frame='1H'

)

data.close.plot()

```

![_images/use_stochastic_data_9_1.png](_images/use_stochastic_data_9_1.png)png

  

**Ornstein Uhlenbeck Process**  

```

data = sp.ornstein(

    base\_price=100,

    base\_volume=5,

    start\_date="2010-01-01",

    times\_to\_generate=1000,

    time\_frame='1H'

)

data.close.plot()

```

![_images/use_stochastic_data_11_1.png](_images/use_stochastic_data_11_1.png)png

Ledger Example[¶](#ledger-example "Permalink to this headline")

---------------------------------------------------------------

  

**Install master branch of TensorTrade**  

```

!pip install git+https://github.com/tensortrade-org/tensortrade.git -U

```

```

import tensortrade.env.default as default

from tensortrade.feed.core import Stream, DataFeed

from tensortrade.data.cdd import CryptoDataDownload

from tensortrade.oms.wallets import Portfolio, Wallet

from tensortrade.oms.exchanges import Exchange

from tensortrade.oms.services.execution.simulated import execute\_order

from tensortrade.oms.instruments import USD, BTC, ETH, LTC

```

  

**Load Data for Exchanges**  

Using the `tensortrade.data.cdd` module you can load data from any `csv` file provided at:

* https://www.cryptodatadownload.com/data/northamerican/

using the `CryptoDataDownload` class.

```

cdd = CryptoDataDownload()

bitfinex\_btc = cdd.fetch("Bitfinex", "USD", "BTC", "1h")

bitfinex\_eth = cdd.fetch("Bitfinex", "USD", "ETH", "1h")

bitstamp\_btc = cdd.fetch("Bitstamp", "USD", "BTC", "1h")

bitstamp\_eth = cdd.fetch("Bitstamp", "USD", "ETH", "1h")

bitstamp\_ltc = cdd.fetch("Bitstamp", "USD", "LTC", "1h")

```

  

**Inspect Transactions**  

```

bitfinex = Exchange("bitfinex", service=execute\_order)(

    Stream.source(list(bitfinex\_btc['close'][-100:]), dtype="float").rename("USD-BTC"),

    Stream.source(list(bitfinex\_eth['close'][-100:]), dtype="float").rename("USD-ETH")

)

bitstamp = Exchange("bitstamp", service=execute\_order)(

    Stream.source(list(bitstamp\_btc['close'][-100:]), dtype="float").rename("USD-BTC"),

    Stream.source(list(bitstamp\_eth['close'][-100:]), dtype="float").rename("USD-ETH"),

    Stream.source(list(bitstamp\_ltc['close'][-100:]), dtype="float").rename("USD-LTC")

)

portfolio = Portfolio(USD, [

    Wallet(bitfinex, 10000 \* USD),

    Wallet(bitfinex, 10 \* BTC),

    Wallet(bitfinex, 5 \* ETH),

    Wallet(bitstamp, 1000 \* USD),

    Wallet(bitstamp, 5 \* BTC),

    Wallet(bitstamp, 20 \* ETH),

    Wallet(bitstamp, 3 \* LTC)

])

feed = DataFeed([

    Stream.source(list(bitstamp\_eth['volume'][-100:]), dtype="float").rename("volume:/USD-ETH"),

    Stream.source(list(bitstamp\_ltc['volume'][-100:]), dtype="float").rename("volume:/USD-LTC")

])

env = default.create(

    portfolio=portfolio,

    action\_scheme=default.actions.SimpleOrders(),

    reward\_scheme=default.rewards.SimpleProfit(),

    feed=feed

)

done = False

obs = env.reset()

while not done:

    action = env.action\_space.sample()

    obs, reward, done, info = env.step(action)

portfolio.ledger.as\_frame().head(7)

```

  

**Inspect Transactions of ManagedRiskOrders**  

```

portfolio = Portfolio(USD, [

    Wallet(bitfinex, 10000 \* USD),

    Wallet(bitfinex, 0 \* BTC),

    Wallet(bitfinex, 0 \* ETH),

])

env = default.create(

    portfolio=portfolio,

    action\_scheme=default.actions.ManagedRiskOrders(),

    reward\_scheme=default.rewards.SimpleProfit(),

    feed=feed

)

done = False

while not done:

    action = env.action\_space.sample()

    obs, reward, done, info = env.step(action)

portfolio.ledger.as\_frame().head(20)

```

  

**Transactions in Spreadsheets**  

To take a closer look at the transactions that are happening within the system, copy the transactions to a csv file and load it into any spreadsheet software. If where you are running this allows access to the system clipboard, you can directly copy the frame to your system clipboard by doing the following:

* `portfolio.ledger.as\_frame().to\_clipboard(index=False)`

Then just paste into any spreadsheet software (e.g. Execel, Google Sheets).

Using Ray with TensorTrade[¶](#using-ray-with-tensortrade "Permalink to this headline")

---------------------------------------------------------------------------------------

In this tutorial, we are going to learn how to use `ray` with TensorTrade in order to create a profitable algorithm on a predictable sine curve. You may be asking yourself, why use something so simple when the real world data is much more difficult to predict? Now this is a very good question and there is a simple answer.

> 

> “The man who moves a mountain begins by carrying away small stones.”

> 

> 

> 

> > 

> > - Confucius

> 

> 

> 

Before trying to jump into the world of complex trading environments, a simple sine curve can be used to perform a sanity check on your trading algorithm. The reward and action scheme you use should be able to make money on the predictable pattern of a sine curve. If it does not, then you know there is no possibility success will be found on a more complex environment. There are some answers we would like to know fast before we waste time and resources in developing an algorithm which are and one of them is, does our `RewardScheme` correctly specify the goal we are after?

In this tutorial we will propose a new reward scheme and action scheme and show that you can actually have the reward scheme be dependent on the action scheme. This will be done through the use of a `DataFeed`. We first, however, need to install `ray`.

```

!pip install ray==0.8.7

!pip install symfit

```

We will begin by defining the two instruments we want to define our portfolio with. We will be using the U.S. dollar and fake coin called TensorTrade Coin.

```

from tensortrade.oms.instruments import Instrument

USD = Instrument("USD", 2, "U.S. Dollar")

TTC = Instrument("TTC", 8, "TensorTrade Coin")

```

Now let us look at the curve we will be using to define our price.

![_images/sine_curve.png](_images/sine_curve.png)png

Ideally, what we will be expecting from our agent is that it will be able to sell at the peaks and buy at the troughs. We will move on to defining our action scheme. The `ActionScheme` we are going to build is going to be extremely simple. There are only 3 states that our agent can be in which are `buy`, `sell`, and `hold`. We will make use of a new function in the library, `proportion\_order`. This function enables the user to make an order that can take a percentage of funds at a particular wallet and send it to another. Therefore, we want to structure a way to only have two actions in our scheme and use them as indicators to move our funds to the opposite wallet.

```

from gym.spaces import Discrete

from tensortrade.env.default.actions import TensorTradeActionScheme

from tensortrade.env.generic import ActionScheme, TradingEnv

from tensortrade.core import Clock

from tensortrade.oms.instruments import ExchangePair

from tensortrade.oms.wallets import Portfolio

from tensortrade.oms.orders import (

    Order,

    proportion\_order,

    TradeSide,

    TradeType

)

class BSH(TensorTradeActionScheme):

    registered\_name = "bsh"

    def \_\_init\_\_(self, cash: 'Wallet', asset: 'Wallet'):

        super().\_\_init\_\_()

        self.cash = cash

        self.asset = asset

        self.listeners = []

        self.action = 0

    @property

    def action\_space(self):

        return Discrete(2)

    def attach(self, listener):

        self.listeners += [listener]

        return self

    def get\_orders(self, action: int, portfolio: 'Portfolio'):

        order = None

        if abs(action - self.action) > 0:

            src = self.cash if self.action == 0 else self.asset

            tgt = self.asset if self.action == 0 else self.cash

            order = proportion\_order(portfolio, src, tgt, 1.0)

            self.action = action

        for listener in self.listeners:

            listener.on\_action(action)

        return [order]

    def reset(self):

        super().reset()

        self.action = 0

```

Next, we want to create our reward scheme to reflect how well we are positioned in the environment. Essentially, we want to make a mapping that shows how we would like our rewards to be reflected for each state we are in. The following shows such a mapping:

| State | Price Up | Price Down |

| --- | --- | --- |

| All funds in `cash` wallet (0) | - | + |

| All funds in `asset` wallet (1) | + | - |

The signs in the table show what we would like the sign of the rewards to be. The position-based reward scheme (PBR) achieves this mapping.

```

from tensortrade.env.default.rewards import TensorTradeRewardScheme

from tensortrade.feed.core import Stream, DataFeed

class PBR(TensorTradeRewardScheme):

    registered\_name = "pbr"

    def \_\_init\_\_(self, price: 'Stream'):

        super().\_\_init\_\_()

        self.position = -1

        r = Stream.sensor(price, lambda p: p.value, dtype="float").diff()

        position = Stream.sensor(self, lambda rs: rs.position, dtype="float")

        reward = (r \* position).fillna(0).rename("reward")

        self.feed = DataFeed([reward])

        self.feed.compile()

    def on\_action(self, action: int):

        self.position = -1 if action == 0 else 1

    def get\_reward(self, portfolio: 'Portfolio'):

        return self.feed.next()["reward"]

    def reset(self):

        self.position = -1

        self.feed.reset()

```

Finally, we would like to make sure we can see if the agent is selling at the peaks and buying at the troughs. We will make a quick `Renderer` that can show this information using `Matplotlib`.

```

import matplotlib.pyplot as plt

from tensortrade.env.generic import Renderer

class PositionChangeChart(Renderer):

    def \_\_init\_\_(self, color: str = "orange"):

        self.color = "orange"

    def render(self, env, \*\*kwargs):

        history = pd.DataFrame(env.observer.renderer\_history)

        actions = list(history.action)

        p = list(history.price)

        buy = {}

        sell = {}

        for i in range(len(actions) - 1):

            a1 = actions[i]

            a2 = actions[i + 1]

            if a1 != a2:

                if a1 == 0 and a2 == 1:

                    buy[i] = p[i]

                else:

                    sell[i] = p[i]

        buy = pd.Series(buy)

        sell = pd.Series(sell)

        fig, axs = plt.subplots(1, 2, figsize=(15, 5))

        fig.suptitle("Performance")

        axs[0].plot(np.arange(len(p)), p, label="price", color=self.color)

        axs[0].scatter(buy.index, buy.values, marker="^", color="green")

        axs[0].scatter(sell.index, sell.values, marker="^", color="red")

        axs[0].set\_title("Trading Chart")

        env.action\_scheme.portfolio.performance.plot(ax=axs[1])

        axs[1].set\_title("Net Worth")

        plt.show()

```

  

**Train**  

Now in order to use our custom environment in `ray` we must first write a function that creates an instance of the `TradingEnv` from a configuration dictionary.

```

import ray

import numpy as np

import pandas as pd

from ray import tune

from ray.tune.registry import register\_env

import tensortrade.env.default as default

from tensortrade.feed.core import DataFeed, Stream

from tensortrade.oms.exchanges import Exchange

from tensortrade.oms.services.execution.simulated import execute\_order

from tensortrade.oms.wallets import Wallet, Portfolio

def create\_env(config):

    x = np.arange(0, 2\*np.pi, 2\*np.pi / 1001)

    y = 50\*np.sin(3\*x) + 100

    x = np.arange(0, 2\*np.pi, 2\*np.pi / 1000)

    p = Stream.source(y, dtype="float").rename("USD-TTC")

    bitfinex = Exchange("bitfinex", service=execute\_order)(

        p

    )

    cash = Wallet(bitfinex, 100000 \* USD)

    asset = Wallet(bitfinex, 0 \* TTC)

    portfolio = Portfolio(USD, [

        cash,

        asset

    ])

    feed = DataFeed([

        p,

        p.rolling(window=10).mean().rename("fast"),

        p.rolling(window=50).mean().rename("medium"),

        p.rolling(window=100).mean().rename("slow"),

        p.log().diff().fillna(0).rename("lr")

    ])

    reward\_scheme = PBR(price=p)

    action\_scheme = BSH(

        cash=cash,

        asset=asset

    ).attach(reward\_scheme)

    renderer\_feed = DataFeed([

        Stream.source(y, dtype="float").rename("price"),

        Stream.sensor(action\_scheme, lambda s: s.action, dtype="float").rename("action")

    ])

    environment = default.create(

        feed=feed,

        portfolio=portfolio,

        action\_scheme=action\_scheme,

        reward\_scheme=reward\_scheme,

        renderer\_feed=renderer\_feed,

        renderer=PositionChangeChart(),

        window\_size=config["window\_size"],

        max\_allowed\_loss=0.6

    )

    return environment

register\_env("TradingEnv", create\_env)

```

Now that the environment is registered we can run the training algorithm using the Proximal Policy Optimization (PPO) algorithm implemented in `rllib`.

```

analysis = tune.run(

    "PPO",

    stop={

      "episode\_reward\_mean": 500

    },

    config={

        "env": "TradingEnv",

        "env\_config": {

            "window\_size": 25

        },

        "log\_level": "DEBUG",

        "framework": "torch",

        "ignore\_worker\_failures": True,

        "num\_workers": 1,

        "num\_gpus": 0,

        "clip\_rewards": True,

        "lr": 8e-6,

        "lr\_schedule": [

            [0, 1e-1],

            [int(1e2), 1e-2],

            [int(1e3), 1e-3],

            [int(1e4), 1e-4],

            [int(1e5), 1e-5],

            [int(1e6), 1e-6],

            [int(1e7), 1e-7]

        ],

        "gamma": 0,

        "observation\_filter": "MeanStdFilter",

        "lambda": 0.72,

        "vf\_loss\_coeff": 0.5,

        "entropy\_coeff": 0.01

    },

    checkpoint\_at\_end=True

)

```

After training is complete, we would now like to get access to the agents policy. We can do that by restoring the agent using the following code.

```

import ray.rllib.agents.ppo as ppo

# Get checkpoint

checkpoints = analysis.get\_trial\_checkpoints\_paths(

    trial=analysis.get\_best\_trial("episode\_reward\_mean"),

    metric="episode\_reward\_mean"

)

checkpoint\_path = checkpoints[0][0]

# Restore agent

agent = ppo.PPOTrainer(

    env="TradingEnv",

    config={

        "env\_config": {

            "window\_size": 25

        },

        "framework": "torch",

        "log\_level": "DEBUG",

        "ignore\_worker\_failures": True,

        "num\_workers": 1,

        "num\_gpus": 0,

        "clip\_rewards": True,

        "lr": 8e-6,

        "lr\_schedule": [

            [0, 1e-1],

            [int(1e2), 1e-2],

            [int(1e3), 1e-3],

            [int(1e4), 1e-4],

            [int(1e5), 1e-5],

            [int(1e6), 1e-6],

            [int(1e7), 1e-7]

        ],

        "gamma": 0,

        "observation\_filter": "MeanStdFilter",

        "lambda": 0.72,

        "vf\_loss\_coeff": 0.5,

        "entropy\_coeff": 0.01

    }

)

agent.restore(checkpoint\_path)

```

Now let us get a visualization of the agent’s decision making on our sine curve example by rendering the environment.

```

# Instantiate the environment

env = create\_env({

    "window\_size": 25

})

# Run until episode ends

episode\_reward = 0

done = False

obs = env.reset()

while not done:

    action = agent.compute\_action(obs)

    obs, reward, done, info = env.step(action)

    episode\_reward += reward

env.render()

```

![_images/train_performance.png](_images/train_performance.png)png

From the rendering, you can see that the agent is making near optimal decisions on the environment. Now we want to put the agent in an environment it is not used to and see what kind of decisions it makes. We will use for our price, an `order` 5 Fourier series fitted to a randomly generated Geometric Brownian Motion (GBM). We will use the `symfit` library to do this.

```

from symfit import parameters, variables, sin, cos, Fit

def fourier\_series(x, f, n=0):

    """Creates a symbolic fourier series of order `n`.

 Parameters

 ----------

 x : `symfit.Variable`

 The input variable for the function.

 f : `symfit.Parameter`

 Frequency of the fourier series

 n : int

 Order of the fourier series.

 """

    # Make the parameter objects for all the terms

    a0, \*cos\_a = parameters(','.join(['a{}'.format(i) for i in range(0, n + 1)]))

    sin\_b = parameters(','.join(['b{}'.format(i) for i in range(1, n + 1)]))

    # Construct the series

    series = a0 + sum(ai \* cos(i \* f \* x) + bi \* sin(i \* f \* x)

                     for i, (ai, bi) in enumerate(zip(cos\_a, sin\_b), start=1))

    return series

def gbm(price: float,

        mu: float,

        sigma: float,

        dt: float,

        n: int) -> np.array:

    """Generates a geometric brownian motion path.

 Parameters

 ----------

 price : float

 The initial price of the series.

 mu : float

 The percentage drift.

 sigma : float

 The percentage volatility.

 dt : float

 The time step size.

 n : int

 The number of steps to be generated in the path.

 Returns

 -------

 `np.array`

 The generated path.

 """

    y = np.exp((mu - sigma \*\* 2 / 2) \* dt + sigma \* np.random.normal(0, np.sqrt(dt), size=n).T)

    y = price \* y.cumprod(axis=0)

    return y

def fourier\_gbm(price, mu, sigma, dt, n, order):

    x, y = variables('x, y')

    w, = parameters('w')

    model\_dict = {y: fourier\_series(x, f=w, n=order)}

    # Make step function data

    xdata = np.arange(-np.pi, np.pi, 2\*np.pi / n)

    ydata = np.log(gbm(price, mu, sigma, dt, n))

    # Define a Fit object for this model and data

    fit = Fit(model\_dict, x=xdata, y=ydata)

    fit\_result = fit.execute()

    return np.exp(fit.model(x=xdata, \*\*fit\_result.params).y)

```

Now we can make the evaluation environment and see how the agent performs.

```

def create\_eval\_env(config):

    y = config["y"]

    x = np.arange(0, 2\*np.pi, 2\*np.pi / 1000)

    p = Stream.source(y, dtype="float").rename("USD-TTC")

    bitfinex = Exchange("bitfinex", service=execute\_order)(

        p

    )

    cash = Wallet(bitfinex, 100000 \* USD)

    asset = Wallet(bitfinex, 0 \* TTC)

    portfolio = Portfolio(USD, [

        cash,

        asset

    ])

    feed = DataFeed([

        p,

        p.rolling(window=10).mean().rename("fast"),

        p.rolling(window=50).mean().rename("medium"),

        p.rolling(window=100).mean().rename("slow"),

        p.log().diff().fillna(0).rename("lr")

    ])

    reward\_scheme = PBR(price=p)

    action\_scheme = BSH(

        cash=cash,

        asset=asset

    ).attach(reward\_scheme)

    renderer\_feed = DataFeed([

        Stream.source(y, dtype="float").rename("price"),

        Stream.sensor(action\_scheme, lambda s: s.action, dtype="float").rename("action")

    ])

    environment = default.create(

        feed=feed,

        portfolio=portfolio,

        action\_scheme=action\_scheme,

        reward\_scheme=reward\_scheme,

        renderer\_feed=renderer\_feed,

        renderer=PositionChangeChart(),

        window\_size=config["window\_size"],

        max\_allowed\_loss=0.6

    )

    return environment

# Instantiate the environment

env = create\_eval\_env({

    "window\_size": 25,

    "y": fourier\_gbm(price=100, mu=0.01, sigma=0.5, dt=0.01, n=1000, order=5)

})

# Run until episode ends

episode\_reward = 0

done = False

obs = env.reset()

while not done:

    action = agent.compute\_action(obs)

    obs, reward, done, info = env.step(action)

    episode\_reward += reward

```

The following are a few examples of the rendering that came from the evaluation environment.

![_images/eval_01.png](_images/eval_01.png)png

![_images/eval_02.png](_images/eval_02.png)png

![_images/eval_03.png](_images/eval_03.png)png

![_images/eval_04.png](_images/eval_04.png)png

As you can see, the agent has been able to make correct decisions on some of the price curves, but not all of them. The last curve shows some of the shortcomings of the agent. The agent seemed to have stop making decisions to move its wealth to capitalize on the changes in price. In the first three, however, it was able to make those decisions. The reason for this is most likely the change in the frequency of the curve. The last chart has a price curve that is volatile, containing many local maxima and minima as opposed to the first three charts.

  

**What have we learned?**  

* Make an environment in TT.

* Create a custom `ActionScheme`, `RewardScheme`, and `Renderer` in TT.

* Using a simple price curve to understand more about actions and rewards in our use case.

* Using `ray` to train and restore an agent.

* Making evaluation environments for providing insight into the decisions of an agent.

See you in the next tutorial!

Components[¶](#components "Permalink to this headline")

-------------------------------------------------------

TensorTrade is built around modular components that together make up a trading strategy. Trading strategies combine reinforcement learning agents with composable trading logic in the form of a `gym` environment. A trading environment is made up of a set of modular components that can be mixed and matched to create highly diverse trading and investment strategies.

Just like electrical components, the purpose of TensorTrade components is to be able to mix and match them as necessary.

Action Scheme[¶](#action-scheme "Permalink to this headline")

-------------------------------------------------------------

An `ActionScheme` defines the action space of the environment and interprets the action of an agent and how it gets applied to the environment.

For example, if we were using a discrete action space of 3 actions (0 = hold, 1 = buy 100 %, 2 = sell 100%), our learning agent does not need to know that returning an action of 1 is equivalent to buying an instrument. Rather, the agent needs to know the reward for returning an action of 1 in specific circumstances, and can leave the implementation details of converting actions to trades to the `ActionScheme`.

Each action scheme has a `perform` method, which will interpret the agent’s specified action into a change in the environmental state. It is often necessary to store additional state within the scheme, for example to keep track of the currently traded position. This state should be reset each time the action scheme’s reset method is called, which is done automatically when the parent `TradingEnv` is reset.

### What is an Action?[¶](#what-is-an-action "Permalink to this headline")

This is a review of what was mentioned inside of the overview section and explains how a RL operates. You’ll better understand what an action is in context of an observation space and reward. At the same time, hopefully this will be a proper refresher.

An action is a predefined value of how the machine should move inside of the world. To better summarize, its a *command that a player would give inside of a video game in respose to a stimuli*. The commands usually come in the form of an `action\_space`. An `action\_space` defines the rules for how a user is allowed to act inside of an environment. While it might not be easily interpretable by humans, it can easily be interpreted by a machine.

Let’s look at a good example. Let’s say we’re trying to balance a cart with a pole on it (cartpole). We can choose to move the cart left and right. This is a `Discrete(2)` action space.

* 0 - Push cart to the left

* 1 - Push cart to the right

When we get the action from the agent, the environment will see that number instead of a name.

![_images/cartpole.gif](_images/cartpole.gif)Watch Link Run Around In Circles

An `ActionScheme` supports any type of action space that subclasses `Space` from `gym`. For example, here is an implementation of an action space that represents a probability simplex.

```

import numpy as np

from gym.spaces import Space

class Simplex(Space):

    def \_\_init\_\_(self, k: int) -> None:

        assert k >= 2

        super().\_\_init\_\_(shape=(k, ), dtype=np.float32)

        self.k = k

    def sample(self) -> float:

        return np.random.dirichlet(alpha=self.k\*[3\*np.random.random()])

    def contains(self, x) -> bool:

        if len(x) != self.k:

            return False

        if sum(x) != 1.0:

            return False

        return True

```

### Default[¶](#default "Permalink to this headline")

The default TensorTrade action scheme is made to be compatible with the built-in order management system (OMS). The OMS is a system that is able to have orders be submitted to it for particular financial instruments.

#### Simple[¶](#simple "Permalink to this headline")

  

**Overview**  

A discrete action scheme that determines actions based on a list of

trading pairs, order criteria, and trade sizes.

  

**Action Space**  

The action space is a discrete set of N options. The total number of discrete actions is the product of

* criteria (order criteria for order creation/completion)

* trade sizes (e.g. 1/4, 1/2, 1/3)

* trade durations (e.g. order open for 30 seconds or 60 seconds)

* trade sides (i.e. Buy or Sell)

* the number of tradeable pairs (i.e. BTC/USDT, ETH/BTC, etc)

  

**Perform**  

Performs as per TensorTradeActionScheme, creates order based on models discrete output and submits it to the broker. The state action mapping varies with the parameters above.

#### ManagedRisk[¶](#managedrisk "Permalink to this headline")

  

**Overview**  

A discrete action scheme that determines actions based on managing risk,

through setting a follow-up stop loss and take profit on every order.

  

**Action Space**  

The action space is a discrete set of N options for the model to take. The total number of discrete actions is determined by taking a product of:

* stop percents (i.e. [0.02, 0.04, 0.06] percent changes to trigger a stop loss)

* take percents (i.e. [0.02, 0.03] value percent changes to take profit at)

* trade sizes (e.g. 1/4, 1/2, 1/3)

* trade durations (e.g. order open for 30 seconds or 60 seconds)

* trade sides (i.e. Buy or Sell)

* the number of tradable pairs (i.e. BTC/USDT, ETH/BTC, etc)

  

**Perform**  

Performs as per TensorTradeActionScheme, creates order based on models discrete output and submits it to the broker. The state action mapping varies with the parameters above.

#### BSH[¶](#bsh "Permalink to this headline")

  

 **Overview**   

The buy/sell/hold (BSH) action scheme was made to capture the simplest type of

action space that can be made. If the agent is in state 0, then all of its net worth

is located in our `cash` wallet (e.g. USD). If the agent is in state 1, then all of

its net worth is located in our `asset` wallet (e.g. BTC).

  

 **Action Space**   

* `Discrete(2)` options, buy or sell

  

 **Perform**   

Below is a table that shows the mapping `(state, action) -> (state)`.   

| State | Action | Meaning |

| --- | --- | --- |

| 0 | 0 | Keep net worth in `cash` wallet (HOLD) |

| 0 | 1 | Transition net worth from `cash` wallet to `asset` wallet (BUY) |

| 1 | 0 | Transition net worth from `asset` wallet to `cash` wallet. (SELL) |

| 1 | 1 | Keep net worth in `asset` wallet (HOLD) |

Reward Scheme[¶](#reward-scheme "Permalink to this headline")

-------------------------------------------------------------

Reward schemes receive the `TradingEnv` at each time step and return a `float`, corresponding to the benefit of that specific action. For example, if the action taken this step was a sell that resulted in positive profits, our `RewardScheme` could return a positive number to encourage more trades like this. On the other hand, if the action was a sell that resulted in a loss, the scheme could return a negative reward to teach the agent not to make similar actions in the future.

A version of this example algorithm is implemented in `SimpleProfit`, however more complex schemes can obviously be used instead.

Each reward scheme has a `reward` method, which takes in the `TradingEnv` at each time step and returns a `float` corresponding to the value of that action. As with action schemes, it is often necessary to store additional state within a reward scheme for various reasons. This state should be reset each time the reward scheme’s reset method is called, which is done automatically when the environment is reset.

Ultimately the agent creates a sequence of actions to maximize its total reward over a given time. The `RewardScheme` is an abstract class that encapsulates how to tell the trading bot in `tensortrade` if it’s trading positively or negatively over time. The same methods will be called each time for each step, and we can directly swap out compatible schemes.

```

from tensortrade.env.default.rewards import SimpleProfit

reward\_scheme = SimpleProfit()

```

*The simple profit scheme returns a reward of -1 for not holding a trade, 1 for holding a trade, 2 for purchasing an instrument, and a value corresponding to the (positive/negative) profit earned by a trade if an instrument was sold.*

### Default[¶](#default "Permalink to this headline")

These are the default reward schemes.

---

#### Simple Profit[¶](#simple-profit "Permalink to this headline")

A reward scheme that rewards the agent for profitable trades and prioritizes trading over not trading.

  

**Overview**  

The simple profit scheme needs to keep a history of profit over time. The way it does this is through looking at the portfolio as a means of keeping track of how the portfolio moves. This is seen inside of the `get\_reward` function.

  

**Computing Reward**  

  

**Compatibility**  

---

#### Risk Adjusted Returns[¶](#risk-adjusted-returns "Permalink to this headline")

A reward scheme that rewards the agent for increasing its net worth, while penalizing more volatile strategies.

  

**Overview**  

When trading you often are not just looking at the overall returns of your model. You’re also looking at the overall volatility of your trading strategy over time compared to other metrics. The two major strategies here are the sharpe and sortino ratio.

The **sharpe ratio** looks at the overall movements of the portfolio and generates a penalty for massive movements through a lower score. This includes major movements towards the upside and downside.

![_images/sharpe.png](_images/sharpe.png)Sharpe Ratio

The **sortino ratio** takes the same idea, though it focuses more on penalizing only the upside. That means it’ll give a huge score for moments when the price moves upward, and will only give a negative score when the price drops heavily. This is a great direction for the RL algorithm. Seeing that we don’t want to incur heavy downsides, yet want to take on large upsides, using this metric alone gives us lots of progress to mititgate downsides and increase upsides.

![_images/sortino.png](_images/sortino.png)Sortino Ratio

  

**Computing Reward**  

Given the choice of `return\_algorithm` the reward is computed using the `risk\_free\_rate` and the `target\_returns` parameters.

  

**Compatibility**  

---

Observer[¶](#observer "Permalink to this headline")

---------------------------------------------------

The `Observer` component is what the environment uses to represent the way the agent sees the environment. The way it is built in the `default` environment is with the help of the `DataFeed`. There were many reasons for this decision, but the most important ones are that we would like to be able to compute path-dependent observations in a reliable way. We would also like to minimize lookahead biases and we would also like it to translate well into the live setting as well. To leave the opportunities broad, however, all you need to do is fill out the `observe` method to determine what your agent sees next.

Default[¶](#default "Permalink to this headline")

-------------------------------------------------

The `default` observer at the moment uses a structure of a look-back window in order to create an observation. After the `feed` is made the environment will use a window of past observations and will have the shape `(window\_size, n\_features)`.

IntradayObserver[¶](#intradayobserver "Permalink to this headline")

-------------------------------------------------------------------

The `IntradayObserver` divides the DataFeed into episodes of single trading days. It takes the same parameters as the `default` observer and additional parameters of `stop\_time` of type `datetime.time` and `randomize` of type `bool`. `stop\_time` is the `datetime.time` of the `timestamp` in the `DataFrame` that marks the end of the episode. It is imperative to ensure that each trading day includes the respective `timestamp`. `randomize` determines if the episode, or trading day, should be selected randomly or in the sequence of the `DataFeed`. The `IntradayObserver` requires that the `DataFeed` include a `Stream` of timestamps named `'timestamp'`.

Stopper[¶](#stopper "Permalink to this headline")

-------------------------------------------------

The `Stopper` component just evaluates whether or not the environment is done running after each `step` in the environment. For example, right now the `default` environment just evaluate if the environment is done based on the profit loss of the agent. If the profit loss drops below a certain level the environment will be done. In addition, if the `feed` runs out of data to give the environment will also be done for that episode.

Informer[¶](#informer "Permalink to this headline")

---------------------------------------------------

The `Informer` component just delivers contextual environment information after each `step` in the environment. For example, right now the `default` environment just delivers the `portfolio`, `broker`, and `net\_worth` in the step functions.

Renderer[¶](#renderer "Permalink to this headline")

---------------------------------------------------

The `Renderer` is the component of the `TradingEnv` that lets us peek into the thoughts and actions of an agent. There are many different ways to render this type of environment, but all you need to do in order to get a different renderering is to subclass `Renderer` and fill in the `render` method. If you want to see more on how to make a `Renderer` from scratch check out the tutorial for using `ray` with TensorTrade.

### Default[¶](#default "Permalink to this headline")

The `default` renderers are made to work with any instance of the `BaseRenderer`

class.

---

#### Screen Logger[¶](#screen-logger "Permalink to this headline")

Logs the records of the environment to the screen for the user to see.

---

#### File Logger[¶](#file-logger "Permalink to this headline")

Logs the records of the environment to a specified file.

---

#### Plotly Trading Chart[¶](#plotly-trading-chart "Permalink to this headline")

Uses plotly to make a rendering of the environment. This renderer only works for when the action scheme involves trading one asset. The data required for the `render\_feed` must include the date, open, high, low, close, and volume of the instrument being traded.

![_images/plotly.png](_images/plotly.png)png

  

**References**  

* https://plot.ly/python-api-reference/generated/plotly.graph\_objects.Figure.html

* https://plot.ly/python/figurewidget/

* https://plot.ly/python/subplots/

* https://plot.ly/python/reference/#candlestick

* https://plot.ly/python/#chart-events

---

Overview[¶](#overview "Permalink to this headline")

---------------------------------------------------

A trading environment is a reinforcement learning environment that follows OpenAI’s `gym.Env` specification. This allows us to leverage many of the existing reinforcement learning models in our trading agent, if we’d like.

`TradingEnv` steps through the various interfaces from the `tensortrade` library in a consistent way, and will likely not change too often as all other parts of `tensortrade` changes. We’re going to go through an overview of the Trading environment below.

Trading environments are fully configurable gym environments with highly composable components:

* The `ActionScheme` interprets and applies the agent’s actions to the environment.

* The `RewardScheme` computes the reward for each time step based on the agent’s performance.

* The `Observer` generates the next observation for the agent.

* The `Stopper` determines whether or not the episode is over.

* The `Informer` generates useful monitoring information at each time step.

* The `Renderer` renders a view of the environment and interactions.

That’s all there is to it, now it’s just a matter of composing each of these components into a complete environment.

When the reset method of a `TradingEnv` is called, all of the child components will also be reset. The internal state of each action scheme, reward scheme, observer, stopper, and informer will be set back to their default values, ready for the next episode.

What if I can’t make a particular environment?[¶](#what-if-i-can-t-make-a-particular-environment "Permalink to this headline")

------------------------------------------------------------------------------------------------------------------------------

If none of the environments available in codebase serve your needs let us know! We would love to hear about so we can keep improving the quality of our framework as well as keeping up with the needs of the people using it.

Overview[¶](#overview "Permalink to this headline")

---------------------------------------------------

The `feed` package provides useful tools when building trading environments. The primary reason for using this package is to help build the mechanisms that generate observations from an environment. Therefore, it is fitting that their primary location of use is in the `Observer` component. The `Stream` API provides the granularity needed to connect specific data sources to the `Observer`.

What is a `Stream`?[¶](#what-is-a-stream "Permalink to this headline")

----------------------------------------------------------------------

A `Stream` is the basic building block for the `DataFeed`, which is also a stream itself. Each stream has a name and a data type and they can be set after the stream is created. Streams can be created through the following mechanisms:

* generators

* iterables

* sensors

* direct implementation of `Stream`

For example, if you wanted to make a stream for a simple counter. We will make it such that it will start at 0 and increment by 1 each time it is called and on `reset` will set the count back to 0. The following code accomplishes this functionality through creating a generator function.

```

from tensortrade.feed import Stream

def counter():

    i = 0

    while True:

        yield i

        i += 1

s = Stream.source(counter)

```

In addition, you can also use the built-in `count` generator from the `itertools` package.

```

from itertools import count

s = Stream.source(count(start=0, step=1))

```

These will all create infinite streams that will keep incrementing by 1 to infinity. If you wanted to make something that counted until some finite number you can use the built in `range` function.

```

s = Stream.source(range(5))

```

This can also be done by giving in a `list` directly.

```

s = Stream.source([1, 2, 3, 4, 5])

```

The direct approach to stream creation is by subclassing `Stream` and implementing the `forward`, `has\_next`, and `reset` methods. If the stream does not hold stateful information, then `reset` is not required to be implemented and can be ignored.

```

class Counter(Stream):

    def \_\_init\_\_(self):

        super().\_\_init\_\_()

        self.count = None

    def forward(self):

        if self.count is None:

            self.count = 0

        else:

            self.count += 1

        return self.count

    def has\_next(self):

        return True

    def reset(self):

        self.count = None

s = Counter()

```

There is also a way of creating streams which serves the purpose of watching a particular object and how it changes over time. This can be done through the `sensor` function. For example, we can use this to directly track performance statistics on our `portfolio`. Here is a specific example of how we can use it to track the number of orders the are currently active inside the order management system.

```

from tensortrade.env.default.actions import SimpleOrders

action\_scheme = SimpleOrders()

s = Stream.sensor(action\_scheme.broker, lambda b: len(b.unexecuted))

```

As the agent and the environment are interacting with one another, this stream will be able to monitor the number of active orders being handled by the broker. This stream can then be used by either computing performance statistics and supplying them to a `Renderer` or simply by including it within the observation space.

Now that we have seen the different ways we can create streams, we need to understand the ways in which we can aggregate new streams from old. This is where the data type of a stream becomes important.

Using Data Types[¶](#using-data-types "Permalink to this headline")

-------------------------------------------------------------------

The purpose of the data type of a stream, `dtype`, is to add additional functionality and behavior to a stream such that it can be aggregated with other streams of the same type in an easy and intuitive way. For example, what if the number of executed orders from the `broker` is not important by itself, but is important with respect to the current time of the process. This can be taken into account if we create a stream for keeping count of the active orders and another one for keeping track of the step in the process. Here is what that would look like.

```

from itertools import count

from tensortrade.feed import Stream

from tensortrade.env.default.actions import SimpleOrders

n = Stream.source(count(0, step=1), dtype="float")

n\_active = Stream.sensor(action\_scheme.broker, lambda b: len(b.unexecuted), dtype="float")

s = (n\_active / (n + 1)).rename("avg\_n\_active")

```

Suppose we find that this is not a useful statistic and instead would like to know how many of the active order have been filled since the last time step. This can be done by using the `lag` operator on our stream and finding the difference between the current count and the count from the last time step.

```

n\_active = Stream.sensor(action\_scheme.broker, lambda b: len(b.unexecuted), dtype="float")

s = (n\_active - n\_active.lag()).rename("n\_filled")

```

As you can see from the code above, we were able to make more complex streams by using simple ones. Take note, however, in the way we use the `rename` function. We only really want to rename a stream if we will be using it somewhere else where its name will be useful (e.g. in our `feed`). We do not want to name all the intermediate streams that are used to build our final statistic because the code will become too cumbersome and annoying. To avoid these complications, streams are created to automatically generate a unique name on instantiation. We leave the naming for the user to decide which streams are useful to name.

Since the most common data type is `float` in these tasks, the following is a list of supported special operations for it:

* Let `s`, `s1`, `s2` be streams.

* Let `c` be a constant.

* Let `n` be a number.

* Unary:

	+ `-s`, `s.neg()`

	+ `abs(s)`, `s.abs()`

	+ `s\*\*2`, `pow(s, n)`

* Binary:

	+ `s1 + s2`, `s1.add(s2)`, `s + c`, `c + s`

	+ `s1 - s2`, `s1.sub(s2)`, `s - c`, `c - s`

	+ `s1 \* s2`, `s1.mul(s2)`, `s \* c`, `c \* s`

	+ `s1 / s2`, `s1.div(s2)`, `s / c`, `c / s`

There are many more useful functions that can be utilized, too many to list in fact. You can find all of the. however, in the API reference section of the documentation.

Advanced Usages[¶](#advanced-usages "Permalink to this headline")

-----------------------------------------------------------------

The `Stream` API is very robust and can handle complex streaming operations, particularly for the `float` data type. Some of the more advanced usages include performance tracking and developing reward schemes for the `default` trading environment. In the following example, we will show how to track the net worth of a portfolio. This implementation will be coming directly from the wallets that are defined in the `portfolio`.

```

# Suppose we have an already constructed portfolio object, `portfolio`.

worth\_streams = []

for wallet in portfolio.wallets:

    total\_balance = Stream.sensor(

        wallet,

        lambda w: w.total\_balance.as\_float(),

        dtype="float"

    )

    symbol = w.instrument.symbol

    if symbol == portfolio.base\_instrument.symbol

        worth\_streams += [total\_balance]

    else:

        price = Stream.select(

            w.exchange.streams(),

            lambda s: s.name.endswith(symbol)

        )

        worth\_streams += [(price \* total\_balance)]

net\_worth = Stream.reduce(worth\_streams).sum().rename("net\_worth")

```

Overview[¶](#overview "Permalink to this headline")

---------------------------------------------------

An `order management system (OMS)` is a system that controls how an order for a

specific financial instrument is filled. In building an OMS, you have to make clear

what the lifecycle of an order is. The OMS we use in the default environment for

TensorTrade is a first attempt at building such a system. The goal of our system,

however, was meant to serve the purpose simulating a real order management system.

We created it with the user in mind, hoping to give maximum customization the types

of order placed.

Portfolio[¶](#portfolio "Permalink to this headline")

-----------------------------------------------------

A [portfolio](https://www.investopedia.com/terms/p/portfolio.asp) is a collection of financial investments like stocks, bonds, commodities, cash, and cash equivalents, including closed-end funds and exchange-traded funds (ETFs). Now a portfolio can include more than just these types of assets. For example, real-estate is an investment that can be considered to be part of a portfolio. For the purposes of algorithmic trading, however, a more formal definition of a portfolio is needed. In order for that to be done we first need to define what a financial instrument is and how it fits in with the idea of a portfolio.

  

 **Instruments**   

The core idea surrounding a financial instrument is the idea of tradability. In our universe, an object is said to be tradable if and only if can be traded on an exchange. This definition makes the idea more concrete and solves some ambiguity that can arise when multiple exchanges are involved. For example, Bitcoin (BTC) is an asset that you can hold an amount of, however, its value depends on the exchange that you are trading it on. Therefore, given an `Exchange` we need to be able hold a `Quantity` of an `Instrument`. Now enters the idea for a `Wallet`.

A `Quantity` of an instrument can be created with the following code

```

from tensortrade.oms.instruments import Quantity, USD, BTC

q = 10000 \* USD

q = Quantity(BTC, 10000)

```

  

 **Wallets**   

A `Wallet` is specified by an `Exchange` and a `Quantity`. The financial instrument that the wallet holds is implicitly defined in the `Quantity` we are holding in the wallet. The wallet also gives us the ability to transfer funds from a given wallet to another.

```

# Suppose we have already defined an exchange that supports the financial instrument

# we are creating.

from tensortrade.oms.instruments import USD, BTC

from tensortrade.oms.wallets import Wallet

w1 = Wallet(exchange, 10000 \* USD)

w2 = Wallet(exchange, 0 \* BTC)

```

  

 **Creating a Portfolio**   

A `Portfolio` in the library is defined to be a set of wallets. This makes building a portfolio rather simple. All we need to do is create the wallets and pass them in to the `Portfolio` for construction.

```

# Suppose we have already defined two exchange `e1` and `e2`.

from tensortrade.oms.instruments import USD, BTC, ETH, LTC

from tensortrade.oms.wallets import Wallet, Portfolio

portfolio = Portfolio(

    base\_instrument=USD,

    wallets=[

        Wallet(e1, 10000 \* USD),

        Wallet(e1, 0 \* BTC),

        Wallet(e1, 0 \* ETH),

        Wallet(e2, 10 \* USD),

        Wallet(e2, 0 \* ETH),

        Wallet(e2, 0 \* LTC),

    ]

)

```

In addition, you also have to specify what the base instrument is so the portfolio knows what every instruments value should be in.

Orders[¶](#orders "Permalink to this headline")

-----------------------------------------------

An `Order` is the way in which you can move funds from one wallet to another. The supported orders that can be made right now are the following:

* Market

* Limit

* Stop Loss

* Take Profit

Currently all the `default` action schemes use these orders when interpreting agent actions. The stop loss and take profit orders are the most complicated of which and require the use of an `OrderSpec` for them to function properly. An `OrderSpec` is required when an order must be connected with and followed by a successive order. In the case of a stop order, the process is to buy the quantity requested at the current price and then wait until the price hits a particular mark and then sell it. In addition, an `Order` has an optional `criteria` parameter that needs to be satisfied before being able to execute on an exchange.

Overview[¶](#overview "Permalink to this headline")

---------------------------------------------------

This is where the “deep” part of the deep reinforcement learning framework come in. Learning agents are where the math (read: magic) happens.

At each time step, the agent takes the observation from the environment as input, runs it through its underlying model (a neural network most of the time), and outputs the action to take. For example, the observation might be the previous `open`, `high`, `low`, and `close` price from the exchange. The learning model would take these values as input and output a value corresponding to the action to take, such as `buy`, `sell`, or `hold`.

It is important to remember the learning model has no intuition of the prices or trades being represented by these values. Rather, the model is simply learning which values to output for specific input values or sequences of input values, to earn the highest reward.

In this example, we will be using the Stable Baselines library to provide learning agents to our trading scheme, however, the TensorTrade framework is compatible with many reinforcement learning libraries such as Tensorforce, Ray’s RLLib, OpenAI’s Baselines, Intel’s Coach, or anything from the TensorFlow line such as TF Agents.

It is possible that custom TensorTrade learning agents will be added to this framework in the future, though it will always be a goal of the framework to be interoperable with as many existing reinforcement learning libraries as possible, since there is so much concurrent growth in the space.

But for now, Stable Baselines is simple and powerful enough for our needs.

[Ray](https://docs.ray.io/en/latest/rllib.html)[¶](#ray "Permalink to this headline")

-------------------------------------------------------------------------------------

The following is an example of how to train a strategy on `ray` using the `PPO`

algorithm.

```

import ray

import numpy as np

from ray import tune

from ray.tune.registry import register\_env

import tensortrade.env.default as default

from tensortrade.feed.core import DataFeed, Stream

from tensortrade.oms.instruments import Instrument

from tensortrade.oms.exchanges import Exchange

from tensortrade.oms.services.execution.simulated import execute\_order

from tensortrade.oms.wallets import Wallet, Portfolio

USD = Instrument("USD", 2, "U.S. Dollar")

TTC = Instrument("TTC", 8, "TensorTrade Coin")

def create\_env(config):

    x = np.arange(0, 2\*np.pi, 2\*np.pi / 1000)

    p = Stream.source(50\*np.sin(3\*x) + 100, dtype="float").rename("USD-TTC")

    bitfinex = Exchange("bitfinex", service=execute\_order)(

        p

    )

    cash = Wallet(bitfinex, 100000 \* USD)

    asset = Wallet(bitfinex, 0 \* TTC)

    portfolio = Portfolio(USD, [

        cash,

        asset

    ])

    feed = DataFeed([

        p,

        p.rolling(window=10).mean().rename("fast"),

        p.rolling(window=50).mean().rename("medium"),

        p.rolling(window=100).mean().rename("slow"),

        p.log().diff().fillna(0).rename("lr")

    ])

    reward\_scheme = default.rewards.PBR(price=p)

    action\_scheme = default.actions.BSH(

        cash=cash,

        asset=asset

    ).attach(reward\_scheme)

    env = default.create(

        feed=feed,

        portfolio=portfolio,

        action\_scheme=action\_scheme,

        reward\_scheme=reward\_scheme,

        window\_size=config["window\_size"],

        max\_allowed\_loss=0.6

    )

    return env

register\_env("TradingEnv", create\_env)

analysis = tune.run(

    "PPO",

    stop={

      "episode\_reward\_mean": 500

    },

    config={

        "env": "TradingEnv",

        "env\_config": {

            "window\_size": 25

        },

        "log\_level": "DEBUG",

        "framework": "torch",

        "ignore\_worker\_failures": True,

        "num\_workers": 1,

        "num\_gpus": 0,

        "clip\_rewards": True,

        "lr": 8e-6,

        "lr\_schedule": [

            [0, 1e-1],

            [int(1e2), 1e-2],

            [int(1e3), 1e-3],

            [int(1e4), 1e-4],

            [int(1e5), 1e-5],

            [int(1e6), 1e-6],

            [int(1e7), 1e-7]

        ],

        "gamma": 0,

        "observation\_filter": "MeanStdFilter",

        "lambda": 0.72,

        "vf\_loss\_coeff": 0.5,

        "entropy\_coeff": 0.01

    },

    checkpoint\_at\_end=True

)

```

And then to restore the agent just use the following code.

```

import ray.rllib.agents.ppo as ppo

# Get checkpoint

checkpoints = analysis.get\_trial\_checkpoints\_paths(

    trial=analysis.get\_best\_trial("episode\_reward\_mean"),

    metric="episode\_reward\_mean"

)

checkpoint\_path = checkpoints[0][0]

# Restore agent

agent = ppo.PPOTrainer(

    env="TradingEnv",

    config={

        "env\_config": {

            "window\_size": 25

        },

        "framework": "torch",

        "log\_level": "DEBUG",

        "ignore\_worker\_failures": True,

        "num\_workers": 1,

        "num\_gpus": 0,

        "clip\_rewards": True,

        "lr": 8e-6,

        "lr\_schedule": [

            [0, 1e-1],

            [int(1e2), 1e-2],

            [int(1e3), 1e-3],

            [int(1e4), 1e-4],

            [int(1e5), 1e-5],

            [int(1e6), 1e-6],

            [int(1e7), 1e-7]

        ],

        "gamma": 0,

        "observation\_filter": "MeanStdFilter",

        "lambda": 0.72,

        "vf\_loss\_coeff": 0.5,

        "entropy\_coeff": 0.01

    }

)

agent.restore(checkpoint\_path)

```

[Stable Baselines](https://stable-baselines.readthedocs.io/en/master/)[¶](#stable-baselines "Permalink to this headline")

-------------------------------------------------------------------------------------------------------------------------

```

from stable\_baselines.common.policies import MlpLnLstmPolicy

from stable\_baselines import PPO2

model = PPO2

policy = MlpLnLstmPolicy

params = { "learning\_rate": 1e-5 }

agent = model(policy, environment, model\_kwargs=params)

```

[Tensorforce](https://tensorforce.readthedocs.io/en/0.4.4)[¶](#tensorforce "Permalink to this headline")

--------------------------------------------------------------------------------------------------------

I will also quickly cover the Tensorforce library to show how simple it is to switch between reinforcement learning frameworks.

```

from tensorforce.agents import Agent

agent\_spec = {

    "type": "ppo\_agent",

    "step\_optimizer": {

        "type": "adam",

        "learning\_rate": 1e-4

    },

    "discount": 0.99,

    "likelihood\_ratio\_clipping": 0.2,

}

network\_spec = [

    dict(type='dense', size=64, activation="tanh"),

    dict(type='dense', size=32, activation="tanh")

]

agent = Agent.from\_spec(spec=agent\_spec,

                        kwargs=dict(network=network\_spec,

                                    states=environment.states,

                                    actions=environment.actions))

```

*If you would like to know more about Tensorforce agents, you can view the* [Documentation.](https://tensorforce.readthedocs.io/en/0.4.4)

tensortrade[¶](#tensortrade "Permalink to this headline")

---------------------------------------------------------

### tensortrade package[¶](#module-tensortrade "Permalink to this headline")

#### Subpackages[¶](#subpackages "Permalink to this headline")

##### tensortrade.agents package[¶](#module-tensortrade.agents "Permalink to this headline")

###### Subpackages[¶](#subpackages "Permalink to this headline")

####### tensortrade.agents.parallel package[¶](#module-tensortrade.agents.parallel "Permalink to this headline")

######## Submodules[¶](#submodules "Permalink to this headline")

######### tensortrade.agents.parallel.parallel\_dqn\_agent module[¶](#module-tensortrade.agents.parallel.parallel_dqn_agent "Permalink to this headline")

*class* `tensortrade.agents.parallel.parallel_dqn_agent.``ParallelDQNAgent`(*create\_env: Callable[[None], TradingEnvironment], model: tensortrade.agents.parallel.parallel\_dqn\_model.ParallelDQNModel = None*)[[source]](_modules/tensortrade/agents/parallel/parallel_dqn_agent.html#ParallelDQNAgent)[¶](#tensortrade.agents.parallel.parallel_dqn_agent.ParallelDQNAgent "Permalink to this definition")

Bases: [`tensortrade.agents.agent.Agent`](index.html#tensortrade.agents.agent.Agent "tensortrade.agents.agent.Agent")

`get_action`(*state: numpy.ndarray*, *\*\*kwargs*) → int[[source]](_modules/tensortrade/agents/parallel/parallel_dqn_agent.html#ParallelDQNAgent.get_action)[¶](#tensortrade.agents.parallel.parallel_dqn_agent.ParallelDQNAgent.get_action "Permalink to this definition")

Get an action for a specific state in the environment.

`restore`(*path: str*, *\*\*kwargs*)[[source]](_modules/tensortrade/agents/parallel/parallel_dqn_agent.html#ParallelDQNAgent.restore)[¶](#tensortrade.agents.parallel.parallel_dqn_agent.ParallelDQNAgent.restore "Permalink to this definition")

Restore the agent from the file specified in path.

`save`(*path: str*, *\*\*kwargs*)[[source]](_modules/tensortrade/agents/parallel/parallel_dqn_agent.html#ParallelDQNAgent.save)[¶](#tensortrade.agents.parallel.parallel_dqn_agent.ParallelDQNAgent.save "Permalink to this definition")

Save the agent to the directory specified in path.

`train`(*n\_steps: int = None*, *n\_episodes: int = None*, *save\_every: int = None*, *save\_path: str = None*, *callback: callable = None*, *\*\*kwargs*) → float[[source]](_modules/tensortrade/agents/parallel/parallel_dqn_agent.html#ParallelDQNAgent.train)[¶](#tensortrade.agents.parallel.parallel_dqn_agent.ParallelDQNAgent.train "Permalink to this definition")

Train the agent in the environment and return the mean reward.

`update_networks`(*model: tensortrade.agents.parallel.parallel\_dqn\_model.ParallelDQNModel*)[[source]](_modules/tensortrade/agents/parallel/parallel_dqn_agent.html#ParallelDQNAgent.update_networks)[¶](#tensortrade.agents.parallel.parallel_dqn_agent.ParallelDQNAgent.update_networks "Permalink to this definition")

`update_target_network`()[[source]](_modules/tensortrade/agents/parallel/parallel_dqn_agent.html#ParallelDQNAgent.update_target_network)[¶](#tensortrade.agents.parallel.parallel_dqn_agent.ParallelDQNAgent.update_target_network "Permalink to this definition")

######### tensortrade.agents.parallel.parallel\_dqn\_model module[¶](#module-tensortrade.agents.parallel.parallel_dqn_model "Permalink to this headline")

*class* `tensortrade.agents.parallel.parallel_dqn_model.``ParallelDQNModel`(*create\_env: Callable[[], TradingEnvironment], policy\_network: <sphinx.ext.autodoc.importer.\_MockObject object at 0x7f517eab6390> = None*)[[source]](_modules/tensortrade/agents/parallel/parallel_dqn_model.html#ParallelDQNModel)[¶](#tensortrade.agents.parallel.parallel_dqn_model.ParallelDQNModel "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

`get_action`(*state: numpy.ndarray*, *\*\*kwargs*) → int[[source]](_modules/tensortrade/agents/parallel/parallel_dqn_model.html#ParallelDQNModel.get_action)[¶](#tensortrade.agents.parallel.parallel_dqn_model.ParallelDQNModel.get_action "Permalink to this definition")

`restore`(*path: str*, *\*\*kwargs*)[[source]](_modules/tensortrade/agents/parallel/parallel_dqn_model.html#ParallelDQNModel.restore)[¶](#tensortrade.agents.parallel.parallel_dqn_model.ParallelDQNModel.restore "Permalink to this definition")

`save`(*path: str*, *\*\*kwargs*)[[source]](_modules/tensortrade/agents/parallel/parallel_dqn_model.html#ParallelDQNModel.save)[¶](#tensortrade.agents.parallel.parallel_dqn_model.ParallelDQNModel.save "Permalink to this definition")

`update_networks`(*model: tensortrade.agents.parallel.parallel\_dqn\_model.ParallelDQNModel*)[[source]](_modules/tensortrade/agents/parallel/parallel_dqn_model.html#ParallelDQNModel.update_networks)[¶](#tensortrade.agents.parallel.parallel_dqn_model.ParallelDQNModel.update_networks "Permalink to this definition")

`update_target_network`()[[source]](_modules/tensortrade/agents/parallel/parallel_dqn_model.html#ParallelDQNModel.update_target_network)[¶](#tensortrade.agents.parallel.parallel_dqn_model.ParallelDQNModel.update_target_network "Permalink to this definition")

######### tensortrade.agents.parallel.parallel\_dqn\_optimizer module[¶](#module-tensortrade.agents.parallel.parallel_dqn_optimizer "Permalink to this headline")

*class* `tensortrade.agents.parallel.parallel_dqn_optimizer.``ParallelDQNOptimizer`(*model: ParallelDQNModel*, *n\_envs: int*, *memory\_queue: multiprocessing.context.BaseContext.Queue*, *model\_update\_queue: multiprocessing.context.BaseContext.Queue*, *done\_queue: multiprocessing.context.BaseContext.Queue*, *discount\_factor: float = 0.9999*, *batch\_size: int = 128*, *learning\_rate: float = 0.0001*, *memory\_capacity: int = 10000*)[[source]](_modules/tensortrade/agents/parallel/parallel_dqn_optimizer.html#ParallelDQNOptimizer)[¶](#tensortrade.agents.parallel.parallel_dqn_optimizer.ParallelDQNOptimizer "Permalink to this definition")

Bases: `multiprocessing.context.Process`

`run`()[[source]](_modules/tensortrade/agents/parallel/parallel_dqn_optimizer.html#ParallelDQNOptimizer.run)[¶](#tensortrade.agents.parallel.parallel_dqn_optimizer.ParallelDQNOptimizer.run "Permalink to this definition")

Method to be run in sub-process; can be overridden in sub-class

######### tensortrade.agents.parallel.parallel\_dqn\_trainer module[¶](#module-tensortrade.agents.parallel.parallel_dqn_trainer "Permalink to this headline")

*class* `tensortrade.agents.parallel.parallel_dqn_trainer.``ParallelDQNTrainer`(*agent: ParallelDQNAgent, create\_env: Callable[[None], TrainingEnvironment], memory\_queue: multiprocessing.context.BaseContext.Queue, model\_update\_queue: multiprocessing.context.BaseContext.Queue, done\_queue: multiprocessing.context.BaseContext.Queue, n\_steps: int, n\_episodes: int, eps\_end: int = 0.05, eps\_start: int = 0.99, eps\_decay\_steps: int = 2000, update\_target\_every: int = 2*)[[source]](_modules/tensortrade/agents/parallel/parallel_dqn_trainer.html#ParallelDQNTrainer)[¶](#tensortrade.agents.parallel.parallel_dqn_trainer.ParallelDQNTrainer "Permalink to this definition")

Bases: `multiprocessing.context.Process`

`run`()[[source]](_modules/tensortrade/agents/parallel/parallel_dqn_trainer.html#ParallelDQNTrainer.run)[¶](#tensortrade.agents.parallel.parallel_dqn_trainer.ParallelDQNTrainer.run "Permalink to this definition")

Method to be run in sub-process; can be overridden in sub-class

######### tensortrade.agents.parallel.parallel\_queue module[¶](#module-tensortrade.agents.parallel.parallel_queue "Permalink to this headline")

*class* `tensortrade.agents.parallel.parallel_queue.``ParallelQueue`[[source]](_modules/tensortrade/agents/parallel/parallel_queue.html#ParallelQueue)[¶](#tensortrade.agents.parallel.parallel_queue.ParallelQueue "Permalink to this definition")

Bases: `multiprocessing.queues.Queue`

A portable implementation of multiprocessing.Queue.

Because of multithreading / multiprocessing semantics, Queue.qsize() may

raise the NotImplementedError exception on Unix platforms like Mac OS X

where sem\_getvalue() is not implemented. This subclass addresses this

problem by using a synchronized shared counter (initialized to zero) and

increasing / decreasing its value every time the put() and get() methods

are called, respectively. This not only prevents NotImplementedError from

being raised, but also allows us to implement a reliable version of both

qsize() and empty().

`empty`() → bool[[source]](_modules/tensortrade/agents/parallel/parallel_queue.html#ParallelQueue.empty)[¶](#tensortrade.agents.parallel.parallel_queue.ParallelQueue.empty "Permalink to this definition")

Reliable implementation of multiprocessing.Queue.empty().

`get`(*\*args*, *\*\*kwargs*) → object[[source]](_modules/tensortrade/agents/parallel/parallel_queue.html#ParallelQueue.get)[¶](#tensortrade.agents.parallel.parallel_queue.ParallelQueue.get "Permalink to this definition")

`put`(*\*args*, *\*\*kwargs*) → None[[source]](_modules/tensortrade/agents/parallel/parallel_queue.html#ParallelQueue.put)[¶](#tensortrade.agents.parallel.parallel_queue.ParallelQueue.put "Permalink to this definition")

`qsize`() → int[[source]](_modules/tensortrade/agents/parallel/parallel_queue.html#ParallelQueue.qsize)[¶](#tensortrade.agents.parallel.parallel_queue.ParallelQueue.qsize "Permalink to this definition")

Reliable implementation of multiprocessing.Queue.qsize().

*class* `tensortrade.agents.parallel.parallel_queue.``SharedCounter`(*n: int = 0*)[[source]](_modules/tensortrade/agents/parallel/parallel_queue.html#SharedCounter)[¶](#tensortrade.agents.parallel.parallel_queue.SharedCounter "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

A synchronized shared counter.

The locking done by multiprocessing.Value ensures that only a single

process or thread may read or write the in-memory ctypes object. However,

in order to do n += 1, Python performs a read followed by a write, so a

second process may read the old value before the new one is written by the

first process. The solution is to use a multiprocessing.Lock to guarantee

the atomicity of the modifications to Value.

| Parameters: | **n** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The count to start at. |

References

| [1] | <http://eli.thegreenplace.net/2012/01/04/shared-counter-with-pythons-multiprocessing/> |

`increment`(*n: int = 1*) → None[[source]](_modules/tensortrade/agents/parallel/parallel_queue.html#SharedCounter.increment)[¶](#tensortrade.agents.parallel.parallel_queue.SharedCounter.increment "Permalink to this definition")

Increment the counter by n.

| Parameters: | **n** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The amount to increment the counter by. |

`value`[¶](#tensortrade.agents.parallel.parallel_queue.SharedCounter.value "Permalink to this definition")

The value of the counter. (int, read-only)

###### Submodules[¶](#submodules "Permalink to this headline")

####### tensortrade.agents.a2c\_agent module[¶](#module-tensortrade.agents.a2c_agent "Permalink to this headline")

References

* <http://inoryy.com/post/tensorflow2-deep-reinforcement-learning/#agent-interface>

*class* `tensortrade.agents.a2c_agent.``A2CAgent`(*env: TradingEnvironment*, *shared\_network: <sphinx.ext.autodoc.importer.\_MockObject object at 0x7f517eab40d0> = None*, *actor\_network: <sphinx.ext.autodoc.importer.\_MockObject object at 0x7f517eab4190> = None*, *critic\_network: <sphinx.ext.autodoc.importer.\_MockObject object at 0x7f517eab4210> = None*)[[source]](_modules/tensortrade/agents/a2c_agent.html#A2CAgent)[¶](#tensortrade.agents.a2c_agent.A2CAgent "Permalink to this definition")

Bases: [`tensortrade.agents.agent.Agent`](index.html#tensortrade.agents.agent.Agent "tensortrade.agents.agent.Agent")

`get_action`(*state: numpy.ndarray*, *\*\*kwargs*) → int[[source]](_modules/tensortrade/agents/a2c_agent.html#A2CAgent.get_action)[¶](#tensortrade.agents.a2c_agent.A2CAgent.get_action "Permalink to this definition")

Get an action for a specific state in the environment.

`restore`(*path: str*, *\*\*kwargs*)[[source]](_modules/tensortrade/agents/a2c_agent.html#A2CAgent.restore)[¶](#tensortrade.agents.a2c_agent.A2CAgent.restore "Permalink to this definition")

Restore the agent from the file specified in path.

`save`(*path: str*, *\*\*kwargs*)[[source]](_modules/tensortrade/agents/a2c_agent.html#A2CAgent.save)[¶](#tensortrade.agents.a2c_agent.A2CAgent.save "Permalink to this definition")

Save the agent to the directory specified in path.

`train`(*n\_steps: int = None*, *n\_episodes: int = None*, *save\_every: int = None*, *save\_path: str = None*, *callback: callable = None*, *\*\*kwargs*) → float[[source]](_modules/tensortrade/agents/a2c_agent.html#A2CAgent.train)[¶](#tensortrade.agents.a2c_agent.A2CAgent.train "Permalink to this definition")

Train the agent in the environment and return the mean reward.

*class* `tensortrade.agents.a2c_agent.``A2CTransition`(*state*, *action*, *reward*, *done*, *value*)[¶](#tensortrade.agents.a2c_agent.A2CTransition "Permalink to this definition")

Bases: [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)")

`action`[¶](#tensortrade.agents.a2c_agent.A2CTransition.action "Permalink to this definition")

Alias for field number 1

`done`[¶](#tensortrade.agents.a2c_agent.A2CTransition.done "Permalink to this definition")

Alias for field number 3

`reward`[¶](#tensortrade.agents.a2c_agent.A2CTransition.reward "Permalink to this definition")

Alias for field number 2

`state`[¶](#tensortrade.agents.a2c_agent.A2CTransition.state "Permalink to this definition")

Alias for field number 0

`value`[¶](#tensortrade.agents.a2c_agent.A2CTransition.value "Permalink to this definition")

Alias for field number 4

####### tensortrade.agents.agent module[¶](#module-tensortrade.agents.agent "Permalink to this headline")

*class* `tensortrade.agents.agent.``Agent`[[source]](_modules/tensortrade/agents/agent.html#Agent)[¶](#tensortrade.agents.agent.Agent "Permalink to this definition")

Bases: [`tensortrade.core.base.Identifiable`](index.html#tensortrade.core.base.Identifiable "tensortrade.core.base.Identifiable")

`get_action`(*state: numpy.ndarray*, *\*\*kwargs*) → int[[source]](_modules/tensortrade/agents/agent.html#Agent.get_action)[¶](#tensortrade.agents.agent.Agent.get_action "Permalink to this definition")

Get an action for a specific state in the environment.

`restore`(*path: str*, *\*\*kwargs*)[[source]](_modules/tensortrade/agents/agent.html#Agent.restore)[¶](#tensortrade.agents.agent.Agent.restore "Permalink to this definition")

Restore the agent from the file specified in path.

`save`(*path: str*, *\*\*kwargs*)[[source]](_modules/tensortrade/agents/agent.html#Agent.save)[¶](#tensortrade.agents.agent.Agent.save "Permalink to this definition")

Save the agent to the directory specified in path.

`train`(*n\_steps: int = None*, *n\_episodes: int = 10000*, *save\_every: int = None*, *save\_path: str = None*, *callback: callable = None*, *\*\*kwargs*) → float[[source]](_modules/tensortrade/agents/agent.html#Agent.train)[¶](#tensortrade.agents.agent.Agent.train "Permalink to this definition")

Train the agent in the environment and return the mean reward.

####### tensortrade.agents.dqn\_agent module[¶](#module-tensortrade.agents.dqn_agent "Permalink to this headline")

*class* `tensortrade.agents.dqn_agent.``DQNAgent`(*env: TradingEnv*, *policy\_network: <sphinx.ext.autodoc.importer.\_MockObject object at 0x7f517e88eb10> = None*)[[source]](_modules/tensortrade/agents/dqn_agent.html#DQNAgent)[¶](#tensortrade.agents.dqn_agent.DQNAgent "Permalink to this definition")

Bases: [`tensortrade.agents.agent.Agent`](index.html#tensortrade.agents.agent.Agent "tensortrade.agents.agent.Agent")

> 

> * <https://towardsdatascience.com/deep-reinforcement-learning-build-a-deep-q-network-dqn-to-play-cartpole-with-tensorflow-2-and-gym-8e105744b998>

> * <https://pytorch.org/tutorials/intermediate/reinforcement_q_learning.html#dqn-algorithm>

> 

> 

> 

`get_action`(*state: numpy.ndarray*, *\*\*kwargs*) → int[[source]](_modules/tensortrade/agents/dqn_agent.html#DQNAgent.get_action)[¶](#tensortrade.agents.dqn_agent.DQNAgent.get_action "Permalink to this definition")

Get an action for a specific state in the environment.

`restore`(*path: str*, *\*\*kwargs*)[[source]](_modules/tensortrade/agents/dqn_agent.html#DQNAgent.restore)[¶](#tensortrade.agents.dqn_agent.DQNAgent.restore "Permalink to this definition")

Restore the agent from the file specified in path.

`save`(*path: str*, *\*\*kwargs*)[[source]](_modules/tensortrade/agents/dqn_agent.html#DQNAgent.save)[¶](#tensortrade.agents.dqn_agent.DQNAgent.save "Permalink to this definition")

Save the agent to the directory specified in path.

`train`(*n\_steps: int = None*, *n\_episodes: int = None*, *save\_every: int = None*, *save\_path: str = None*, *callback: callable = None*, *\*\*kwargs*) → float[[source]](_modules/tensortrade/agents/dqn_agent.html#DQNAgent.train)[¶](#tensortrade.agents.dqn_agent.DQNAgent.train "Permalink to this definition")

Train the agent in the environment and return the mean reward.

*class* `tensortrade.agents.dqn_agent.``DQNTransition`(*state*, *action*, *reward*, *next\_state*, *done*)[¶](#tensortrade.agents.dqn_agent.DQNTransition "Permalink to this definition")

Bases: [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)")

`action`[¶](#tensortrade.agents.dqn_agent.DQNTransition.action "Permalink to this definition")

Alias for field number 1

`done`[¶](#tensortrade.agents.dqn_agent.DQNTransition.done "Permalink to this definition")

Alias for field number 4

`next_state`[¶](#tensortrade.agents.dqn_agent.DQNTransition.next_state "Permalink to this definition")

Alias for field number 3

`reward`[¶](#tensortrade.agents.dqn_agent.DQNTransition.reward "Permalink to this definition")

Alias for field number 2

`state`[¶](#tensortrade.agents.dqn_agent.DQNTransition.state "Permalink to this definition")

Alias for field number 0

####### tensortrade.agents.replay\_memory module[¶](#module-tensortrade.agents.replay_memory "Permalink to this headline")

*class* `tensortrade.agents.replay_memory.``ReplayMemory`(*capacity: int*, *transition\_type: collections.namedtuple = <class 'tensortrade.agents.replay\_memory.Transition'>*)[[source]](_modules/tensortrade/agents/replay_memory.html#ReplayMemory)[¶](#tensortrade.agents.replay_memory.ReplayMemory "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

`head`(*batch\_size*) → List[collections.namedtuple][[source]](_modules/tensortrade/agents/replay_memory.html#ReplayMemory.head)[¶](#tensortrade.agents.replay_memory.ReplayMemory.head "Permalink to this definition")

`push`(*\*args*)[[source]](_modules/tensortrade/agents/replay_memory.html#ReplayMemory.push)[¶](#tensortrade.agents.replay_memory.ReplayMemory.push "Permalink to this definition")

`sample`(*batch\_size*) → List[collections.namedtuple][[source]](_modules/tensortrade/agents/replay_memory.html#ReplayMemory.sample)[¶](#tensortrade.agents.replay_memory.ReplayMemory.sample "Permalink to this definition")

`tail`(*batch\_size*) → List[collections.namedtuple][[source]](_modules/tensortrade/agents/replay_memory.html#ReplayMemory.tail)[¶](#tensortrade.agents.replay_memory.ReplayMemory.tail "Permalink to this definition")

*class* `tensortrade.agents.replay_memory.``Transition`(*state*, *action*, *reward*, *done*)[¶](#tensortrade.agents.replay_memory.Transition "Permalink to this definition")

Bases: [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)")

`action`[¶](#tensortrade.agents.replay_memory.Transition.action "Permalink to this definition")

Alias for field number 1

`done`[¶](#tensortrade.agents.replay_memory.Transition.done "Permalink to this definition")

Alias for field number 3

`reward`[¶](#tensortrade.agents.replay_memory.Transition.reward "Permalink to this definition")

Alias for field number 2

`state`[¶](#tensortrade.agents.replay_memory.Transition.state "Permalink to this definition")

Alias for field number 0

##### tensortrade.contrib package[¶](#module-tensortrade.contrib "Permalink to this headline")

##### tensortrade.core package[¶](#module-tensortrade.core "Permalink to this headline")

###### Submodules[¶](#submodules "Permalink to this headline")

####### tensortrade.core.base module[¶](#module-tensortrade.core.base "Permalink to this headline")

Responsible for the basic classes in the project.

`tensortrade.core.base.``global_clock`[¶](#tensortrade.core.base.global_clock "Permalink to this definition")

A clock that provides a global reference for all objects that share a

timeline.

| Type: | Clock |

*class* `tensortrade.core.base.``Identifiable`[[source]](_modules/tensortrade/core/base.html#Identifiable)[¶](#tensortrade.core.base.Identifiable "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

Identifiable mixin for adding a unique id property to instances of a class.

`id`[¶](#tensortrade.core.base.Identifiable.id "Permalink to this definition")

Gets the identifier for the object.

| Returns: | *str* – The identifier for the object. |

*class* `tensortrade.core.base.``Observable`[[source]](_modules/tensortrade/core/base.html#Observable)[¶](#tensortrade.core.base.Observable "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

An object with some value that can be observed.

An object to which a listener can be attached to and be alerted about on

an event happening.

`listeners`[¶](#tensortrade.core.base.Observable.listeners "Permalink to this definition")

A list of listeners that the object will alert on events occurring.

| Type: | list of listeners |

`attach`(*listener*)[[source]](_modules/tensortrade/core/base.html#Observable.attach)[¶](#tensortrade.core.base.Observable.attach "Permalink to this definition")

Adds a listener to receive alerts.

`detach`(*listener*)[[source]](_modules/tensortrade/core/base.html#Observable.detach)[¶](#tensortrade.core.base.Observable.detach "Permalink to this definition")

Removes a listener from receiving alerts.

`attach`(*listener*) → tensortrade.core.base.Observable[[source]](_modules/tensortrade/core/base.html#Observable.attach)

Adds a listener to receive alerts.

| Parameters: | **listener** (*a listener object*) –  |

| Returns: | Observable – The observable being called. |

`detach`(*listener*) → tensortrade.core.base.Observable[[source]](_modules/tensortrade/core/base.html#Observable.detach)

Removes a listener from receiving alerts.

| Parameters: | **listener** (*a listener object*) –  |

| Returns: | Observable – The observable being called. |

*class* `tensortrade.core.base.``TimeIndexed`[[source]](_modules/tensortrade/core/base.html#TimeIndexed)[¶](#tensortrade.core.base.TimeIndexed "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

A class for objects that are indexed by time.

`clock`[¶](#tensortrade.core.base.TimeIndexed.clock "Permalink to this definition")

Gets the clock associated with this object.

| Returns: | Clock – The clock associated with this object. |

*class* `tensortrade.core.base.``TimedIdentifiable`[[source]](_modules/tensortrade/core/base.html#TimedIdentifiable)[¶](#tensortrade.core.base.TimedIdentifiable "Permalink to this definition")

Bases: [`tensortrade.core.base.Identifiable`](#tensortrade.core.base.Identifiable "tensortrade.core.base.Identifiable"), [`tensortrade.core.base.TimeIndexed`](#tensortrade.core.base.TimeIndexed "tensortrade.core.base.TimeIndexed")

A class an identifiable object embedded in a time process.

`created_at`[¶](#tensortrade.core.base.TimedIdentifiable.created_at "Permalink to this definition")

The time at which this object was created according to its associated

clock.

| Type: | datetime.datetime |

`clock`[¶](#tensortrade.core.base.TimedIdentifiable.clock "Permalink to this definition")

Gets the clock associated with the object.

| Returns: | Clock – The clock associated with the object. |

####### tensortrade.core.clock module[¶](#module-tensortrade.core.clock "Permalink to this headline")

*class* `tensortrade.core.clock.``Clock`[[source]](_modules/tensortrade/core/clock.html#Clock)[¶](#tensortrade.core.clock.Clock "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

A class to track the time for a process.

`start`[¶](#tensortrade.core.clock.Clock.start "Permalink to this definition")

The time of start for the clock.

| Type: | [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") |

`step`[¶](#tensortrade.core.clock.Clock.step "Permalink to this definition")

The time of the process the clock is at currently.

| Type: | [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") |

`now`(*format=None*)[[source]](_modules/tensortrade/core/clock.html#Clock.now)[¶](#tensortrade.core.clock.Clock.now "Permalink to this definition")

Gets the current time in the provided format.

`increment`()[[source]](_modules/tensortrade/core/clock.html#Clock.increment)[¶](#tensortrade.core.clock.Clock.increment "Permalink to this definition")

Increments the clock by specified time increment.

`reset`()[[source]](_modules/tensortrade/core/clock.html#Clock.reset)[¶](#tensortrade.core.clock.Clock.reset "Permalink to this definition")

Resets the clock.

`increment`() → None[[source]](_modules/tensortrade/core/clock.html#Clock.increment)

Increments the clock by specified time increment.

`now`(*format: str = None*) → datetime.datetime[[source]](_modules/tensortrade/core/clock.html#Clock.now)

Gets the current time in the provided format.

:param format: The format to put the current time into.

:type format: str or None, optional

| Returns: | *datetime* – The current time. |

`reset`() → None[[source]](_modules/tensortrade/core/clock.html#Clock.reset)

Resets the clock.

####### tensortrade.core.component module[¶](#module-tensortrade.core.component "Permalink to this headline")

*class* `tensortrade.core.component.``Component`[[source]](_modules/tensortrade/core/component.html#Component)[¶](#tensortrade.core.component.Component "Permalink to this definition")

Bases: [`abc.ABC`](https://docs.python.org/3/library/abc.html#abc.ABC "(in Python v3.9)"), [`tensortrade.core.component.ContextualizedMixin`](#tensortrade.core.component.ContextualizedMixin "tensortrade.core.component.ContextualizedMixin"), [`tensortrade.core.base.Identifiable`](index.html#tensortrade.core.base.Identifiable "tensortrade.core.base.Identifiable")

The main class for setting up components to be used in the TradingEnv.

This class if responsible for providing a common way in which different

components of the library can be created. Specifically, it enables the

creation of components from a TradingContext. Therefore making the creation

of complex environments simpler where there are only a few things that

need to be changed from case to case.

`registered_name`[¶](#tensortrade.core.component.Component.registered_name "Permalink to this definition")

The name under which constructor arguments are to be given in a dictionary

and passed to a TradingContext.

| Type: | [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") |

*classmethod* `__init_subclass__`(*\*\*kwargs*) → None[[source]](_modules/tensortrade/core/component.html#Component.__init_subclass__)[¶](#tensortrade.core.component.Component.__init_subclass__ "Permalink to this definition")

Constructs the concrete subclass of Component.

In constructing the subclass, the concrete subclass is also registered

into the project level registry.

| Parameters: | **kwargs** (*keyword arguments*) – The keyword arguments to be provided to the concrete subclass of Component

to create an instance. |

`default`(*key: str*, *value: Any*, *kwargs: dict = None*) → Any[[source]](_modules/tensortrade/core/component.html#Component.default)[¶](#tensortrade.core.component.Component.default "Permalink to this definition")

Resolves which defaults value to use for construction.

A concrete subclass will use this method to resolve which default value

it should use when creating an instance. The default value should go to

the value specified for the variable within the TradingContext. If that

one is not provided it will resolve to value.

| Parameters: | * **key** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The name of the attribute to be resolved for the class.

* **value** (*any*) – The value the attribute should be set to if not provided in the

TradingContext.

* **kwargs** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)")*,* *optional*) – The dictionary to search through for the value associated with key.

 |

`registered_name` *= None*

*class* `tensortrade.core.component.``ContextualizedMixin`[[source]](_modules/tensortrade/core/component.html#ContextualizedMixin)[¶](#tensortrade.core.component.ContextualizedMixin "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

A mixin that is to be mixed with any class that must function in a

contextual setting.

`context`[¶](#tensortrade.core.component.ContextualizedMixin.context "Permalink to this definition")

Gets the Context the object is under.

| Returns: | Context – The context the object is under. |

*class* `tensortrade.core.component.``InitContextMeta`[[source]](_modules/tensortrade/core/component.html#InitContextMeta)[¶](#tensortrade.core.component.InitContextMeta "Permalink to this definition")

Bases: [`abc.ABCMeta`](https://docs.python.org/3/library/abc.html#abc.ABCMeta "(in Python v3.9)")

Metaclass that executes \_\_init\_\_ of instance in it’s core.

This class works with the TradingContext class to ensure the correct

data is being given to the instance created by a concrete class that has

subclassed Component.

`__call__`(*\*args*, *\*\*kwargs*) → tensortrade.core.component.InitContextMeta[[source]](_modules/tensortrade/core/component.html#InitContextMeta.__call__)[¶](#tensortrade.core.component.InitContextMeta.__call__ "Permalink to this definition")

| Parameters: | * **args** – positional arguments to give constructor of subclass of Component

* **kwargs** – keyword arguments to give constructor of subclass of Component

 |

| Returns: | Component – An instance of a concrete class the subclasses Component |

####### tensortrade.core.context module[¶](#module-tensortrade.core.context "Permalink to this headline")

*class* `tensortrade.core.context.``Context`(*\*\*kwargs*)[[source]](_modules/tensortrade/core/context.html#Context)[¶](#tensortrade.core.context.Context "Permalink to this definition")

Bases: [`collections.UserDict`](https://docs.python.org/3/library/collections.html#collections.UserDict "(in Python v3.9)")

A context that is injected into every instance of a class that is

a subclass of Component.

*class* `tensortrade.core.context.``TradingContext`(*config: dict*)[[source]](_modules/tensortrade/core/context.html#TradingContext)[¶](#tensortrade.core.context.TradingContext "Permalink to this definition")

Bases: [`collections.UserDict`](https://docs.python.org/3/library/collections.html#collections.UserDict "(in Python v3.9)")

A class for objects that put themselves in a Context using

the with statement.

The implementation for this class is heavily borrowed from the pymc3

library and adapted with the design goals of TensorTrade in mind.

| Parameters: | **config** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)")) – The configuration holding the information for each Component. |

`from_json`(*path*)[[source]](_modules/tensortrade/core/context.html#TradingContext.from_json)[¶](#tensortrade.core.context.TradingContext.from_json "Permalink to this definition")

Creates a TradingContext from a json file.

`from_yaml`(*path*)[[source]](_modules/tensortrade/core/context.html#TradingContext.from_yaml)[¶](#tensortrade.core.context.TradingContext.from_yaml "Permalink to this definition")

Creates a TradingContext from a yaml file.

Warning

If there is a conflict in the contexts of different components because

they were initialized under different contexts, can have undesirable effects.

Therefore, a warning should be made to the user indicating that using

components together that have conflicting contexts can lead to unwanted

behavior.

References

[1] <https://github.com/pymc-devs/pymc3/blob/master/pymc3/model.py>

`__enter__`() → tensortrade.core.context.TradingContext[[source]](_modules/tensortrade/core/context.html#TradingContext.__enter__)[¶](#tensortrade.core.context.TradingContext.__enter__ "Permalink to this definition")

Adds a new TradingContext to the context stack.

This method is used for a with statement and adds a TradingContext

to the context stack. The new context on the stack is then used by every

class that subclasses Component the initialization of its instances.

| Returns: | TradingContext – The context associated with the given with statement. |

`__exit__`(*typ*, *value*, *traceback*) → None[[source]](_modules/tensortrade/core/context.html#TradingContext.__exit__)[¶](#tensortrade.core.context.TradingContext.__exit__ "Permalink to this definition")

Pops the first TradingContext of the stack.

| Parameters: | * **typ** ([*type*](https://docs.python.org/3/library/functions.html#type "(in Python v3.9)")) – The type of Exception

* **value** (Exception) – An instance of typ.

* **traceback** (*python traceback object*) – The traceback object associated with the exception.

 |

`contexts` *= <\_thread.\_local object>*[¶](#tensortrade.core.context.TradingContext.contexts "Permalink to this definition")

*classmethod* `from_json`(*path: str*) → tensortrade.core.context.TradingContext[[source]](_modules/tensortrade/core/context.html#TradingContext.from_json)

Creates a TradingContext from a json file.

| Parameters: | **path** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The path to locate the json file. |

| Returns: | TradingContext – A trading context with all the variables provided in the json file. |

*classmethod* `from_yaml`(*path: str*) → tensortrade.core.context.TradingContext[[source]](_modules/tensortrade/core/context.html#TradingContext.from_yaml)

Creates a TradingContext from a yaml file.

| Parameters: | **path** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The path to locate the yaml file. |

| Returns: | TradingContext – A trading context with all the variables provided in the yaml file. |

*classmethod* `get_context`() → tensortrade.core.context.TradingContext[[source]](_modules/tensortrade/core/context.html#TradingContext.get_context)[¶](#tensortrade.core.context.TradingContext.get_context "Permalink to this definition")

Gets the first context on the stack.

| Returns: | TradingContext – The first context on the stack. |

*classmethod* `get_contexts`() → List[tensortrade.core.context.TradingContext][[source]](_modules/tensortrade/core/context.html#TradingContext.get_contexts)[¶](#tensortrade.core.context.TradingContext.get_contexts "Permalink to this definition")

Gets the stack of trading contexts.

| Returns: | *List[‘TradingContext’]* – The stack of trading contexts. |

`shared`[¶](#tensortrade.core.context.TradingContext.shared "Permalink to this definition")

The shared values in common for all components involved with the

TradingContext.

| Returns: | *dict* – Shared values for components under the TradingContext. |

####### tensortrade.core.exceptions module[¶](#module-tensortrade.core.exceptions "Permalink to this headline")

Holds all the exceptions for the project.

*exception* `tensortrade.core.exceptions.``DoubleLockedQuantity`(*quantity: Quantity*, *\*args*)[[source]](_modules/tensortrade/core/exceptions.html#DoubleLockedQuantity)[¶](#tensortrade.core.exceptions.DoubleLockedQuantity "Permalink to this definition")

Bases: [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception "(in Python v3.9)")

Raised when a locked Quantity is trying to get locked again.

| Parameters: | * **quantity** (Quantity) – A locked quantity.

* **\*args** (*positional arguments*) – More positional arguments for the exception.

 |

*exception* `tensortrade.core.exceptions.``DoubleUnlockedQuantity`(*quantity: Quantity*, *\*args*)[[source]](_modules/tensortrade/core/exceptions.html#DoubleUnlockedQuantity)[¶](#tensortrade.core.exceptions.DoubleUnlockedQuantity "Permalink to this definition")

Bases: [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception "(in Python v3.9)")

Raised when a free Quantity is trying to get unlocked.

| Parameters: | * **quantity** (Quantity) – A unlocked quantity.

* **\*args** (*positional arguments*) – More positional arguments for the exception.

 |

*exception* `tensortrade.core.exceptions.``IncompatibleInstrumentOperation`(*left: Quantity*, *right: Quantity*, *\*args*)[[source]](_modules/tensortrade/core/exceptions.html#IncompatibleInstrumentOperation)[¶](#tensortrade.core.exceptions.IncompatibleInstrumentOperation "Permalink to this definition")

Bases: [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception "(in Python v3.9)")

Raised when two quantities with different instruments occurs.

| Parameters: | * **left** (Quantity) – The left argument of the operation.

* **right** (Quantity) – The right argument of the operation.

* **\*args** (*positional arguments*) – More positional arguments for the exception.

 |

*exception* `tensortrade.core.exceptions.``InsufficientFunds`(*balance: Quantity*, *size: Quantity*, *\*args*)[[source]](_modules/tensortrade/core/exceptions.html#InsufficientFunds)[¶](#tensortrade.core.exceptions.InsufficientFunds "Permalink to this definition")

Bases: [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception "(in Python v3.9)")

Raised when requested funds are greater than the free balance of a Wallet

| Parameters: | * **balance** (Quantity) – The balance of the Wallet where funds are being allocated from.

* **size** (Quantity) – The amount being requested for allocation.

* **\*args** (*positional arguments*) – More positional arguments for the exception.

 |

*exception* `tensortrade.core.exceptions.``InvalidNegativeQuantity`(*size: float*, *\*args*)[[source]](_modules/tensortrade/core/exceptions.html#InvalidNegativeQuantity)[¶](#tensortrade.core.exceptions.InvalidNegativeQuantity "Permalink to this definition")

Bases: [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception "(in Python v3.9)")

Raised when a Quantity tries to be instantiated with a negative amount.

| Parameters: | * **size** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The size that was specified for the Quantity.

* **\*args** (*positional arguments*) – More positional arguments for the exception.

 |

*exception* `tensortrade.core.exceptions.``InvalidNonNumericQuantity`(*size: Union[float, int, numbers.Number], \*args*)[[source]](_modules/tensortrade/core/exceptions.html#InvalidNonNumericQuantity)[¶](#tensortrade.core.exceptions.InvalidNonNumericQuantity "Permalink to this definition")

Bases: [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception "(in Python v3.9)")

Raised when a Quantity tries to be instantiated with a value

that is not numeric.

| Parameters: | * **size** (Union[float, int, Number]) – The value that was specified for the Quantity.

* **\*args** (*positional arguments*) – More positional arguments for the exception.

 |

*exception* `tensortrade.core.exceptions.``InvalidOrderQuantity`(*quantity: Quantity*, *\*args*)[[source]](_modules/tensortrade/core/exceptions.html#InvalidOrderQuantity)[¶](#tensortrade.core.exceptions.InvalidOrderQuantity "Permalink to this definition")

Bases: [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception "(in Python v3.9)")

Raised when an Order with a non-negative amount is placed

| Parameters: | * **quantity** (Quantity) – An invalid order quantity.

* **\*args** (*positional arguments*) – More positional arguments for the exception.

 |

*exception* `tensortrade.core.exceptions.``InvalidTradingPair`(*base: Instrument*, *quote: Instrument*, *\*args*)[[source]](_modules/tensortrade/core/exceptions.html#InvalidTradingPair)[¶](#tensortrade.core.exceptions.InvalidTradingPair "Permalink to this definition")

Bases: [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception "(in Python v3.9)")

Raised when an invalid trading pair is trying to be created.

| Parameters: | * **base** (*'Instrument'*) – The base instrument of the pair.

* **quote** (*'Instrument'*) – The quote instrument of the pair.

* **\*args** (*positional arguments*) – More positional arguments for the exception.

 |

*exception* `tensortrade.core.exceptions.``QuantityNotLocked`(*quantity: Quantity*, *\*args*)[[source]](_modules/tensortrade/core/exceptions.html#QuantityNotLocked)[¶](#tensortrade.core.exceptions.QuantityNotLocked "Permalink to this definition")

Bases: [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception "(in Python v3.9)")

Raised when a locked Quantity does not have a path\_id in the Wallet

it is trying to be unlocked in.

| Parameters: | * **quantity** (Quantity) – A locked quantity.

* **\*args** (*positional arguments*) – More positional arguments for the exception.

 |

*exception* `tensortrade.core.exceptions.``QuantityOpPathMismatch`(*left\_id: str*, *right\_id: str*, *\*args*)[[source]](_modules/tensortrade/core/exceptions.html#QuantityOpPathMismatch)[¶](#tensortrade.core.exceptions.QuantityOpPathMismatch "Permalink to this definition")

Bases: [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception "(in Python v3.9)")

Raised when an operation tries to occur between quantities that are not

under the same path\_id.

| Parameters: | * **left\_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The path\_id for the left argument in the operation.

* **right\_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The path\_id for the right argument in the operation.

* **\*args** (*positional arguments*) – More positional arguments for the exception.

 |

####### tensortrade.core.registry module[¶](#module-tensortrade.core.registry "Permalink to this headline")

This module hold the project level registry and provides methods to mutate

and change the registry.

`tensortrade.core.registry.``MAJOR_COMPONENTS`[¶](#tensortrade.core.registry.MAJOR_COMPONENTS "Permalink to this definition")

The list of the major components that can be injected into.

| Type: | List[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")] |

`tensortrade.core.registry.``register`(*component: Component*, *registered\_name: str*) → None[[source]](_modules/tensortrade/core/registry.html#register)[¶](#tensortrade.core.registry.register "Permalink to this definition")

Registers a component into the registry

| Parameters: | * **component** (*'Component'*) – The component to be registered.

* **registered\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The name to be associated with the registered component.

 |

`tensortrade.core.registry.``registry`() → dict[[source]](_modules/tensortrade/core/registry.html#registry)[¶](#tensortrade.core.registry.registry "Permalink to this definition")

Gets the project level registry.

| Returns: | *dict* – The project level registry. |

##### tensortrade.data package[¶](#module-tensortrade.data "Permalink to this headline")

###### Submodules[¶](#submodules "Permalink to this headline")

####### tensortrade.data.cdd module[¶](#module-tensortrade.data.cdd "Permalink to this headline")

Contains methods and classes to collect data from

<https://www.cryptodatadownload.com>.

*class* `tensortrade.data.cdd.``CryptoDataDownload`[[source]](_modules/tensortrade/data/cdd.html#CryptoDataDownload)[¶](#tensortrade.data.cdd.CryptoDataDownload "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

Provides methods for retrieving data on different cryptocurrencies from

<https://www.cryptodatadownload.com/cdd/>.

`url`[¶](#tensortrade.data.cdd.CryptoDataDownload.url "Permalink to this definition")

The url for collecting data from CryptoDataDownload.

| Type: | [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") |

`fetch`(*exchange\_name*, *base\_symbol*, *quote\_symbol*, *timeframe*, *include\_all\_volumes=False*)[[source]](_modules/tensortrade/data/cdd.html#CryptoDataDownload.fetch)[¶](#tensortrade.data.cdd.CryptoDataDownload.fetch "Permalink to this definition")

Fetches data for different exchanges and cryptocurrency pairs.

`fetch`(*exchange\_name: str*, *base\_symbol: str*, *quote\_symbol: str*, *timeframe: str*, *include\_all\_volumes: bool = False*) → pandas.core.frame.DataFrame[[source]](_modules/tensortrade/data/cdd.html#CryptoDataDownload.fetch)

Fetches data for different exchanges and cryptocurrency pairs.

| Parameters: | * **exchange\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The name of the exchange.

* **base\_symbol** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The base symbol fo the cryptocurrency pair.

* **quote\_symbol** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The quote symbol fo the cryptocurrency pair.

* **timeframe** (*{"d"**,* *"h"**,* *"m"}*) – The timeframe to collect data from.

* **include\_all\_volumes** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *optional*) – Whether or not to include both base and quote volume.

 |

| Returns: | pd.DataFrame – A open, high, low, close and volume for the specified exchange and

cryptocurrency pair. |

`fetch_default`(*exchange\_name: str*, *base\_symbol: str*, *quote\_symbol: str*, *timeframe: str*, *include\_all\_volumes: bool = False*) → pandas.core.frame.DataFrame[[source]](_modules/tensortrade/data/cdd.html#CryptoDataDownload.fetch_default)[¶](#tensortrade.data.cdd.CryptoDataDownload.fetch_default "Permalink to this definition")

Fetches data from all exchanges that match the evaluation structure.

| Parameters: | * **exchange\_name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The name of the exchange.

* **base\_symbol** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The base symbol fo the cryptocurrency pair.

* **quote\_symbol** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The quote symbol fo the cryptocurrency pair.

* **timeframe** (*{"d"**,* *"h"**,* *"m"}*) – The timeframe to collect data from.

* **include\_all\_volumes** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *optional*) – Whether or not to include both base and quote volume.

 |

| Returns: | pd.DataFrame – A open, high, low, close and volume for the specified exchange and

cryptocurrency pair. |

`fetch_gemini`(*base\_symbol: str*, *quote\_symbol: str*, *timeframe: str*) → pandas.core.frame.DataFrame[[source]](_modules/tensortrade/data/cdd.html#CryptoDataDownload.fetch_gemini)[¶](#tensortrade.data.cdd.CryptoDataDownload.fetch_gemini "Permalink to this definition")

Fetches data from the gemini exchange.

| Parameters: | * **base\_symbol** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The base symbol fo the cryptocurrency pair.

* **quote\_symbol** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The quote symbol fo the cryptocurrency pair.

* **timeframe** (*{"d"**,* *"h"**,* *"m"}*) – The timeframe to collect data from.

 |

| Returns: | pd.DataFrame – A open, high, low, close and volume for the specified

cryptocurrency pair. |

##### tensortrade.env package[¶](#module-tensortrade.env "Permalink to this headline")

###### Subpackages[¶](#subpackages "Permalink to this headline")

####### tensortrade.env.default package[¶](#module-tensortrade.env.default "Permalink to this headline")

`tensortrade.env.default.``create`(*portfolio: tensortrade.oms.wallets.portfolio.Portfolio, action\_scheme: Union[tensortrade.env.default.actions.TensorTradeActionScheme, str], reward\_scheme: Union[tensortrade.env.default.rewards.TensorTradeRewardScheme, str], feed: tensortrade.feed.core.feed.DataFeed, window\_size: int = 1, min\_periods: int = None, \*\*kwargs*) → tensortrade.env.generic.environment.TradingEnv[[source]](_modules/tensortrade/env/default.html#create)[¶](#tensortrade.env.default.create "Permalink to this definition")

Creates the default TradingEnv of the project to be used in training

RL agents.

| Parameters: | * **portfolio** (Portfolio) – The portfolio to be used by the environment.

* **action\_scheme** (actions.TensorTradeActionScheme or str) – The action scheme for computing actions at every step of an episode.

* **reward\_scheme** (rewards.TensorTradeRewardScheme or str) – The reward scheme for computing rewards at every step of an episode.

* **feed** (DataFeed) – The feed for generating observations to be used in the look back

window.

* **window\_size** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The size of the look back window to use for the observation space.

* **min\_periods** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *optional*) – The minimum number of steps to warm up the feed.

* **\*\*kwargs** (*keyword arguments*) – Extra keyword arguments needed to build the environment.

 |

| Returns: | TradingEnv – The default trading environment. |

######## Submodules[¶](#submodules "Permalink to this headline")

######### tensortrade.env.default.actions module[¶](#module-tensortrade.env.default.actions "Permalink to this headline")

*class* `tensortrade.env.default.actions.``BSH`(*cash: Wallet*, *asset: Wallet*)[[source]](_modules/tensortrade/env/default/actions.html#BSH)[¶](#tensortrade.env.default.actions.BSH "Permalink to this definition")

Bases: [`tensortrade.env.default.actions.TensorTradeActionScheme`](#tensortrade.env.default.actions.TensorTradeActionScheme "tensortrade.env.default.actions.TensorTradeActionScheme")

A simple discrete action scheme where the only options are to buy, sell,

or hold.

| Parameters: | * **cash** (Wallet) – The wallet to hold funds in the base intrument.

* **asset** (Wallet) – The wallet to hold funds in the quote instrument.

 |

`action_space`[¶](#tensortrade.env.default.actions.BSH.action_space "Permalink to this definition")

The action space of the TradingEnv. (Space, read-only)

`attach`(*listener*)[[source]](_modules/tensortrade/env/default/actions.html#BSH.attach)[¶](#tensortrade.env.default.actions.BSH.attach "Permalink to this definition")

`get_orders`(*action: int*, *portfolio: tensortrade.oms.wallets.portfolio.Portfolio*) → tensortrade.oms.orders.order.Order[[source]](_modules/tensortrade/env/default/actions.html#BSH.get_orders)[¶](#tensortrade.env.default.actions.BSH.get_orders "Permalink to this definition")

Gets the list of orders to be submitted for the given action.

| Parameters: | * **action** (*Any*) – The action to be interpreted.

* **portfolio** (*'Portfolio'*) – The portfolio defined for the environment.

 |

| Returns: | *List[Order]* – A list of orders to be submitted to the broker. |

`registered_name` *= 'bsh'*[¶](#tensortrade.env.default.actions.BSH.registered_name "Permalink to this definition")

`reset`()[[source]](_modules/tensortrade/env/default/actions.html#BSH.reset)[¶](#tensortrade.env.default.actions.BSH.reset "Permalink to this definition")

Resets the action scheme.

*class* `tensortrade.env.default.actions.``ManagedRiskOrders`(*stop: List[float] = [0.02, 0.04, 0.06], take: List[float] = [0.01, 0.02, 0.03], trade\_sizes: Union[List[float], int] = 10, durations: Union[List[int], int, None] = None, trade\_type: tensortrade.oms.orders.trade.TradeType = <TradeType.MARKET: 'market'>, order\_listener: Optional[tensortrade.oms.orders.order\_listener.OrderListener] = None, min\_order\_pct: float = 0.02, min\_order\_abs: float = 0.0*)[[source]](_modules/tensortrade/env/default/actions.html#ManagedRiskOrders)[¶](#tensortrade.env.default.actions.ManagedRiskOrders "Permalink to this definition")

Bases: [`tensortrade.env.default.actions.TensorTradeActionScheme`](#tensortrade.env.default.actions.TensorTradeActionScheme "tensortrade.env.default.actions.TensorTradeActionScheme")

A discrete action scheme that determines actions based on managing risk,

through setting a follow-up stop loss and take profit on every order.

| Parameters: | * **stop** (*List**[*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*]*) – A list of possible stop loss percentages for each order.

* **take** (*List**[*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*]*) – A list of possible take profit percentages for each order.

* **trade\_sizes** (*List**[*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*]*) – A list of trade sizes to select from when submitting an order.

(e.g. ‘[1, 1/3]’ = 100% or 33% of balance is tradable.

‘4’ = 25%, 50%, 75%, or 100% of balance is tradable.)

* **durations** (*List**[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*]*) – A list of durations to select from when submitting an order.

* **trade\_type** (TradeType) – A type of trade to make.

* **order\_listener** ([*OrderListener*](index.html#tensortrade.oms.orders.order_listener.OrderListener "tensortrade.oms.orders.order_listener.OrderListener")) – A callback class to use for listening to steps of the order process.

* **min\_order\_pct** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The minimum value when placing an order, calculated in percent over net\_worth.

* **min\_order\_abs** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The minimum value when placing an order, calculated in absolute order value.

 |

`action_space`[¶](#tensortrade.env.default.actions.ManagedRiskOrders.action_space "Permalink to this definition")

The action space of the TradingEnv. (Space, read-only)

`get_orders`(*action: int*, *portfolio: tensortrade.oms.wallets.portfolio.Portfolio*) → List[tensortrade.oms.orders.order.Order][[source]](_modules/tensortrade/env/default/actions.html#ManagedRiskOrders.get_orders)[¶](#tensortrade.env.default.actions.ManagedRiskOrders.get_orders "Permalink to this definition")

Gets the list of orders to be submitted for the given action.

| Parameters: | * **action** (*Any*) – The action to be interpreted.

* **portfolio** (*'Portfolio'*) – The portfolio defined for the environment.

 |

| Returns: | *List[Order]* – A list of orders to be submitted to the broker. |

*class* `tensortrade.env.default.actions.``SimpleOrders`(*criteria: Union[List[OrderCriteria], OrderCriteria] = None, trade\_sizes: Union[List[float], int] = 10, durations: Union[List[int], int] = None, trade\_type: TradeType = <TradeType.MARKET: 'market'>, order\_listener: OrderListener = None, min\_order\_pct: float = 0.02, min\_order\_abs: float = 0.0*)[[source]](_modules/tensortrade/env/default/actions.html#SimpleOrders)[¶](#tensortrade.env.default.actions.SimpleOrders "Permalink to this definition")

Bases: [`tensortrade.env.default.actions.TensorTradeActionScheme`](#tensortrade.env.default.actions.TensorTradeActionScheme "tensortrade.env.default.actions.TensorTradeActionScheme")

A discrete action scheme that determines actions based on a list of

trading pairs, order criteria, and trade sizes.

| Parameters: | * **criteria** (*List**[**OrderCriteria**]*) – A list of order criteria to select from when submitting an order.

(e.g. MarketOrder, LimitOrder w/ price, StopLoss, etc.)

* **trade\_sizes** (*List**[*[*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*]*) – A list of trade sizes to select from when submitting an order.

(e.g. ‘[1, 1/3]’ = 100% or 33% of balance is tradable.

‘4’ = 25%, 50%, 75%, or 100% of balance is tradable.)

* **durations** (*List**[*[*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*]*) – A list of durations to select from when submitting an order.

* **trade\_type** ([*TradeType*](index.html#tensortrade.oms.orders.trade.TradeType "tensortrade.oms.orders.trade.TradeType")) – A type of trade to make.

* **order\_listener** ([*OrderListener*](index.html#tensortrade.oms.orders.order_listener.OrderListener "tensortrade.oms.orders.order_listener.OrderListener")) – A callback class to use for listening to steps of the order process.

* **min\_order\_pct** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The minimum value when placing an order, calculated in percent over net\_worth.

* **min\_order\_abs** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The minimum value when placing an order, calculated in absolute order value.

 |

`action_space`[¶](#tensortrade.env.default.actions.SimpleOrders.action_space "Permalink to this definition")

The action space of the TradingEnv. (Space, read-only)

`get_orders`(*action: int*, *portfolio: tensortrade.oms.wallets.portfolio.Portfolio*) → List[tensortrade.oms.orders.order.Order][[source]](_modules/tensortrade/env/default/actions.html#SimpleOrders.get_orders)[¶](#tensortrade.env.default.actions.SimpleOrders.get_orders "Permalink to this definition")

Gets the list of orders to be submitted for the given action.

| Parameters: | * **action** (*Any*) – The action to be interpreted.

* **portfolio** (*'Portfolio'*) – The portfolio defined for the environment.

 |

| Returns: | *List[Order]* – A list of orders to be submitted to the broker. |

*class* `tensortrade.env.default.actions.``TensorTradeActionScheme`[[source]](_modules/tensortrade/env/default/actions.html#TensorTradeActionScheme)[¶](#tensortrade.env.default.actions.TensorTradeActionScheme "Permalink to this definition")

Bases: [`tensortrade.env.generic.components.action\_scheme.ActionScheme`](index.html#tensortrade.env.generic.components.action_scheme.ActionScheme "tensortrade.env.generic.components.action_scheme.ActionScheme")

An abstract base class for any ActionScheme that wants to be

compatible with the built in OMS.

The structure of the action scheme is built to make sure that action space

can be used with the system, provided that the user defines the methods to

interpret that action.

`portfolio`[¶](#tensortrade.env.default.actions.TensorTradeActionScheme.portfolio "Permalink to this definition")

The portfolio object to be used in defining actions.

| Type: | ‘Portfolio’ |

`broker`[¶](#tensortrade.env.default.actions.TensorTradeActionScheme.broker "Permalink to this definition")

The broker object to be used for placing orders in the OMS.

| Type: | ‘Broker’ |

`perform`(*env*, *portfolio*)[[source]](_modules/tensortrade/env/default/actions.html#TensorTradeActionScheme.perform)[¶](#tensortrade.env.default.actions.TensorTradeActionScheme.perform "Permalink to this definition")

Performs the action on the given environment.

`get_orders`(*action*, *portfolio*)[[source]](_modules/tensortrade/env/default/actions.html#TensorTradeActionScheme.get_orders)[¶](#tensortrade.env.default.actions.TensorTradeActionScheme.get_orders "Permalink to this definition")

Gets the list of orders to be submitted for the given action.

`clock`[¶](#tensortrade.env.default.actions.TensorTradeActionScheme.clock "Permalink to this definition")

The reference clock from the environment. (Clock)

When the clock is set for the we also set the clock for the portfolio

as well as the exchanges defined in the portfolio.

| Returns: | Clock – The environment clock. |

`get_orders`(*action: Any*, *portfolio: tensortrade.oms.wallets.portfolio.Portfolio*) → List[tensortrade.oms.orders.order.Order][[source]](_modules/tensortrade/env/default/actions.html#TensorTradeActionScheme.get_orders)

Gets the list of orders to be submitted for the given action.

| Parameters: | * **action** (*Any*) – The action to be interpreted.

* **portfolio** (*'Portfolio'*) – The portfolio defined for the environment.

 |

| Returns: | *List[Order]* – A list of orders to be submitted to the broker. |

`perform`(*env: tensortrade.env.generic.environment.TradingEnv*, *action: Any*) → None[[source]](_modules/tensortrade/env/default/actions.html#TensorTradeActionScheme.perform)

Performs the action on the given environment.

Under the TT action scheme, the subclassed action scheme is expected

to provide a method for getting a list of orders to be submitted to

the broker for execution in the OMS.

| Parameters: | * **env** (*'TradingEnv'*) – The environment to perform the action on.

* **action** (*Any*) – The specific action selected from the action space.

 |

`reset`() → None[[source]](_modules/tensortrade/env/default/actions.html#TensorTradeActionScheme.reset)[¶](#tensortrade.env.default.actions.TensorTradeActionScheme.reset "Permalink to this definition")

Resets the action scheme.

`tensortrade.env.default.actions.``get`(*identifier: str*) → tensortrade.env.generic.components.action\_scheme.ActionScheme[[source]](_modules/tensortrade/env/default/actions.html#get)[¶](#tensortrade.env.default.actions.get "Permalink to this definition")

Gets the ActionScheme that matches with the identifier.

| Parameters: | **identifier** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The identifier for the ActionScheme. |

| Returns: | *‘ActionScheme’* – The action scheme associated with the identifier. |

| Raises: | KeyError: – Raised if the identifier is not associated with any ActionScheme. |

######### tensortrade.env.default.informers module[¶](#module-tensortrade.env.default.informers "Permalink to this headline")

*class* `tensortrade.env.default.informers.``TensorTradeInformer`[[source]](_modules/tensortrade/env/default/informers.html#TensorTradeInformer)[¶](#tensortrade.env.default.informers.TensorTradeInformer "Permalink to this definition")

Bases: [`tensortrade.env.generic.components.informer.Informer`](index.html#tensortrade.env.generic.components.informer.Informer "tensortrade.env.generic.components.informer.Informer")

`info`(*env: tensortrade.env.generic.environment.TradingEnv*) → dict[[source]](_modules/tensortrade/env/default/informers.html#TensorTradeInformer.info)[¶](#tensortrade.env.default.informers.TensorTradeInformer.info "Permalink to this definition")

Provides information at a given step of an episode.

| Parameters: | **env** (*'TradingEnv'*) – The trading environment. |

| Returns: | *dict* – A dictionary of information about the portfolio and net worth. |

######### tensortrade.env.default.observers module[¶](#module-tensortrade.env.default.observers "Permalink to this headline")

*class* `tensortrade.env.default.observers.``IntradayObserver`(*portfolio: Portfolio*, *feed: DataFeed = None*, *renderer\_feed: DataFeed = None*, *stop\_time: datetime.time = datetime.time(16*, *0)*, *window\_size: int = 1*, *min\_periods: int = None*, *randomize: bool = False*, *\*\*kwargs*)[[source]](_modules/tensortrade/env/default/observers.html#IntradayObserver)[¶](#tensortrade.env.default.observers.IntradayObserver "Permalink to this definition")

Bases: [`tensortrade.env.generic.components.observer.Observer`](index.html#tensortrade.env.generic.components.observer.Observer "tensortrade.env.generic.components.observer.Observer")

The IntradayObserver observer that is compatible with the other default

components.

:param portfolio: The portfolio to be used to create the internal data feed mechanism.

:type portfolio: Portfolio

:param feed: The feed to be used to collect observations to the observation window.

:type feed: DataFeed

:param renderer\_feed: The feed to be used for giving information to the renderer.

:type renderer\_feed: DataFeed

:param stop\_time: The time at which the episode will stop.

:type stop\_time: datetime.time

:param window\_size: The size of the observation window.

:type window\_size: int

:param min\_periods: The amount of steps needed to warmup the feed.

:type min\_periods: int

:param randomize: Whether or not to select a random episode when reset.

:type randomize: bool

:param \*\*kwargs: Additional keyword arguments for observer creation.

:type \*\*kwargs: keyword arguments

`feed`[¶](#tensortrade.env.default.observers.IntradayObserver.feed "Permalink to this definition")

The master feed in charge of streaming the internal, external, and

renderer data feeds.

| Type: | DataFeed |

`stop_time`[¶](#tensortrade.env.default.observers.IntradayObserver.stop_time "Permalink to this definition")

The time at which the episode will stop.

| Type: | [datetime.time](https://docs.python.org/3/library/datetime.html#datetime.time "(in Python v3.9)") |

`window_size`[¶](#tensortrade.env.default.observers.IntradayObserver.window_size "Permalink to this definition")

The size of the observation window.

| Type: | [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") |

`min_periods`[¶](#tensortrade.env.default.observers.IntradayObserver.min_periods "Permalink to this definition")

The amount of steps needed to warmup the feed.

| Type: | [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") |

`randomize`[¶](#tensortrade.env.default.observers.IntradayObserver.randomize "Permalink to this definition")

Whether or not a random episode is selected when reset.

| Type: | [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)") |

`history`[¶](#tensortrade.env.default.observers.IntradayObserver.history "Permalink to this definition")

The observation history.

| Type: | ObservationHistory |

`renderer_history`[¶](#tensortrade.env.default.observers.IntradayObserver.renderer_history "Permalink to this definition")

The history of the renderer data feed.

| Type: | List[dict] |

`has_next`() → bool[[source]](_modules/tensortrade/env/default/observers.html#IntradayObserver.has_next)[¶](#tensortrade.env.default.observers.IntradayObserver.has_next "Permalink to this definition")

Checks if there is another observation to be generated.

:returns: *bool* – Whether there is another observation to be generated.

`observation_space`[¶](#tensortrade.env.default.observers.IntradayObserver.observation_space "Permalink to this definition")

The observation space of the TradingEnv. (Space, read-only)

`observe`(*env: TradingEnv*) → numpy.array[[source]](_modules/tensortrade/env/default/observers.html#IntradayObserver.observe)[¶](#tensortrade.env.default.observers.IntradayObserver.observe "Permalink to this definition")

Observes the environment.

As a consequence of observing the env, a new observation is generated

from the feed and stored in the observation history.

:returns: np.array – The current observation of the environment.

`reset`() → None[[source]](_modules/tensortrade/env/default/observers.html#IntradayObserver.reset)[¶](#tensortrade.env.default.observers.IntradayObserver.reset "Permalink to this definition")

Resets the observer

`warmup`() → None[[source]](_modules/tensortrade/env/default/observers.html#IntradayObserver.warmup)[¶](#tensortrade.env.default.observers.IntradayObserver.warmup "Permalink to this definition")

Warms up the data feed.

*class* `tensortrade.env.default.observers.``ObservationHistory`(*window\_size: int*)[[source]](_modules/tensortrade/env/default/observers.html#ObservationHistory)[¶](#tensortrade.env.default.observers.ObservationHistory "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

Stores observations from a given episode of the environment.

| Parameters: | **window\_size** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The amount of observations to keep stored before discarding them. |

`window_size`[¶](#tensortrade.env.default.observers.ObservationHistory.window_size "Permalink to this definition")

The amount of observations to keep stored before discarding them.

| Type: | [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") |

`rows`[¶](#tensortrade.env.default.observers.ObservationHistory.rows "Permalink to this definition")

The rows of observations that are used as the environment observation

at each step of an episode.

| Type: | pd.DataFrame |

`observe`() → numpy.array[[source]](_modules/tensortrade/env/default/observers.html#ObservationHistory.observe)[¶](#tensortrade.env.default.observers.ObservationHistory.observe "Permalink to this definition")

Gets the observation at a given step in an episode

| Returns: | np.array – The current observation of the environment. |

`push`(*row: dict*) → None[[source]](_modules/tensortrade/env/default/observers.html#ObservationHistory.push)[¶](#tensortrade.env.default.observers.ObservationHistory.push "Permalink to this definition")

Stores an observation.

| Parameters: | **row** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)")) – The new observation to store. |

`reset`() → None[[source]](_modules/tensortrade/env/default/observers.html#ObservationHistory.reset)[¶](#tensortrade.env.default.observers.ObservationHistory.reset "Permalink to this definition")

Resets the observation history

*class* `tensortrade.env.default.observers.``TensorTradeObserver`(*portfolio: Portfolio*, *feed: DataFeed = None*, *renderer\_feed: DataFeed = None*, *window\_size: int = 1*, *min\_periods: int = None*, *\*\*kwargs*)[[source]](_modules/tensortrade/env/default/observers.html#TensorTradeObserver)[¶](#tensortrade.env.default.observers.TensorTradeObserver "Permalink to this definition")

Bases: [`tensortrade.env.generic.components.observer.Observer`](index.html#tensortrade.env.generic.components.observer.Observer "tensortrade.env.generic.components.observer.Observer")

The TensorTrade observer that is compatible with the other default

components.

| Parameters: | * **portfolio** (Portfolio) – The portfolio to be used to create the internal data feed mechanism.

* **feed** (DataFeed) – The feed to be used to collect observations to the observation window.

* **renderer\_feed** (DataFeed) – The feed to be used for giving information to the renderer.

* **window\_size** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The size of the observation window.

* **min\_periods** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The amount of steps needed to warmup the feed.

* **\*\*kwargs** (*keyword arguments*) – Additional keyword arguments for observer creation.

 |

`feed`[¶](#tensortrade.env.default.observers.TensorTradeObserver.feed "Permalink to this definition")

The master feed in charge of streaming the internal, external, and

renderer data feeds.

| Type: | DataFeed |

`window_size`[¶](#tensortrade.env.default.observers.TensorTradeObserver.window_size "Permalink to this definition")

The size of the observation window.

| Type: | [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") |

`min_periods`[¶](#tensortrade.env.default.observers.TensorTradeObserver.min_periods "Permalink to this definition")

The amount of steps needed to warmup the feed.

| Type: | [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") |

`history`[¶](#tensortrade.env.default.observers.TensorTradeObserver.history "Permalink to this definition")

The observation history.

| Type: | ObservationHistory |

`renderer_history`[¶](#tensortrade.env.default.observers.TensorTradeObserver.renderer_history "Permalink to this definition")

The history of the renderer data feed.

| Type: | List[dict] |

`has_next`() → bool[[source]](_modules/tensortrade/env/default/observers.html#TensorTradeObserver.has_next)[¶](#tensortrade.env.default.observers.TensorTradeObserver.has_next "Permalink to this definition")

Checks if there is another observation to be generated.

| Returns: | *bool* – Whether there is another observation to be generated. |

`observation_space`[¶](#tensortrade.env.default.observers.TensorTradeObserver.observation_space "Permalink to this definition")

The observation space of the TradingEnv. (Space, read-only)

`observe`(*env: TradingEnv*) → numpy.array[[source]](_modules/tensortrade/env/default/observers.html#TensorTradeObserver.observe)[¶](#tensortrade.env.default.observers.TensorTradeObserver.observe "Permalink to this definition")

Observes the environment.

As a consequence of observing the env, a new observation is generated

from the feed and stored in the observation history.

| Returns: | np.array – The current observation of the environment. |

`reset`() → None[[source]](_modules/tensortrade/env/default/observers.html#TensorTradeObserver.reset)[¶](#tensortrade.env.default.observers.TensorTradeObserver.reset "Permalink to this definition")

Resets the observer

`warmup`() → None[[source]](_modules/tensortrade/env/default/observers.html#TensorTradeObserver.warmup)[¶](#tensortrade.env.default.observers.TensorTradeObserver.warmup "Permalink to this definition")

Warms up the data feed.

######### tensortrade.env.default.renderers module[¶](#module-tensortrade.env.default.renderers "Permalink to this headline")

*class* `tensortrade.env.default.renderers.``BaseRenderer`[[source]](_modules/tensortrade/env/default/renderers.html#BaseRenderer)[¶](#tensortrade.env.default.renderers.BaseRenderer "Permalink to this definition")

Bases: [`tensortrade.env.generic.components.renderer.Renderer`](index.html#tensortrade.env.generic.components.renderer.Renderer "tensortrade.env.generic.components.renderer.Renderer")

The abstract base renderer to be subclassed when making a renderer

the incorporates a Portfolio.

`render`(*env: tensortrade.env.generic.environment.TradingEnv*, *\*\*kwargs*)[[source]](_modules/tensortrade/env/default/renderers.html#BaseRenderer.render)[¶](#tensortrade.env.default.renderers.BaseRenderer.render "Permalink to this definition")

Renders a view of the environment at the current step of an episode.

| Parameters: | * **env** (*'TradingEnv'*) – The trading environment.

* **kwargs** (*keyword arguments*) – Additional keyword arguments for rendering the environment.

 |

`render_env`(*episode: int = None*, *max\_episodes: int = None*, *step: int = None*, *max\_steps: int = None*, *price\_history: Optional[pandas.core.frame.DataFrame] = None*, *net\_worth: Optional[pandas.core.series.Series] = None*, *performance: Optional[pandas.core.frame.DataFrame] = None*, *trades: Optional[collections.OrderedDict] = None*) → None[[source]](_modules/tensortrade/env/default/renderers.html#BaseRenderer.render_env)[¶](#tensortrade.env.default.renderers.BaseRenderer.render_env "Permalink to this definition")

Renderers the current state of the environment.

| Parameters: | * **episode** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The episode that the environment is being rendered for.

* **max\_episodes** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The maximum number of episodes that will occur.

* **step** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The step of the current episode that is happening.

* **max\_steps** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The maximum number of steps that will occur in an episode.

* **price\_history** (pd.DataFrame) – The history of instrument involved with the environment. The

required columns are: date, open, high, low, close, and volume.

* **net\_worth** (pd.Series) – The history of the net worth of the portfolio.

* **performance** (pd.Series) – The history of performance of the portfolio.

* **trades** (OrderedDict) – The history of trades for the current episode.

 |

`reset`() → None[[source]](_modules/tensortrade/env/default/renderers.html#BaseRenderer.reset)[¶](#tensortrade.env.default.renderers.BaseRenderer.reset "Permalink to this definition")

Resets the renderer.

`save`() → None[[source]](_modules/tensortrade/env/default/renderers.html#BaseRenderer.save)[¶](#tensortrade.env.default.renderers.BaseRenderer.save "Permalink to this definition")

Saves the rendering of the TradingEnv.

*class* `tensortrade.env.default.renderers.``EmptyRenderer`[[source]](_modules/tensortrade/env/default/renderers.html#EmptyRenderer)[¶](#tensortrade.env.default.renderers.EmptyRenderer "Permalink to this definition")

Bases: [`tensortrade.env.generic.components.renderer.Renderer`](index.html#tensortrade.env.generic.components.renderer.Renderer "tensortrade.env.generic.components.renderer.Renderer")

A renderer that does renders nothing.

Needed to make sure that environment can function without requiring a

renderer.

`render`(*env*, *\*\*kwargs*)[[source]](_modules/tensortrade/env/default/renderers.html#EmptyRenderer.render)[¶](#tensortrade.env.default.renderers.EmptyRenderer.render "Permalink to this definition")

Renders a view of the environment at the current step of an episode.

| Parameters: | * **env** (*'TradingEnv'*) – The trading environment.

* **kwargs** (*keyword arguments*) – Additional keyword arguments for rendering the environment.

 |

*class* `tensortrade.env.default.renderers.``FileLogger`(*filename: str = None*, *path: str = 'log'*, *log\_format: str = None*, *timestamp\_format: str = None*)[[source]](_modules/tensortrade/env/default/renderers.html#FileLogger)[¶](#tensortrade.env.default.renderers.FileLogger "Permalink to this definition")

Bases: [`tensortrade.env.default.renderers.BaseRenderer`](#tensortrade.env.default.renderers.BaseRenderer "tensortrade.env.default.renderers.BaseRenderer")

Logs information to a file.

| Parameters: | * **filename** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The file name of the log file. If omitted, a file name will be

created automatically.

* **path** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The path to save the log files to. None to save to same script directory.

* **log\_format** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The log entry format as per Python logging. None for default. For

more details, refer to <https://docs.python.org/3/library/logging.html>

* **timestamp\_format** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The format of the timestamp of the log entry. Node for default.

 |

`DEFAULT_LOG_FORMAT` *= '[%(asctime)-15s] %(message)s'*[¶](#tensortrade.env.default.renderers.FileLogger.DEFAULT_LOG_FORMAT "Permalink to this definition")

`DEFAULT_TIMESTAMP_FORMAT` *= '%Y-%m-%d %H:%M:%S'*[¶](#tensortrade.env.default.renderers.FileLogger.DEFAULT_TIMESTAMP_FORMAT "Permalink to this definition")

`log_file`[¶](#tensortrade.env.default.renderers.FileLogger.log_file "Permalink to this definition")

The filename information is being logged to. (str, read-only)

`render_env`(*episode: int = None*, *max\_episodes: int = None*, *step: int = None*, *max\_steps: int = None*, *price\_history: pandas.core.frame.DataFrame = None*, *net\_worth: pandas.core.series.Series = None*, *performance: pandas.core.frame.DataFrame = None*, *trades: Optional[collections.OrderedDict] = None*) → None[[source]](_modules/tensortrade/env/default/renderers.html#FileLogger.render_env)[¶](#tensortrade.env.default.renderers.FileLogger.render_env "Permalink to this definition")

Renderers the current state of the environment.

| Parameters: | * **episode** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The episode that the environment is being rendered for.

* **max\_episodes** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The maximum number of episodes that will occur.

* **step** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The step of the current episode that is happening.

* **max\_steps** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The maximum number of steps that will occur in an episode.

* **price\_history** (pd.DataFrame) – The history of instrument involved with the environment. The

required columns are: date, open, high, low, close, and volume.

* **net\_worth** (pd.Series) – The history of the net worth of the portfolio.

* **performance** (pd.Series) – The history of performance of the portfolio.

* **trades** (OrderedDict) – The history of trades for the current episode.

 |

*class* `tensortrade.env.default.renderers.``MatplotlibTradingChart`(*display: bool = True*, *save\_format: str = None*, *path: str = 'charts'*, *filename\_prefix: str = 'chart\_'*)[[source]](_modules/tensortrade/env/default/renderers.html#MatplotlibTradingChart)[¶](#tensortrade.env.default.renderers.MatplotlibTradingChart "Permalink to this definition")

Bases: [`tensortrade.env.default.renderers.BaseRenderer`](#tensortrade.env.default.renderers.BaseRenderer "tensortrade.env.default.renderers.BaseRenderer")

Trading visualization for TensorTrade using Matplotlib

:param display: True to display the chart on the screen, False for not.

:type display: bool

:param save\_format: A format to save the chart to. Acceptable formats are

> 

> png, jpg, svg, pdf.

| Parameters: | * **path** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The path to save the char to if save\_format is not None. The folder

will be created if not found.

* **filename\_prefix** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – A string that precedes automatically-created file name

when charts are saved. Default ‘[chart\_](#id6)’.

 |

`render_env`(*episode: int = None*, *max\_episodes: int = None*, *step: int = None*, *max\_steps: int = None*, *price\_history: Optional[pandas.core.frame.DataFrame] = None*, *net\_worth: Optional[pandas.core.series.Series] = None*, *performance: Optional[pandas.core.frame.DataFrame] = None*, *trades: Optional[collections.OrderedDict] = None*) → None[[source]](_modules/tensortrade/env/default/renderers.html#MatplotlibTradingChart.render_env)[¶](#tensortrade.env.default.renderers.MatplotlibTradingChart.render_env "Permalink to this definition")

Renderers the current state of the environment.

| Parameters: | * **episode** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The episode that the environment is being rendered for.

* **max\_episodes** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The maximum number of episodes that will occur.

* **step** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The step of the current episode that is happening.

* **max\_steps** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The maximum number of steps that will occur in an episode.

* **price\_history** (pd.DataFrame) – The history of instrument involved with the environment. The

required columns are: date, open, high, low, close, and volume.

* **net\_worth** (pd.Series) – The history of the net worth of the portfolio.

* **performance** (pd.Series) – The history of performance of the portfolio.

* **trades** (OrderedDict) – The history of trades for the current episode.

 |

`reset`() → None[[source]](_modules/tensortrade/env/default/renderers.html#MatplotlibTradingChart.reset)[¶](#tensortrade.env.default.renderers.MatplotlibTradingChart.reset "Permalink to this definition")

Resets the renderer.

`save`() → None[[source]](_modules/tensortrade/env/default/renderers.html#MatplotlibTradingChart.save)[¶](#tensortrade.env.default.renderers.MatplotlibTradingChart.save "Permalink to this definition")

Saves the rendering of the TradingEnv.

*class* `tensortrade.env.default.renderers.``PlotlyTradingChart`(*display: bool = True*, *height: int = None*, *timestamp\_format: str = '%Y-%m-%d %H:%M:%S'*, *save\_format: str = None*, *path: str = 'charts'*, *filename\_prefix: str = 'chart\_'*, *auto\_open\_html: bool = False*, *include\_plotlyjs: Union[bool*, *str] = 'cdn'*)[[source]](_modules/tensortrade/env/default/renderers.html#PlotlyTradingChart)[¶](#tensortrade.env.default.renderers.PlotlyTradingChart "Permalink to this definition")

Bases: [`tensortrade.env.default.renderers.BaseRenderer`](#tensortrade.env.default.renderers.BaseRenderer "tensortrade.env.default.renderers.BaseRenderer")

Trading visualization for TensorTrade using Plotly.

| Parameters: | * **display** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")) – True to display the chart on the screen, False for not.

* **height** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – Chart height in pixels. Affects both display and saved file

charts. Set to None for 100% height. Default is None.

* **save\_format** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – A format to save the chart to. Acceptable formats are

html, png, jpeg, webp, svg, pdf, eps. All the formats except for

‘html’ require Orca. Default is None for no saving.

* **path** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The path to save the char to if save\_format is not None. The folder

will be created if not found.

* **filename\_prefix** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – A string that precedes automatically-created file name

when charts are saved. Default ‘[chart\_](#id8)’.

* **timestamp\_format** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The format of the date shown in the chart title.

* **auto\_open\_html** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")) – Works for save\_format=’html’ only. True to automatically

open the saved chart HTML file in the default browser, False otherwise.

* **include\_plotlyjs** (*Union**[*[*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* [*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*]*) – Whether to include/load the plotly.js library in the saved

file. ‘cdn’ results in a smaller file by loading the library online but

requires an Internet connect while True includes the library resulting

in much larger file sizes. False to not include the library. For more

details, refer to <https://plot.ly/python-api-reference/generated/plotly.graph_objects.Figure.html>

 |

Notes

Possible Future Enhancements:

* Saving images without using Orca.

* Limit displayed step range for the case of a large number of steps and let

the shown part of the chart slide after filling that range to keep showing

recent data as it’s being added.

References

| [1] | <https://plot.ly/python-api-reference/generated/plotly.graph_objects.Figure.html> |

| [2] | <https://plot.ly/python/figurewidget/> |

| [3] | <https://plot.ly/python/subplots/> |

| [4] | <https://plot.ly/python/reference/#candlestick> |

| [5] | <https://plot.ly/python/#chart-events> |

`render_env`(*episode: int = None*, *max\_episodes: int = None*, *step: int = None*, *max\_steps: int = None*, *price\_history: pandas.core.frame.DataFrame = None*, *net\_worth: pandas.core.series.Series = None*, *performance: pandas.core.frame.DataFrame = None*, *trades: Optional[collections.OrderedDict] = None*) → None[[source]](_modules/tensortrade/env/default/renderers.html#PlotlyTradingChart.render_env)[¶](#tensortrade.env.default.renderers.PlotlyTradingChart.render_env "Permalink to this definition")

Renderers the current state of the environment.

| Parameters: | * **episode** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The episode that the environment is being rendered for.

* **max\_episodes** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The maximum number of episodes that will occur.

* **step** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The step of the current episode that is happening.

* **max\_steps** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The maximum number of steps that will occur in an episode.

* **price\_history** (pd.DataFrame) – The history of instrument involved with the environment. The

required columns are: date, open, high, low, close, and volume.

* **net\_worth** (pd.Series) – The history of the net worth of the portfolio.

* **performance** (pd.Series) – The history of performance of the portfolio.

* **trades** (OrderedDict) – The history of trades for the current episode.

 |

`reset`() → None[[source]](_modules/tensortrade/env/default/renderers.html#PlotlyTradingChart.reset)[¶](#tensortrade.env.default.renderers.PlotlyTradingChart.reset "Permalink to this definition")

Resets the renderer.

`save`() → None[[source]](_modules/tensortrade/env/default/renderers.html#PlotlyTradingChart.save)[¶](#tensortrade.env.default.renderers.PlotlyTradingChart.save "Permalink to this definition")

Saves the current chart to a file.

Notes

All formats other than HTML require Orca installed and server running.

*class* `tensortrade.env.default.renderers.``ScreenLogger`(*date\_format: str = '%Y-%m-%d %-I:%M:%S %p'*)[[source]](_modules/tensortrade/env/default/renderers.html#ScreenLogger)[¶](#tensortrade.env.default.renderers.ScreenLogger "Permalink to this definition")

Bases: [`tensortrade.env.default.renderers.BaseRenderer`](#tensortrade.env.default.renderers.BaseRenderer "tensortrade.env.default.renderers.BaseRenderer")

Logs information the screen of the user.

| Parameters: | **date\_format** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The format for logging the date. |

`DEFAULT_FORMAT` *= '[%(asctime)-15s] %(message)s'*[¶](#tensortrade.env.default.renderers.ScreenLogger.DEFAULT_FORMAT "Permalink to this definition")

`render_env`(*episode: int = None*, *max\_episodes: int = None*, *step: int = None*, *max\_steps: int = None*, *price\_history: pandas.core.frame.DataFrame = None*, *net\_worth: pandas.core.series.Series = None*, *performance: pandas.core.frame.DataFrame = None*, *trades: Optional[collections.OrderedDict] = None*)[[source]](_modules/tensortrade/env/default/renderers.html#ScreenLogger.render_env)[¶](#tensortrade.env.default.renderers.ScreenLogger.render_env "Permalink to this definition")

Renderers the current state of the environment.

| Parameters: | * **episode** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The episode that the environment is being rendered for.

* **max\_episodes** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The maximum number of episodes that will occur.

* **step** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The step of the current episode that is happening.

* **max\_steps** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The maximum number of steps that will occur in an episode.

* **price\_history** (pd.DataFrame) – The history of instrument involved with the environment. The

required columns are: date, open, high, low, close, and volume.

* **net\_worth** (pd.Series) – The history of the net worth of the portfolio.

* **performance** (pd.Series) – The history of performance of the portfolio.

* **trades** (OrderedDict) – The history of trades for the current episode.

 |

`tensortrade.env.default.renderers.``get`(*identifier: str*) → tensortrade.env.default.renderers.BaseRenderer[[source]](_modules/tensortrade/env/default/renderers.html#get)[¶](#tensortrade.env.default.renderers.get "Permalink to this definition")

Gets the BaseRenderer that matches the identifier.

| Parameters: | **identifier** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The identifier for the BaseRenderer |

| Returns: | BaseRenderer – The renderer associated with the identifier. |

| Raises: | KeyError: – Raised if identifier is not associated with any BaseRenderer |

######### tensortrade.env.default.rewards module[¶](#module-tensortrade.env.default.rewards "Permalink to this headline")

*class* `tensortrade.env.default.rewards.``PBR`(*price: tensortrade.feed.core.base.Stream*)[[source]](_modules/tensortrade/env/default/rewards.html#PBR)[¶](#tensortrade.env.default.rewards.PBR "Permalink to this definition")

Bases: [`tensortrade.env.default.rewards.TensorTradeRewardScheme`](#tensortrade.env.default.rewards.TensorTradeRewardScheme "tensortrade.env.default.rewards.TensorTradeRewardScheme")

A reward scheme for position-based returns.

* Let \(p\_t\) denote the price at time t.

* Let \(x\_t\) denote the position at time t.

* Let \(R\_t\) denote the reward at time t.

Then the reward is defined as,

\(R\_{t} = (p\_{t} - p\_{t-1}) \cdot x\_{t}\).

| Parameters: | **price** (Stream) – The price stream to use for computing rewards. |

`get_reward`(*portfolio: Portfolio*) → float[[source]](_modules/tensortrade/env/default/rewards.html#PBR.get_reward)[¶](#tensortrade.env.default.rewards.PBR.get_reward "Permalink to this definition")

Gets the reward associated with current step of the episode.

| Parameters: | **portfolio** (Portfolio) – The portfolio associated with the TensorTradeActionScheme. |

| Returns: | *float* – The reward for the current step of the episode. |

`on_action`(*action: int*) → None[[source]](_modules/tensortrade/env/default/rewards.html#PBR.on_action)[¶](#tensortrade.env.default.rewards.PBR.on_action "Permalink to this definition")

`registered_name` *= 'pbr'*[¶](#tensortrade.env.default.rewards.PBR.registered_name "Permalink to this definition")

`reset`() → None[[source]](_modules/tensortrade/env/default/rewards.html#PBR.reset)[¶](#tensortrade.env.default.rewards.PBR.reset "Permalink to this definition")

Resets the position and feed of the reward scheme.

*class* `tensortrade.env.default.rewards.``RiskAdjustedReturns`(*return\_algorithm: str = 'sharpe'*, *risk\_free\_rate: float = 0.0*, *target\_returns: float = 0.0*, *window\_size: int = 1*)[[source]](_modules/tensortrade/env/default/rewards.html#RiskAdjustedReturns)[¶](#tensortrade.env.default.rewards.RiskAdjustedReturns "Permalink to this definition")

Bases: [`tensortrade.env.default.rewards.TensorTradeRewardScheme`](#tensortrade.env.default.rewards.TensorTradeRewardScheme "tensortrade.env.default.rewards.TensorTradeRewardScheme")

A reward scheme that rewards the agent for increasing its net worth,

while penalizing more volatile strategies.

| Parameters: | * **return\_algorithm** (*{'sharpe'**,* *'sortino'}**,* *Default 'sharpe'.*) – The risk-adjusted return metric to use.

* **risk\_free\_rate** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *Default 0.*) – The risk free rate of returns to use for calculating metrics.

* **target\_returns** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *Default 0*) – The target returns per period for use in calculating the sortino ratio.

* **window\_size** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The size of the look back window for computing the reward.

 |

`get_reward`(*portfolio: Portfolio*) → float[[source]](_modules/tensortrade/env/default/rewards.html#RiskAdjustedReturns.get_reward)[¶](#tensortrade.env.default.rewards.RiskAdjustedReturns.get_reward "Permalink to this definition")

Computes the reward corresponding to the selected risk-adjusted return metric.

| Parameters: | **portfolio** (Portfolio) – The current portfolio being used by the environment. |

| Returns: | *float* – The reward corresponding to the selected risk-adjusted return metric. |

*class* `tensortrade.env.default.rewards.``SimpleProfit`(*window\_size: int = 1*)[[source]](_modules/tensortrade/env/default/rewards.html#SimpleProfit)[¶](#tensortrade.env.default.rewards.SimpleProfit "Permalink to this definition")

Bases: [`tensortrade.env.default.rewards.TensorTradeRewardScheme`](#tensortrade.env.default.rewards.TensorTradeRewardScheme "tensortrade.env.default.rewards.TensorTradeRewardScheme")

A simple reward scheme that rewards the agent for incremental increases

in net worth.

| Parameters: | **window\_size** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The size of the look back window for computing the reward. |

`window_size`[¶](#tensortrade.env.default.rewards.SimpleProfit.window_size "Permalink to this definition")

The size of the look back window for computing the reward.

| Type: | [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)") |

`get_reward`(*portfolio: Portfolio*) → float[[source]](_modules/tensortrade/env/default/rewards.html#SimpleProfit.get_reward)[¶](#tensortrade.env.default.rewards.SimpleProfit.get_reward "Permalink to this definition")

Rewards the agent for incremental increases in net worth over a

sliding window.

| Parameters: | **portfolio** (Portfolio) – The portfolio being used by the environment. |

| Returns: | *float* – The cumulative percentage change in net worth over the previous

window\_size time steps. |

*class* `tensortrade.env.default.rewards.``TensorTradeRewardScheme`[[source]](_modules/tensortrade/env/default/rewards.html#TensorTradeRewardScheme)[¶](#tensortrade.env.default.rewards.TensorTradeRewardScheme "Permalink to this definition")

Bases: [`tensortrade.env.generic.components.reward\_scheme.RewardScheme`](index.html#tensortrade.env.generic.components.reward_scheme.RewardScheme "tensortrade.env.generic.components.reward_scheme.RewardScheme")

An abstract base class for reward schemes for the default environment.

`get_reward`(*portfolio*) → float[[source]](_modules/tensortrade/env/default/rewards.html#TensorTradeRewardScheme.get_reward)[¶](#tensortrade.env.default.rewards.TensorTradeRewardScheme.get_reward "Permalink to this definition")

Gets the reward associated with current step of the episode.

| Parameters: | **portfolio** (Portfolio) – The portfolio associated with the TensorTradeActionScheme. |

| Returns: | *float* – The reward for the current step of the episode. |

`reward`(*env: tensortrade.env.generic.environment.TradingEnv*) → float[[source]](_modules/tensortrade/env/default/rewards.html#TensorTradeRewardScheme.reward)[¶](#tensortrade.env.default.rewards.TensorTradeRewardScheme.reward "Permalink to this definition")

Computes the reward for the current step of an episode.

| Parameters: | **env** (TradingEnv) – The trading environment |

| Returns: | *float* – The computed reward. |

`tensortrade.env.default.rewards.``get`(*identifier: str*) → tensortrade.env.default.rewards.TensorTradeRewardScheme[[source]](_modules/tensortrade/env/default/rewards.html#get)[¶](#tensortrade.env.default.rewards.get "Permalink to this definition")

Gets the RewardScheme that matches with the identifier.

| Parameters: | **identifier** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The identifier for the RewardScheme |

| Returns: | TensorTradeRewardScheme – The reward scheme associated with the identifier. |

| Raises: | KeyError: – Raised if identifier is not associated with any RewardScheme |

######### tensortrade.env.default.stoppers module[¶](#module-tensortrade.env.default.stoppers "Permalink to this headline")

*class* `tensortrade.env.default.stoppers.``MaxLossStopper`(*max\_allowed\_loss: float*)[[source]](_modules/tensortrade/env/default/stoppers.html#MaxLossStopper)[¶](#tensortrade.env.default.stoppers.MaxLossStopper "Permalink to this definition")

Bases: [`tensortrade.env.generic.components.stopper.Stopper`](index.html#tensortrade.env.generic.components.stopper.Stopper "tensortrade.env.generic.components.stopper.Stopper")

A stopper that stops an episode if the portfolio has lost a particular

percentage of its wealth.

| Parameters: | **max\_allowed\_loss** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The maximum percentage of initial funds that is willing to

be lost before stopping the episode. |

`max_allowed_loss`[¶](#tensortrade.env.default.stoppers.MaxLossStopper.max_allowed_loss "Permalink to this definition")

The maximum percentage of initial funds that is willing to

be lost before stopping the episode.

| Type: | [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)") |

Notes

This stopper also stops if it has reached the end of the observation feed.

`stop`(*env: tensortrade.env.generic.environment.TradingEnv*) → bool[[source]](_modules/tensortrade/env/default/stoppers.html#MaxLossStopper.stop)[¶](#tensortrade.env.default.stoppers.MaxLossStopper.stop "Permalink to this definition")

Computes if the environment satisfies the defined stopping criteria.

| Parameters: | **env** (TradingEnv) – The trading environment. |

| Returns: | *bool* – If the environment should stop or continue. |

####### tensortrade.env.generic package[¶](#module-tensortrade.env.generic "Permalink to this headline")

######## Subpackages[¶](#subpackages "Permalink to this headline")

######### tensortrade.env.generic.components package[¶](#module-tensortrade.env.generic.components "Permalink to this headline")

########## Submodules[¶](#submodules "Permalink to this headline")

########### tensortrade.env.generic.components.action\_scheme module[¶](#module-tensortrade.env.generic.components.action_scheme "Permalink to this headline")

*class* `tensortrade.env.generic.components.action_scheme.``ActionScheme`[[source]](_modules/tensortrade/env/generic/components/action_scheme.html#ActionScheme)[¶](#tensortrade.env.generic.components.action_scheme.ActionScheme "Permalink to this definition")

Bases: [`tensortrade.core.component.Component`](index.html#tensortrade.core.component.Component "tensortrade.core.component.Component"), [`tensortrade.core.base.TimeIndexed`](index.html#tensortrade.core.base.TimeIndexed "tensortrade.core.base.TimeIndexed")

A component for determining the action to take at each step of an

episode.

`action_space`[¶](#tensortrade.env.generic.components.action_scheme.ActionScheme.action_space "Permalink to this definition")

The action space of the TradingEnv. (Space, read-only)

`perform`(*env: TradingEnv*, *action: Any*) → None[[source]](_modules/tensortrade/env/generic/components/action_scheme.html#ActionScheme.perform)[¶](#tensortrade.env.generic.components.action_scheme.ActionScheme.perform "Permalink to this definition")

Performs an action on the environment.

| Parameters: | * **env** (TradingEnv) – The trading environment to perform the action on.

* **action** (*Any*) – The action to perform on env.

 |

`registered_name` *= 'actions'*[¶](#tensortrade.env.generic.components.action_scheme.ActionScheme.registered_name "Permalink to this definition")

`reset`() → None[[source]](_modules/tensortrade/env/generic/components/action_scheme.html#ActionScheme.reset)[¶](#tensortrade.env.generic.components.action_scheme.ActionScheme.reset "Permalink to this definition")

Resets the action scheme.

########### tensortrade.env.generic.components.informer module[¶](#module-tensortrade.env.generic.components.informer "Permalink to this headline")

*class* `tensortrade.env.generic.components.informer.``Informer`[[source]](_modules/tensortrade/env/generic/components/informer.html#Informer)[¶](#tensortrade.env.generic.components.informer.Informer "Permalink to this definition")

Bases: [`tensortrade.core.component.Component`](index.html#tensortrade.core.component.Component "tensortrade.core.component.Component"), [`tensortrade.core.base.TimeIndexed`](index.html#tensortrade.core.base.TimeIndexed "tensortrade.core.base.TimeIndexed")

A component to provide information at each step of an episode.

`info`(*env: TradingEnv*) → dict[[source]](_modules/tensortrade/env/generic/components/informer.html#Informer.info)[¶](#tensortrade.env.generic.components.informer.Informer.info "Permalink to this definition")

Provides information at a given step of an episode.

| Parameters: | **env** (*'TradingEnv'*) – The trading environment. |

| Returns: | *dict* – A dictionary of information about the portfolio and net worth. |

`registered_name` *= 'monitor'*[¶](#tensortrade.env.generic.components.informer.Informer.registered_name "Permalink to this definition")

`reset`()[[source]](_modules/tensortrade/env/generic/components/informer.html#Informer.reset)[¶](#tensortrade.env.generic.components.informer.Informer.reset "Permalink to this definition")

Resets the informer.

########### tensortrade.env.generic.components.observer module[¶](#module-tensortrade.env.generic.components.observer "Permalink to this headline")

*class* `tensortrade.env.generic.components.observer.``Observer`[[source]](_modules/tensortrade/env/generic/components/observer.html#Observer)[¶](#tensortrade.env.generic.components.observer.Observer "Permalink to this definition")

Bases: [`tensortrade.core.component.Component`](index.html#tensortrade.core.component.Component "tensortrade.core.component.Component"), [`tensortrade.core.base.TimeIndexed`](index.html#tensortrade.core.base.TimeIndexed "tensortrade.core.base.TimeIndexed")

A component to generate an observation at each step of an episode.

`observation_space`[¶](#tensortrade.env.generic.components.observer.Observer.observation_space "Permalink to this definition")

The observation space of the TradingEnv. (Space, read-only)

`observe`(*env: TradingEnv*) → numpy.array[[source]](_modules/tensortrade/env/generic/components/observer.html#Observer.observe)[¶](#tensortrade.env.generic.components.observer.Observer.observe "Permalink to this definition")

Gets the observation at the current step of an episode

| Parameters: | **env** (*'TradingEnv'*) – The trading environment. |

| Returns: | np.array – The current observation of the environment. |

`registered_name` *= 'observer'*[¶](#tensortrade.env.generic.components.observer.Observer.registered_name "Permalink to this definition")

`reset`()[[source]](_modules/tensortrade/env/generic/components/observer.html#Observer.reset)[¶](#tensortrade.env.generic.components.observer.Observer.reset "Permalink to this definition")

Resets the observer.

########### tensortrade.env.generic.components.renderer module[¶](#module-tensortrade.env.generic.components.renderer "Permalink to this headline")

*class* `tensortrade.env.generic.components.renderer.``AggregateRenderer`(*renderers: List[tensortrade.env.generic.components.renderer.Renderer]*)[[source]](_modules/tensortrade/env/generic/components/renderer.html#AggregateRenderer)[¶](#tensortrade.env.generic.components.renderer.AggregateRenderer "Permalink to this definition")

Bases: [`tensortrade.env.generic.components.renderer.Renderer`](#tensortrade.env.generic.components.renderer.Renderer "tensortrade.env.generic.components.renderer.Renderer")

A renderer that aggregates compatible renderers so they can all be used

to render a view of the environment.

| Parameters: | **renderers** (*List**[*[*Renderer*](index.html#tensortrade.env.generic.components.renderer.Renderer "tensortrade.env.generic.components.renderer.Renderer")*]*) – A list of renderers to aggregate. |

`renderers`[¶](#tensortrade.env.generic.components.renderer.AggregateRenderer.renderers "Permalink to this definition")

A list of renderers to aggregate.

| Type: | List[[Renderer](index.html#tensortrade.env.generic.components.renderer.Renderer "tensortrade.env.generic.components.renderer.Renderer")] |

`close`() → None[[source]](_modules/tensortrade/env/generic/components/renderer.html#AggregateRenderer.close)[¶](#tensortrade.env.generic.components.renderer.AggregateRenderer.close "Permalink to this definition")

Closes the renderer.

`render`(*env: TradingEnv*, *\*\*kwargs*) → None[[source]](_modules/tensortrade/env/generic/components/renderer.html#AggregateRenderer.render)[¶](#tensortrade.env.generic.components.renderer.AggregateRenderer.render "Permalink to this definition")

Renders a view of the environment at the current step of an episode.

| Parameters: | * **env** (*'TradingEnv'*) – The trading environment.

* **kwargs** (*keyword arguments*) – Additional keyword arguments for rendering the environment.

 |

`reset`() → None[[source]](_modules/tensortrade/env/generic/components/renderer.html#AggregateRenderer.reset)[¶](#tensortrade.env.generic.components.renderer.AggregateRenderer.reset "Permalink to this definition")

Resets the renderer.

`save`() → None[[source]](_modules/tensortrade/env/generic/components/renderer.html#AggregateRenderer.save)[¶](#tensortrade.env.generic.components.renderer.AggregateRenderer.save "Permalink to this definition")

Saves the rendered view of the environment.

*class* `tensortrade.env.generic.components.renderer.``Renderer`[[source]](_modules/tensortrade/env/generic/components/renderer.html#Renderer)[¶](#tensortrade.env.generic.components.renderer.Renderer "Permalink to this definition")

Bases: [`tensortrade.core.component.Component`](index.html#tensortrade.core.component.Component "tensortrade.core.component.Component")

A component for rendering a view of the environment at each step of

an episode.

`close`() → None[[source]](_modules/tensortrade/env/generic/components/renderer.html#Renderer.close)[¶](#tensortrade.env.generic.components.renderer.Renderer.close "Permalink to this definition")

Closes the renderer.

`registered_name` *= 'renderer'*[¶](#tensortrade.env.generic.components.renderer.Renderer.registered_name "Permalink to this definition")

`render`(*env: TradingEnv*, *\*\*kwargs*)[[source]](_modules/tensortrade/env/generic/components/renderer.html#Renderer.render)[¶](#tensortrade.env.generic.components.renderer.Renderer.render "Permalink to this definition")

Renders a view of the environment at the current step of an episode.

| Parameters: | * **env** (*'TradingEnv'*) – The trading environment.

* **kwargs** (*keyword arguments*) – Additional keyword arguments for rendering the environment.

 |

`reset`() → None[[source]](_modules/tensortrade/env/generic/components/renderer.html#Renderer.reset)[¶](#tensortrade.env.generic.components.renderer.Renderer.reset "Permalink to this definition")

Resets the renderer.

`save`() → None[[source]](_modules/tensortrade/env/generic/components/renderer.html#Renderer.save)[¶](#tensortrade.env.generic.components.renderer.Renderer.save "Permalink to this definition")

Saves the rendered view of the environment.

########### tensortrade.env.generic.components.reward\_scheme module[¶](#module-tensortrade.env.generic.components.reward_scheme "Permalink to this headline")

*class* `tensortrade.env.generic.components.reward_scheme.``RewardScheme`[[source]](_modules/tensortrade/env/generic/components/reward_scheme.html#RewardScheme)[¶](#tensortrade.env.generic.components.reward_scheme.RewardScheme "Permalink to this definition")

Bases: [`tensortrade.core.component.Component`](index.html#tensortrade.core.component.Component "tensortrade.core.component.Component"), [`tensortrade.core.base.TimeIndexed`](index.html#tensortrade.core.base.TimeIndexed "tensortrade.core.base.TimeIndexed")

A component to compute the reward at each step of an episode.

`registered_name` *= 'rewards'*[¶](#tensortrade.env.generic.components.reward_scheme.RewardScheme.registered_name "Permalink to this definition")

`reset`() → None[[source]](_modules/tensortrade/env/generic/components/reward_scheme.html#RewardScheme.reset)[¶](#tensortrade.env.generic.components.reward_scheme.RewardScheme.reset "Permalink to this definition")

Resets the reward scheme.

`reward`(*env: TradingEnv*) → float[[source]](_modules/tensortrade/env/generic/components/reward_scheme.html#RewardScheme.reward)[¶](#tensortrade.env.generic.components.reward_scheme.RewardScheme.reward "Permalink to this definition")

Computes the reward for the current step of an episode.

| Parameters: | **env** (TradingEnv) – The trading environment |

| Returns: | *float* – The computed reward. |

########### tensortrade.env.generic.components.stopper module[¶](#module-tensortrade.env.generic.components.stopper "Permalink to this headline")

*class* `tensortrade.env.generic.components.stopper.``Stopper`[[source]](_modules/tensortrade/env/generic/components/stopper.html#Stopper)[¶](#tensortrade.env.generic.components.stopper.Stopper "Permalink to this definition")

Bases: [`tensortrade.core.component.Component`](index.html#tensortrade.core.component.Component "tensortrade.core.component.Component"), [`tensortrade.core.base.TimeIndexed`](index.html#tensortrade.core.base.TimeIndexed "tensortrade.core.base.TimeIndexed")

A component for determining if the environment satisfies a defined

stopping criteria.

`registered_name` *= 'stopper'*[¶](#tensortrade.env.generic.components.stopper.Stopper.registered_name "Permalink to this definition")

`reset`() → None[[source]](_modules/tensortrade/env/generic/components/stopper.html#Stopper.reset)[¶](#tensortrade.env.generic.components.stopper.Stopper.reset "Permalink to this definition")

Resets the stopper.

`stop`(*env: TradingEnv*) → bool[[source]](_modules/tensortrade/env/generic/components/stopper.html#Stopper.stop)[¶](#tensortrade.env.generic.components.stopper.Stopper.stop "Permalink to this definition")

Computes if the environment satisfies the defined stopping criteria.

| Parameters: | **env** (TradingEnv) – The trading environment. |

| Returns: | *bool* – If the environment should stop or continue. |

######## Submodules[¶](#submodules "Permalink to this headline")

######### tensortrade.env.generic.environment module[¶](#module-tensortrade.env.generic.environment "Permalink to this headline")

*class* `tensortrade.env.generic.environment.``TradingEnv`(*action\_scheme: tensortrade.env.generic.components.action\_scheme.ActionScheme*, *reward\_scheme: tensortrade.env.generic.components.reward\_scheme.RewardScheme*, *observer: tensortrade.env.generic.components.observer.Observer*, *stopper: tensortrade.env.generic.components.stopper.Stopper*, *informer: tensortrade.env.generic.components.informer.Informer*, *renderer: tensortrade.env.generic.components.renderer.Renderer*, *\*\*kwargs*)[[source]](_modules/tensortrade/env/generic/environment.html#TradingEnv)[¶](#tensortrade.env.generic.environment.TradingEnv "Permalink to this definition")

Bases: `gym.core.Env`, [`tensortrade.core.base.TimeIndexed`](index.html#tensortrade.core.base.TimeIndexed "tensortrade.core.base.TimeIndexed")

A trading environment made for use with Gym-compatible reinforcement

learning algorithms.

| Parameters: | * **action\_scheme** (ActionScheme) – A component for generating an action to perform at each step of the

environment.

* **reward\_scheme** (RewardScheme) – A component for computing reward after each step of the environment.

* **observer** (Observer) – A component for generating observations after each step of the

environment.

* **informer** (Informer) – A component for providing information after each step of the

environment.

* **renderer** (Renderer) – A component for rendering the environment.

* **kwargs** (*keyword arguments*) – Additional keyword arguments needed to create the environment.

 |

`agent_id` *= None*[¶](#tensortrade.env.generic.environment.TradingEnv.agent_id "Permalink to this definition")

`close`() → None[[source]](_modules/tensortrade/env/generic/environment.html#TradingEnv.close)[¶](#tensortrade.env.generic.environment.TradingEnv.close "Permalink to this definition")

Closes the environment.

`components`[¶](#tensortrade.env.generic.environment.TradingEnv.components "Permalink to this definition")

The components of the environment. (Dict[str,Component], read-only)

`episode_id` *= None*[¶](#tensortrade.env.generic.environment.TradingEnv.episode_id "Permalink to this definition")

`render`(*\*\*kwargs*) → None[[source]](_modules/tensortrade/env/generic/environment.html#TradingEnv.render)[¶](#tensortrade.env.generic.environment.TradingEnv.render "Permalink to this definition")

Renders the environment.

`reset`() → numpy.array[[source]](_modules/tensortrade/env/generic/environment.html#TradingEnv.reset)[¶](#tensortrade.env.generic.environment.TradingEnv.reset "Permalink to this definition")

Resets the environment.

| Returns: | **obs** (np.array) – The first observation of the environment. |

`save`() → None[[source]](_modules/tensortrade/env/generic/environment.html#TradingEnv.save)[¶](#tensortrade.env.generic.environment.TradingEnv.save "Permalink to this definition")

Saves the rendered view of the environment.

`step`(*action: Any*) → Tuple[numpy.array, float, bool, dict][[source]](_modules/tensortrade/env/generic/environment.html#TradingEnv.step)[¶](#tensortrade.env.generic.environment.TradingEnv.step "Permalink to this definition")

Makes on step through the environment.

| Parameters: | **action** (*Any*) – An action to perform on the environment. |

| Returns: | * np.array – The observation of the environment after the action being

performed.

* *float* – The computed reward for performing the action.

* *bool* – Whether or not the episode is complete.

* *dict* – The information gathered after completing the step.

 |

##### tensortrade.feed package[¶](#module-tensortrade.feed "Permalink to this headline")

###### Subpackages[¶](#subpackages "Permalink to this headline")

####### tensortrade.feed.api package[¶](#module-tensortrade.feed.api "Permalink to this headline")

######## Subpackages[¶](#subpackages "Permalink to this headline")

######### tensortrade.feed.api.boolean package[¶](#module-tensortrade.feed.api.boolean "Permalink to this headline")

*class* `tensortrade.feed.api.boolean.``Boolean`[[source]](_modules/tensortrade/feed/api/boolean.html#Boolean)[¶](#tensortrade.feed.api.boolean.Boolean "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

A class to register accessor and instance methods.

*classmethod* `register`(*names: List[str]*)[[source]](_modules/tensortrade/feed/api/boolean.html#Boolean.register)[¶](#tensortrade.feed.api.boolean.Boolean.register "Permalink to this definition")

A function decorator that adds accessor and instance methods for

specified data type.

| Parameters: | **names** (List[str]) – A list of names used to register the function as a method. |

| Returns: | *Callable* – A decorated function. |

*class* `tensortrade.feed.api.boolean.``BooleanMethods`(*stream: Stream*)[[source]](_modules/tensortrade/feed/api/boolean.html#BooleanMethods)[¶](#tensortrade.feed.api.boolean.BooleanMethods "Permalink to this definition")

Bases: [`tensortrade.feed.core.methods.Methods`](index.html#tensortrade.feed.core.methods.Methods "tensortrade.feed.core.methods.Methods")

`invert`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.boolean.BooleanMethods.invert "Permalink to this definition")

*class* `tensortrade.feed.api.boolean.``BooleanMixin`[[source]](_modules/tensortrade/feed/api/boolean.html#BooleanMixin)[¶](#tensortrade.feed.api.boolean.BooleanMixin "Permalink to this definition")

Bases: [`tensortrade.feed.core.mixins.DataTypeMixin`](index.html#tensortrade.feed.core.mixins.DataTypeMixin "tensortrade.feed.core.mixins.DataTypeMixin")

`invert`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.boolean.BooleanMixin.invert "Permalink to this definition")

########## Submodules[¶](#submodules "Permalink to this headline")

########### tensortrade.feed.api.boolean.operations module[¶](#module-tensortrade.feed.api.boolean.operations "Permalink to this headline")

`tensortrade.feed.api.boolean.operations.``invert`(*s: tensortrade.feed.core.base.Stream[bool][bool]*) → tensortrade.feed.core.base.Stream[bool][bool][[source]](_modules/tensortrade/feed/api/boolean/operations.html#invert)[¶](#tensortrade.feed.api.boolean.operations.invert "Permalink to this definition")

Inverts the truth value of the given stream.

| Parameters: | **s** (Stream[bool]) – A boolean stream. |

| Returns: | Stream[bool] – An inverted stream of s. |

######### tensortrade.feed.api.float package[¶](#module-tensortrade.feed.api.float "Permalink to this headline")

*class* `tensortrade.feed.api.float.``Float`[[source]](_modules/tensortrade/feed/api/float.html#Float)[¶](#tensortrade.feed.api.float.Float "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

A class to register accessor and instance methods.

*classmethod* `register`(*names: List[str]*)[[source]](_modules/tensortrade/feed/api/float.html#Float.register)[¶](#tensortrade.feed.api.float.Float.register "Permalink to this definition")

A function decorator that adds accessor and instance methods for

specified data type.

| Parameters: | **names** (List[str]) – A list of names used to register the function as a method. |

| Returns: | *Callable* – A decorated function. |

*class* `tensortrade.feed.api.float.``FloatMethods`(*stream: Stream*)[[source]](_modules/tensortrade/feed/api/float.html#FloatMethods)[¶](#tensortrade.feed.api.float.FloatMethods "Permalink to this definition")

Bases: [`tensortrade.feed.core.methods.Methods`](index.html#tensortrade.feed.core.methods.Methods "tensortrade.feed.core.methods.Methods")

`abs`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.abs "Permalink to this definition")

`add`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.add "Permalink to this definition")

`ceil`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.ceil "Permalink to this definition")

`clamp`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.clamp "Permalink to this definition")

`clamp_max`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.clamp_max "Permalink to this definition")

`clamp_min`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.clamp_min "Permalink to this definition")

`cummax`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.cummax "Permalink to this definition")

`cummin`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.cummin "Permalink to this definition")

`cumprod`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.cumprod "Permalink to this definition")

`cumsum`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.cumsum "Permalink to this definition")

`diff`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.diff "Permalink to this definition")

`div`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.div "Permalink to this definition")

`ewm`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.ewm "Permalink to this definition")

`expanding`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.expanding "Permalink to this definition")

`ffill`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.ffill "Permalink to this definition")

`fillna`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.fillna "Permalink to this definition")

`floor`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.floor "Permalink to this definition")

`log`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.log "Permalink to this definition")

`max`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.max "Permalink to this definition")

`min`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.min "Permalink to this definition")

`mul`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.mul "Permalink to this definition")

`neg`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.neg "Permalink to this definition")

`pct_change`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.pct_change "Permalink to this definition")

`pow`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.pow "Permalink to this definition")

`radd`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.radd "Permalink to this definition")

`rdiv`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.rdiv "Permalink to this definition")

`rmul`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.rmul "Permalink to this definition")

`rolling`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.rolling "Permalink to this definition")

`rsub`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.rsub "Permalink to this definition")

`sqrt`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.sqrt "Permalink to this definition")

`square`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.square "Permalink to this definition")

`sub`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMethods.sub "Permalink to this definition")

*class* `tensortrade.feed.api.float.``FloatMixin`[[source]](_modules/tensortrade/feed/api/float.html#FloatMixin)[¶](#tensortrade.feed.api.float.FloatMixin "Permalink to this definition")

Bases: [`tensortrade.feed.core.mixins.DataTypeMixin`](index.html#tensortrade.feed.core.mixins.DataTypeMixin "tensortrade.feed.core.mixins.DataTypeMixin")

`abs`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.abs "Permalink to this definition")

`add`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.add "Permalink to this definition")

`ceil`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.ceil "Permalink to this definition")

`clamp`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.clamp "Permalink to this definition")

`clamp_max`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.clamp_max "Permalink to this definition")

`clamp_min`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.clamp_min "Permalink to this definition")

`cummax`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.cummax "Permalink to this definition")

`cummin`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.cummin "Permalink to this definition")

`cumprod`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.cumprod "Permalink to this definition")

`cumsum`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.cumsum "Permalink to this definition")

`diff`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.diff "Permalink to this definition")

`div`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.div "Permalink to this definition")

`ewm`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.ewm "Permalink to this definition")

`expanding`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.expanding "Permalink to this definition")

`ffill`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.ffill "Permalink to this definition")

`fillna`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.fillna "Permalink to this definition")

`floor`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.floor "Permalink to this definition")

`log`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.log "Permalink to this definition")

`max`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.max "Permalink to this definition")

`min`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.min "Permalink to this definition")

`mul`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.mul "Permalink to this definition")

`neg`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.neg "Permalink to this definition")

`pct_change`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.pct_change "Permalink to this definition")

`pow`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.pow "Permalink to this definition")

`radd`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.radd "Permalink to this definition")

`rdiv`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.rdiv "Permalink to this definition")

`rmul`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.rmul "Permalink to this definition")

`rolling`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.rolling "Permalink to this definition")

`rsub`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.rsub "Permalink to this definition")

`sqrt`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.sqrt "Permalink to this definition")

`square`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.square "Permalink to this definition")

`sub`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.float.FloatMixin.sub "Permalink to this definition")

########## Subpackages[¶](#subpackages "Permalink to this headline")

########### tensortrade.feed.api.float.window package[¶](#module-tensortrade.feed.api.float.window "Permalink to this headline")

############ Submodules[¶](#submodules "Permalink to this headline")

############# tensortrade.feed.api.float.window.ewm module[¶](#module-tensortrade.feed.api.float.window.ewm "Permalink to this headline")

ewm.py contains functions and classes for exponential weighted moving stream

operations.

*class* `tensortrade.feed.api.float.window.ewm.``EWM`(*com: float = None*, *span: float = None*, *halflife: float = None*, *alpha: float = None*, *min\_periods: int = 0*, *adjust: bool = True*, *ignore\_na: bool = False*)[[source]](_modules/tensortrade/feed/api/float/window/ewm.html#EWM)[¶](#tensortrade.feed.api.float.window.ewm.EWM "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](index.html#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

Provide exponential weighted (EW) functions.

Exactly one parameter: com, span, halflife, or alpha must be

provided.

| Parameters: | * **com** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *optional*) – Specify decay in terms of center of mass,

\(\alpha = 1 / (1 + com)\), for \(com \geq 0\).

* **span** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *optional*) – Specify decay in terms of span,

\(\alpha = 2 / (span + 1)\), for \(span \geq 1\).

* **halflife** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* [*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *timedelta**,* *optional*) – Specify decay in terms of half-life,

\(\alpha = 1 - \exp\left(-\ln(2) / halflife\right)\), for

\(halflife > 0\).

If `times` is specified, the time unit (str or timedelta) over which an

observation decays to half its value. Only applicable to `mean()`

and halflife value will not apply to the other functions.

* **alpha** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *optional*) – Specify smoothing factor \(\alpha\) directly,

\(0 < \alpha \leq 1\).

* **min\_periods** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 0*) – Minimum number of observations in window required to have a value

(otherwise result is NA).

* **adjust** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default True*) – Divide by decaying adjustment factor in beginning periods to account

for imbalance in relative weightings (viewing EWMA as a moving average).

- When `adjust=True` (default), the EW function is calculated using weights

\(w\_i = (1 - \alpha)^i\). For example, the EW moving average of the series

[\(x\_0, x\_1, ..., x\_t\)] would be:

\[y\_t = \frac{x\_t + (1 - \alpha)x\_{t-1} + (1 - \alpha)^2 x\_{t-2} + ... + (1 -

\alpha)^t x\_0}{1 + (1 - \alpha) + (1 - \alpha)^2 + ... + (1 - \alpha)^t}\]

	+ When `adjust=False`, the exponentially weighted function is calculated

	recursively:

\[\begin{split}\begin{split}

 y\_0 &= x\_0\\

 y\_t &= (1 - \alpha) y\_{t-1} + \alpha x\_t,

\end{split}\end{split}\]

* **ignore\_na** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default False*) – Ignore missing values when calculating weights.

- When `ignore\_na=False` (default), weights are based on absolute positions.

- When `ignore\_na=True`, weights are based on relative positions.

 |

See also

References

| [1] | <https://github.com/pandas-dev/pandas/blob/d9fff2792bf16178d4e450fe7384244e50635733/pandas/core/window/ewm.py#L65> |

`forward`() → Tuple[List[float], List[float]][[source]](_modules/tensortrade/feed/api/float/window/ewm.html#EWM.forward)[¶](#tensortrade.feed.api.float.window.ewm.EWM.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`has_next`() → bool[[source]](_modules/tensortrade/feed/api/float/window/ewm.html#EWM.has_next)[¶](#tensortrade.feed.api.float.window.ewm.EWM.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

`mean`() → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/window/ewm.html#EWM.mean)[¶](#tensortrade.feed.api.float.window.ewm.EWM.mean "Permalink to this definition")

Computes the exponential weighted moving average.

| Returns: | Stream[float] – The exponential weighted moving average stream based on the

underlying stream of values. |

`reset`() → None[[source]](_modules/tensortrade/feed/api/float/window/ewm.html#EWM.reset)[¶](#tensortrade.feed.api.float.window.ewm.EWM.reset "Permalink to this definition")

Resets all inputs to and listeners of the stream and sets stream value to None.

`std`(*bias=False*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/window/ewm.html#EWM.std)[¶](#tensortrade.feed.api.float.window.ewm.EWM.std "Permalink to this definition")

Computes the exponential weighted moving standard deviation.

| Returns: | Stream[float] – The exponential weighted moving standard deviation stream based on

the underlying stream of values. |

`var`(*bias=False*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/window/ewm.html#EWM.var)[¶](#tensortrade.feed.api.float.window.ewm.EWM.var "Permalink to this definition")

Computes the exponential weighted moving variance.

| Returns: | Stream[float] – The exponential weighted moving variance stream based on the

underlying stream of values. |

*class* `tensortrade.feed.api.float.window.ewm.``ExponentialWeightedMovingAverage`(*alpha: float*, *adjust: bool*, *ignore\_na: bool*, *min\_periods: int*)[[source]](_modules/tensortrade/feed/api/float/window/ewm.html#ExponentialWeightedMovingAverage)[¶](#tensortrade.feed.api.float.window.ewm.ExponentialWeightedMovingAverage "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](index.html#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

A stream operator that computes an exponential weighted moving average

on a given float stream.

| Parameters: | * **alpha** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The smoothing factor \(\alpha\) directly,

\(0 < \alpha \leq 1\).

* **adjust** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")) – Divide by decaying adjustment factor in beginning periods to account

for imbalance in relative weightings (viewing EWMA as a moving average).

* **ignore\_na** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")) – Ignore missing values when calculating weights.

* **min\_periods** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – Minimum number of observations in window required to have a value

(otherwise result is NA).

 |

References

| [1] | <https://github.com/pandas-dev/pandas/blob/d9fff2792bf16178d4e450fe7384244e50635733/pandas/_libs/window/aggregations.pyx#L1801> |

`forward`() → float[[source]](_modules/tensortrade/feed/api/float/window/ewm.html#ExponentialWeightedMovingAverage.forward)[¶](#tensortrade.feed.api.float.window.ewm.ExponentialWeightedMovingAverage.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`has_next`() → bool[[source]](_modules/tensortrade/feed/api/float/window/ewm.html#ExponentialWeightedMovingAverage.has_next)[¶](#tensortrade.feed.api.float.window.ewm.ExponentialWeightedMovingAverage.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

`reset`() → None[[source]](_modules/tensortrade/feed/api/float/window/ewm.html#ExponentialWeightedMovingAverage.reset)[¶](#tensortrade.feed.api.float.window.ewm.ExponentialWeightedMovingAverage.reset "Permalink to this definition")

Resets all inputs to and listeners of the stream and sets stream value to None.

*class* `tensortrade.feed.api.float.window.ewm.``ExponentialWeightedMovingCovariance`(*alpha: float*, *adjust: bool*, *ignore\_na: bool*, *min\_periods: int*, *bias: bool*)[[source]](_modules/tensortrade/feed/api/float/window/ewm.html#ExponentialWeightedMovingCovariance)[¶](#tensortrade.feed.api.float.window.ewm.ExponentialWeightedMovingCovariance "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](index.html#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

A stream operator that computes an exponential weighted moving average

on a given float stream.

| Parameters: | * **alpha** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The smoothing factor \(\alpha\) directly,

\(0 < \alpha \leq 1\).

* **adjust** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")) – Divide by decaying adjustment factor in beginning periods to account

for imbalance in relative weightings (viewing EWMA as a moving average).

* **ignore\_na** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")) – Ignore missing values when calculating weights.

* **min\_periods** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – Minimum number of observations in window required to have a value

(otherwise result is NA).

* **bias** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")) – Use a standard estimation bias correction

 |

`forward`() → float[[source]](_modules/tensortrade/feed/api/float/window/ewm.html#ExponentialWeightedMovingCovariance.forward)[¶](#tensortrade.feed.api.float.window.ewm.ExponentialWeightedMovingCovariance.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`has_next`() → bool[[source]](_modules/tensortrade/feed/api/float/window/ewm.html#ExponentialWeightedMovingCovariance.has_next)[¶](#tensortrade.feed.api.float.window.ewm.ExponentialWeightedMovingCovariance.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

`reset`() → None[[source]](_modules/tensortrade/feed/api/float/window/ewm.html#ExponentialWeightedMovingCovariance.reset)[¶](#tensortrade.feed.api.float.window.ewm.ExponentialWeightedMovingCovariance.reset "Permalink to this definition")

Resets all inputs to and listeners of the stream and sets stream value to None.

`tensortrade.feed.api.float.window.ewm.``ewm`(*s: tensortrade.feed.core.base.Stream[float][float], com: float = None, span: float = None, halflife: float = None, alpha: float = None, min\_periods: int = 0, adjust: bool = True, ignore\_na: bool = False*) → tensortrade.feed.core.base.Stream[typing.Tuple[typing.List[float], typing.List[float]]][Tuple[List[float], List[float]]][[source]](_modules/tensortrade/feed/api/float/window/ewm.html#ewm)[¶](#tensortrade.feed.api.float.window.ewm.ewm "Permalink to this definition")

Computes the weights and values in order to perform an exponential

weighted moving operation.

| Parameters: | * **s** (Stream[float]) – A float stream.

* **com** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *optional*) – Specify decay in terms of center of mass,

\(\alpha = 1 / (1 + com)\), for \(com \geq 0\).

* **span** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *optional*) – Specify decay in terms of span,

\(\alpha = 2 / (span + 1)\), for \(span \geq 1\).

* **halflife** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *optional*) – Specify decay in terms of half-life,

\(\alpha = 1 - \exp\left(-\ln(2) / halflife\right)\), for

\(halflife > 0\).

* **alpha** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *optional*) – Specify smoothing factor \(\alpha\) directly,

\(0 < \alpha \leq 1\).

* **min\_periods** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 0*) – Minimum number of observations in window required to have a value

(otherwise result is NA).

* **adjust** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default True*) – Divide by decaying adjustment factor in beginning periods to account

for imbalance in relative weightings (viewing EWMA as a moving average).

* **ignore\_na** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default False*) – Ignore missing values when calculating weights.

 |

| Returns: | Stream[Tuple[List[float], List[float]]] – A stream of weights and values to be used for computation of exponential

weighted moving operations. |

############# tensortrade.feed.api.float.window.expanding module[¶](#module-tensortrade.feed.api.float.window.expanding "Permalink to this headline")

expanding.py contains functions and classes for expanding stream operations.

*class* `tensortrade.feed.api.float.window.expanding.``Expanding`(*min\_periods: int = 1*)[[source]](_modules/tensortrade/feed/api/float/window/expanding.html#Expanding)[¶](#tensortrade.feed.api.float.window.expanding.Expanding "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](index.html#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

A stream that generates the entire history of a stream at each time step.

| Parameters: | **min\_periods** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1*) – The number of periods to wait before producing values from the aggregation

function. |

`agg`(*func: Callable[[List[float]], float]*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/window/expanding.html#Expanding.agg)[¶](#tensortrade.feed.api.float.window.expanding.Expanding.agg "Permalink to this definition")

Computes an aggregation of a stream’s history.

| Parameters: | **func** (Callable[[List[float]], float]) – A aggregation function. |

| Returns: | Stream[float] – A stream producing aggregations of the stream history at each time

step. |

`count`() → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/window/expanding.html#Expanding.count)[¶](#tensortrade.feed.api.float.window.expanding.Expanding.count "Permalink to this definition")

Computes an expanding count fo the underlying stream.

| Returns: | Stream[float] – An expanding count stream. |

`forward`() → List[float][[source]](_modules/tensortrade/feed/api/float/window/expanding.html#Expanding.forward)[¶](#tensortrade.feed.api.float.window.expanding.Expanding.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`generic_name` *= 'expanding'*[¶](#tensortrade.feed.api.float.window.expanding.Expanding.generic_name "Permalink to this definition")

`has_next`() → bool[[source]](_modules/tensortrade/feed/api/float/window/expanding.html#Expanding.has_next)[¶](#tensortrade.feed.api.float.window.expanding.Expanding.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

`max`() → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/window/expanding.html#Expanding.max)[¶](#tensortrade.feed.api.float.window.expanding.Expanding.max "Permalink to this definition")

Computes an expanding maximum fo the underlying stream.

| Returns: | Stream[float] – An expanding maximum stream. |

`mean`() → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/window/expanding.html#Expanding.mean)[¶](#tensortrade.feed.api.float.window.expanding.Expanding.mean "Permalink to this definition")

Computes an expanding mean fo the underlying stream.

| Returns: | Stream[float] – An expanding mean stream. |

`median`() → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/window/expanding.html#Expanding.median)[¶](#tensortrade.feed.api.float.window.expanding.Expanding.median "Permalink to this definition")

Computes an expanding median fo the underlying stream.

| Returns: | Stream[float] – An expanding median stream. |

`min`() → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/window/expanding.html#Expanding.min)[¶](#tensortrade.feed.api.float.window.expanding.Expanding.min "Permalink to this definition")

Computes an expanding minimum fo the underlying stream.

| Returns: | Stream[float] – An expanding minimum stream. |

`reset`() → None[[source]](_modules/tensortrade/feed/api/float/window/expanding.html#Expanding.reset)[¶](#tensortrade.feed.api.float.window.expanding.Expanding.reset "Permalink to this definition")

Resets all inputs to and listeners of the stream and sets stream value to None.

`std`() → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/window/expanding.html#Expanding.std)[¶](#tensortrade.feed.api.float.window.expanding.Expanding.std "Permalink to this definition")

Computes an expanding standard deviation fo the underlying stream.

| Returns: | Stream[float] – An expanding standard deviation stream. |

`sum`() → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/window/expanding.html#Expanding.sum)[¶](#tensortrade.feed.api.float.window.expanding.Expanding.sum "Permalink to this definition")

Computes an expanding sum fo the underlying stream.

| Returns: | Stream[float] – An expanding sum stream. |

`var`() → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/window/expanding.html#Expanding.var)[¶](#tensortrade.feed.api.float.window.expanding.Expanding.var "Permalink to this definition")

Computes an expanding variance fo the underlying stream.

| Returns: | Stream[float] – An expanding variance stream. |

*class* `tensortrade.feed.api.float.window.expanding.``ExpandingCount`[[source]](_modules/tensortrade/feed/api/float/window/expanding.html#ExpandingCount)[¶](#tensortrade.feed.api.float.window.expanding.ExpandingCount "Permalink to this definition")

Bases: [`tensortrade.feed.api.float.window.expanding.ExpandingNode`](#tensortrade.feed.api.float.window.expanding.ExpandingNode "tensortrade.feed.api.float.window.expanding.ExpandingNode")

A stream operator that counts the number of non-missing values.

`forward`() → float[[source]](_modules/tensortrade/feed/api/float/window/expanding.html#ExpandingCount.forward)[¶](#tensortrade.feed.api.float.window.expanding.ExpandingCount.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

*class* `tensortrade.feed.api.float.window.expanding.``ExpandingNode`(*func: Callable[[List[float]], float]*)[[source]](_modules/tensortrade/feed/api/float/window/expanding.html#ExpandingNode)[¶](#tensortrade.feed.api.float.window.expanding.ExpandingNode "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](index.html#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

A stream operator for aggregating an entire history of a stream.

| Parameters: | **func** (Callable[[List[float]], float]) – A function that aggregates the history of a stream. |

`forward`() → float[[source]](_modules/tensortrade/feed/api/float/window/expanding.html#ExpandingNode.forward)[¶](#tensortrade.feed.api.float.window.expanding.ExpandingNode.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`has_next`()[[source]](_modules/tensortrade/feed/api/float/window/expanding.html#ExpandingNode.has_next)[¶](#tensortrade.feed.api.float.window.expanding.ExpandingNode.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

`tensortrade.feed.api.float.window.expanding.``expanding`(*s: tensortrade.feed.core.base.Stream[float][float], min\_periods: int = 1*) → tensortrade.feed.core.base.Stream[typing.List[float]][List[float]][[source]](_modules/tensortrade/feed/api/float/window/expanding.html#expanding)[¶](#tensortrade.feed.api.float.window.expanding.expanding "Permalink to this definition")

Computes a stream that generates the entire history of a stream at each

time step.

| Parameters: | * **s** (Stream[float]) – A float stream.

* **min\_periods** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1*) – The number of periods to wait before producing values from the aggregation

function.

 |

############# tensortrade.feed.api.float.window.rolling module[¶](#module-tensortrade.feed.api.float.window.rolling "Permalink to this headline")

rolling.py contains functions and classes for rolling stream operations.

*class* `tensortrade.feed.api.float.window.rolling.``Rolling`(*window: int*, *min\_periods: int = 1*)[[source]](_modules/tensortrade/feed/api/float/window/rolling.html#Rolling)[¶](#tensortrade.feed.api.float.window.rolling.Rolling "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](index.html#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

A stream that generates a rolling window of values from a stream.

| Parameters: | * **window** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The size of the rolling window.

* **min\_periods** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1*) – The number of periods to wait before producing values from the aggregation

function.

 |

`agg`(*func: Callable[[List[float]], float]*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/window/rolling.html#Rolling.agg)[¶](#tensortrade.feed.api.float.window.rolling.Rolling.agg "Permalink to this definition")

Computes an aggregation of a rolling window of values.

| Parameters: | **func** (Callable[[List[float]], float]) – A aggregation function. |

| Returns: | Stream[float] – A stream producing aggregations of a rolling window of values. |

`count`() → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/window/rolling.html#Rolling.count)[¶](#tensortrade.feed.api.float.window.rolling.Rolling.count "Permalink to this definition")

Computes a rolling count from the underlying stream.

| Returns: | Stream[float] – A rolling count stream. |

`forward`() → List[float][[source]](_modules/tensortrade/feed/api/float/window/rolling.html#Rolling.forward)[¶](#tensortrade.feed.api.float.window.rolling.Rolling.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`generic_name` *= 'rolling'*[¶](#tensortrade.feed.api.float.window.rolling.Rolling.generic_name "Permalink to this definition")

`has_next`() → bool[[source]](_modules/tensortrade/feed/api/float/window/rolling.html#Rolling.has_next)[¶](#tensortrade.feed.api.float.window.rolling.Rolling.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

`max`() → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/window/rolling.html#Rolling.max)[¶](#tensortrade.feed.api.float.window.rolling.Rolling.max "Permalink to this definition")

Computes a rolling maximum from the underlying stream.

| Returns: | Stream[float] – A rolling maximum stream. |

`mean`() → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/window/rolling.html#Rolling.mean)[¶](#tensortrade.feed.api.float.window.rolling.Rolling.mean "Permalink to this definition")

Computes a rolling mean from the underlying stream.

| Returns: | Stream[float] – A rolling mean stream. |

`median`() → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/window/rolling.html#Rolling.median)[¶](#tensortrade.feed.api.float.window.rolling.Rolling.median "Permalink to this definition")

Computes a rolling median from the underlying stream.

| Returns: | Stream[float] – A rolling median stream. |

`min`() → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/window/rolling.html#Rolling.min)[¶](#tensortrade.feed.api.float.window.rolling.Rolling.min "Permalink to this definition")

Computes a rolling minimum from the underlying stream.

| Returns: | Stream[float] – A rolling minimum stream. |

`reset`() → None[[source]](_modules/tensortrade/feed/api/float/window/rolling.html#Rolling.reset)[¶](#tensortrade.feed.api.float.window.rolling.Rolling.reset "Permalink to this definition")

Resets all inputs to and listeners of the stream and sets stream value to None.

`std`() → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/window/rolling.html#Rolling.std)[¶](#tensortrade.feed.api.float.window.rolling.Rolling.std "Permalink to this definition")

Computes a rolling standard deviation from the underlying stream.

| Returns: | Stream[float] – A rolling standard deviation stream. |

`sum`() → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/window/rolling.html#Rolling.sum)[¶](#tensortrade.feed.api.float.window.rolling.Rolling.sum "Permalink to this definition")

Computes a rolling sum from the underlying stream.

| Returns: | Stream[float] – A rolling sum stream. |

`var`() → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/window/rolling.html#Rolling.var)[¶](#tensortrade.feed.api.float.window.rolling.Rolling.var "Permalink to this definition")

Computes a rolling variance from the underlying stream.

| Returns: | Stream[float] – A rolling variance stream. |

*class* `tensortrade.feed.api.float.window.rolling.``RollingCount`[[source]](_modules/tensortrade/feed/api/float/window/rolling.html#RollingCount)[¶](#tensortrade.feed.api.float.window.rolling.RollingCount "Permalink to this definition")

Bases: [`tensortrade.feed.api.float.window.rolling.RollingNode`](#tensortrade.feed.api.float.window.rolling.RollingNode "tensortrade.feed.api.float.window.rolling.RollingNode")

A stream operator that counts the number of non-missing values in the

rolling window.

`forward`()[[source]](_modules/tensortrade/feed/api/float/window/rolling.html#RollingCount.forward)[¶](#tensortrade.feed.api.float.window.rolling.RollingCount.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

*class* `tensortrade.feed.api.float.window.rolling.``RollingNode`(*func: Callable[[List[float]], float]*)[[source]](_modules/tensortrade/feed/api/float/window/rolling.html#RollingNode)[¶](#tensortrade.feed.api.float.window.rolling.RollingNode "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](index.html#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

A stream operator for aggregating a rolling window of a stream.

| Parameters: | **func** (Callable[[List[float]], float]) – A function that aggregates a rolling window. |

`forward`() → float[[source]](_modules/tensortrade/feed/api/float/window/rolling.html#RollingNode.forward)[¶](#tensortrade.feed.api.float.window.rolling.RollingNode.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`has_next`() → bool[[source]](_modules/tensortrade/feed/api/float/window/rolling.html#RollingNode.has_next)[¶](#tensortrade.feed.api.float.window.rolling.RollingNode.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

`reset`() → None[[source]](_modules/tensortrade/feed/api/float/window/rolling.html#RollingNode.reset)[¶](#tensortrade.feed.api.float.window.rolling.RollingNode.reset "Permalink to this definition")

Resets all inputs to and listeners of the stream and sets stream value to None.

`tensortrade.feed.api.float.window.rolling.``rolling`(*s: tensortrade.feed.core.base.Stream[float][float], window: int, min\_periods: int = 1*) → tensortrade.feed.core.base.Stream[typing.List[float]][List[float]][[source]](_modules/tensortrade/feed/api/float/window/rolling.html#rolling)[¶](#tensortrade.feed.api.float.window.rolling.rolling "Permalink to this definition")

Creates a stream that generates a rolling window of values from a stream.

| Parameters: | * **s** (Stream[float]) – A float stream.

* **window** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The size of the rolling window.

* **min\_periods** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1*) – The number of periods to wait before producing values from the aggregation

function.

 |

########## Submodules[¶](#submodules "Permalink to this headline")

########### tensortrade.feed.api.float.accumulators module[¶](#module-tensortrade.feed.api.float.accumulators "Permalink to this headline")

*class* `tensortrade.feed.api.float.accumulators.``CumMax`(*skip\_na: bool = True*)[[source]](_modules/tensortrade/feed/api/float/accumulators.html#CumMax)[¶](#tensortrade.feed.api.float.accumulators.CumMax "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](index.html#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

A stream operator that creates a cumulative maximum of values.

| Parameters: | **skip\_na** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default True*) – Exclude NA/null values. If a value is NA, the result will be NA. |

References

[1] <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.cummax.html>

`forward`() → float[[source]](_modules/tensortrade/feed/api/float/accumulators.html#CumMax.forward)[¶](#tensortrade.feed.api.float.accumulators.CumMax.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`has_next`() → bool[[source]](_modules/tensortrade/feed/api/float/accumulators.html#CumMax.has_next)[¶](#tensortrade.feed.api.float.accumulators.CumMax.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

*class* `tensortrade.feed.api.float.accumulators.``CumMin`(*skip\_na: bool = True*)[[source]](_modules/tensortrade/feed/api/float/accumulators.html#CumMin)[¶](#tensortrade.feed.api.float.accumulators.CumMin "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](index.html#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

A stream operator that creates a cumulative minimum of values.

| Parameters: | **skip\_na** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default True*) – Exclude NA/null values. If a value is NA, the result will be NA. |

References

[1] <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.cummin.html>

`forward`() → float[[source]](_modules/tensortrade/feed/api/float/accumulators.html#CumMin.forward)[¶](#tensortrade.feed.api.float.accumulators.CumMin.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`has_next`() → bool[[source]](_modules/tensortrade/feed/api/float/accumulators.html#CumMin.has_next)[¶](#tensortrade.feed.api.float.accumulators.CumMin.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

*class* `tensortrade.feed.api.float.accumulators.``CumProd`[[source]](_modules/tensortrade/feed/api/float/accumulators.html#CumProd)[¶](#tensortrade.feed.api.float.accumulators.CumProd "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](index.html#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

A stream operator that creates a cumulative product of values.

References

| [1] | <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.cumprod.html> |

`forward`() → float[[source]](_modules/tensortrade/feed/api/float/accumulators.html#CumProd.forward)[¶](#tensortrade.feed.api.float.accumulators.CumProd.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`has_next`() → bool[[source]](_modules/tensortrade/feed/api/float/accumulators.html#CumProd.has_next)[¶](#tensortrade.feed.api.float.accumulators.CumProd.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

*class* `tensortrade.feed.api.float.accumulators.``CumSum`[[source]](_modules/tensortrade/feed/api/float/accumulators.html#CumSum)[¶](#tensortrade.feed.api.float.accumulators.CumSum "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](index.html#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

A stream operator that creates a cumulative sum of values.

References

| [1] | <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.cumsum.html> |

`forward`() → float[[source]](_modules/tensortrade/feed/api/float/accumulators.html#CumSum.forward)[¶](#tensortrade.feed.api.float.accumulators.CumSum.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`has_next`() → bool[[source]](_modules/tensortrade/feed/api/float/accumulators.html#CumSum.has_next)[¶](#tensortrade.feed.api.float.accumulators.CumSum.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

`tensortrade.feed.api.float.accumulators.``cummax`(*s: tensortrade.feed.core.base.Stream[float][float], skipna: bool = True*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/accumulators.html#cummax)[¶](#tensortrade.feed.api.float.accumulators.cummax "Permalink to this definition")

Computes the cumulative maximum of a stream.

| Parameters: | * **s** (Stream[float]) – A float stream.

* **skipna** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default True*) – Exclude NA/null values. If a value is NA, the result will be NA.

 |

| Returns: | Stream[float] – The cumulative maximum stream of s. |

`tensortrade.feed.api.float.accumulators.``cummin`(*s: tensortrade.feed.core.base.Stream[float][float], skipna: bool = True*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/accumulators.html#cummin)[¶](#tensortrade.feed.api.float.accumulators.cummin "Permalink to this definition")

Computes the cumulative minimum of a stream.

| Parameters: | * **s** (Stream[float]) – A float stream.

* **skipna** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default True*) – Exclude NA/null values. If a value is NA, the result will be NA.

 |

| Returns: | Stream[float] – The cumulative minimum stream of s. |

`tensortrade.feed.api.float.accumulators.``cumprod`(*s: tensortrade.feed.core.base.Stream[float][float]*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/accumulators.html#cumprod)[¶](#tensortrade.feed.api.float.accumulators.cumprod "Permalink to this definition")

Computes the cumulative product of a stream.

| Parameters: | **s** (Stream[float]) – A float stream. |

| Returns: | Stream[float] – The cumulative product stream of s. |

`tensortrade.feed.api.float.accumulators.``cumsum`(*s: tensortrade.feed.core.base.Stream[float][float]*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/accumulators.html#cumsum)[¶](#tensortrade.feed.api.float.accumulators.cumsum "Permalink to this definition")

Computes the cumulative sum of a stream.

| Parameters: | **s** (Stream[float]) – A float stream. |

| Returns: | Stream[float] – The cumulative sum stream of s. |

########### tensortrade.feed.api.float.imputation module[¶](#module-tensortrade.feed.api.float.imputation "Permalink to this headline")

`tensortrade.feed.api.float.imputation.``ffill`(*s: tensortrade.feed.core.base.Stream[float][float]*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/imputation.html#ffill)[¶](#tensortrade.feed.api.float.imputation.ffill "Permalink to this definition")

Fill in missing values by forward filling.

| Parameters: | **s** (Stream[float]) – A float stream. |

| Returns: | Stream[float] – An imputed stream via forward filling. |

`tensortrade.feed.api.float.imputation.``fillna`(*s: tensortrade.feed.core.base.Stream[float][float], fill\_value: float = 0.0*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/imputation.html#fillna)[¶](#tensortrade.feed.api.float.imputation.fillna "Permalink to this definition")

Fill in missing values with a fill value.

| Parameters: | * **s** (Stream[float]) – A float stream.

* **fill\_value** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – A value to fill in missing values with.

 |

| Returns: | Stream[float] – An imputed stream via padding. |

########### tensortrade.feed.api.float.operations module[¶](#module-tensortrade.feed.api.float.operations "Permalink to this headline")

operations.py contains functions for computing arithmetic operations on float

streams.

`tensortrade.feed.api.float.operations.``abs`(*s: tensortrade.feed.core.base.Stream[float][float]*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/operations.html#abs)[¶](#tensortrade.feed.api.float.operations.abs "Permalink to this definition")

Computes the absolute value of a float stream.

| Parameters: | **s** (Stream[float]) – A float stream. |

| Returns: | Stream[float] – The absolute value stream of s. |

`tensortrade.feed.api.float.operations.``add`(*s1: tensortrade.feed.core.base.Stream[float][float], s2: tensortrade.feed.core.base.Stream[float][float]*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/operations.html#add)[¶](#tensortrade.feed.api.float.operations.add "Permalink to this definition")

Computes the addition of two float streams.

| Parameters: | * **s1** (Stream[float]) – The first float stream.

* **s2** (Stream[float] or float) – The second float stream.

 |

| Returns: | Stream[float] – A stream created from adding s1 and s2. |

`tensortrade.feed.api.float.operations.``mul`(*s1: tensortrade.feed.core.base.Stream[float][float], s2: tensortrade.feed.core.base.Stream[float][float]*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/operations.html#mul)[¶](#tensortrade.feed.api.float.operations.mul "Permalink to this definition")

Computes the multiplication of two float streams.

| Parameters: | * **s1** (Stream[float]) – The first float stream.

* **s2** (Stream[float] or float) – The second float stream.

 |

| Returns: | Stream[float] – A stream created from multiplying s1 and s2. |

`tensortrade.feed.api.float.operations.``neg`(*s: tensortrade.feed.core.base.Stream[float][float]*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/operations.html#neg)[¶](#tensortrade.feed.api.float.operations.neg "Permalink to this definition")

Computes the negation of a float stream.

| Parameters: | **s** (Stream[float]) – A float stream. |

| Returns: | Stream[float] – The negated stream of s. |

`tensortrade.feed.api.float.operations.``pow`(*s: tensortrade.feed.core.base.Stream[float][float], power: float*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/operations.html#pow)[¶](#tensortrade.feed.api.float.operations.pow "Permalink to this definition")

Computes the power of a float stream.

| Parameters: | * **s** (Stream[float]) – A float stream.

* **power** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The power to raise s by.

 |

| Returns: | Stream[float] – The power stream of s. |

`tensortrade.feed.api.float.operations.``radd`(*s1: tensortrade.feed.core.base.Stream[float][float], s2: tensortrade.feed.core.base.Stream[float][float]*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/operations.html#radd)[¶](#tensortrade.feed.api.float.operations.radd "Permalink to this definition")

Computes the reversed addition of two float streams.

| Parameters: | * **s1** (Stream[float]) – The first float stream.

* **s2** (Stream[float] or float) – The second float stream.

 |

| Returns: | Stream[float] – A stream created from adding s1 and s2. |

`tensortrade.feed.api.float.operations.``rmul`(*s1: tensortrade.feed.core.base.Stream[float][float], s2: tensortrade.feed.core.base.Stream[float][float]*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/operations.html#rmul)[¶](#tensortrade.feed.api.float.operations.rmul "Permalink to this definition")

Computes the reverse multiplication of two float streams.

| Parameters: | * **s1** (Stream[float]) – The first float stream.

* **s2** (Stream[float] or float) – The second float stream.

 |

| Returns: | Stream[float] – A stream created from multiplying s2 and s1. |

`tensortrade.feed.api.float.operations.``rsub`(*s1: tensortrade.feed.core.base.Stream[float][float], s2: tensortrade.feed.core.base.Stream[float][float]*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/operations.html#rsub)[¶](#tensortrade.feed.api.float.operations.rsub "Permalink to this definition")

Computes the reverse subtraction of two float streams.

| Parameters: | * **s1** (Stream[float]) – The first float stream.

* **s2** (Stream[float] or float) – The second float stream.

 |

| Returns: | Stream[float] – A stream created from subtracting s1 from s2. |

`tensortrade.feed.api.float.operations.``rtruediv`(*s1: tensortrade.feed.core.base.Stream[float][float], s2: tensortrade.feed.core.base.Stream[float][float]*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/operations.html#rtruediv)[¶](#tensortrade.feed.api.float.operations.rtruediv "Permalink to this definition")

Computes the reverse division of two float streams.

| Parameters: | * **s1** (Stream[float]) – The first float stream.

* **s2** (Stream[float] or float) – The second float stream.

 |

| Returns: | Stream[float] – A stream created from dividing s2 by s1. |

`tensortrade.feed.api.float.operations.``sub`(*s1: tensortrade.feed.core.base.Stream[float][float], s2: tensortrade.feed.core.base.Stream[float][float]*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/operations.html#sub)[¶](#tensortrade.feed.api.float.operations.sub "Permalink to this definition")

Computes the subtraction of two float streams.

| Parameters: | * **s1** (Stream[float]) – The first float stream.

* **s2** (Stream[float] or float) – The second float stream.

 |

| Returns: | Stream[float] – A stream created from subtracting s2 from s1. |

`tensortrade.feed.api.float.operations.``truediv`(*s1: tensortrade.feed.core.base.Stream[float][float], s2: tensortrade.feed.core.base.Stream[float][float]*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/operations.html#truediv)[¶](#tensortrade.feed.api.float.operations.truediv "Permalink to this definition")

Computes the division of two float streams.

| Parameters: | * **s1** (Stream[float]) – The first float stream.

* **s2** (Stream[float] or float) – The second float stream.

 |

| Returns: | Stream[float] – A stream created from dividing s1 by s2. |

########### tensortrade.feed.api.float.ordering module[¶](#module-tensortrade.feed.api.float.ordering "Permalink to this headline")

`tensortrade.feed.api.float.ordering.``clamp`(*s: tensortrade.feed.core.base.Stream[float][float], c\_min: float, c\_max: float*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/ordering.html#clamp)[¶](#tensortrade.feed.api.float.ordering.clamp "Permalink to this definition")

Clamps the minimum and maximum value of a stream.

| Parameters: | * **s** (Stream[float]) – A float stream.

* **c\_min** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The mimimum value to clamp by.

* **c\_max** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The maximum value to clamp by.

 |

| Returns: | Stream[float] – The clamped stream of s. |

`tensortrade.feed.api.float.ordering.``clamp_max`(*s: tensortrade.feed.core.base.Stream[float][float], c\_max: float*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/ordering.html#clamp_max)[¶](#tensortrade.feed.api.float.ordering.clamp_max "Permalink to this definition")

Clamps the maximum value of a stream.

| Parameters: | * **s** (Stream[float]) – A float stream.

* **c\_max** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The maximum value to clamp by.

 |

| Returns: | Stream[float] – The maximum clamped stream of s. |

`tensortrade.feed.api.float.ordering.``clamp_min`(*s: tensortrade.feed.core.base.Stream[float][float], c\_min: float*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/ordering.html#clamp_min)[¶](#tensortrade.feed.api.float.ordering.clamp_min "Permalink to this definition")

Clamps the minimum value of a stream.

| Parameters: | * **s** (Stream[float]) – A float stream.

* **c\_min** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The mimimum value to clamp by.

 |

| Returns: | Stream[float] – The minimum clamped stream of s. |

`tensortrade.feed.api.float.ordering.``max`(*s1: tensortrade.feed.core.base.Stream[float][float], s2: tensortrade.feed.core.base.Stream[float][float]*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/ordering.html#max)[¶](#tensortrade.feed.api.float.ordering.max "Permalink to this definition")

Computes the maximum of two streams.

| Parameters: | * **s1** (Stream[float]) – The first float stream.

* **s2** (Stream[float]) – The second float stream.

 |

| Returns: | Stream[float] – The maximum stream of s1 and s2. |

`tensortrade.feed.api.float.ordering.``min`(*s1: tensortrade.feed.core.base.Stream[float][float], s2: tensortrade.feed.core.base.Stream[float][float]*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/ordering.html#min)[¶](#tensortrade.feed.api.float.ordering.min "Permalink to this definition")

Computes the minimum of two streams.

| Parameters: | * **s1** (Stream[float]) – The first float stream.

* **s2** (Stream[float]) – The second float stream.

 |

| Returns: | Stream[float] – The minimum stream of s1 and s2. |

########### tensortrade.feed.api.float.utils module[¶](#module-tensortrade.feed.api.float.utils "Permalink to this headline")

`tensortrade.feed.api.float.utils.``ceil`(*s: tensortrade.feed.core.base.Stream[float][float]*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/utils.html#ceil)[¶](#tensortrade.feed.api.float.utils.ceil "Permalink to this definition")

Computes the ceiling of a float stream.

| Parameters: | **s** (Stream[float]) – A float stream. |

| Returns: | Stream[float] – The ceiling stream of s. |

`tensortrade.feed.api.float.utils.``diff`(*s: tensortrade.feed.core.base.Stream[float][float], periods: int = 1*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/utils.html#diff)[¶](#tensortrade.feed.api.float.utils.diff "Permalink to this definition")

Computes the difference of a float stream.

| Parameters: | * **s** (Stream[float]) – A float stream.

* **periods** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1*) – The number of periods to lag for until computing the difference.

 |

| Returns: | Stream[float] – The difference stream of s. |

`tensortrade.feed.api.float.utils.``floor`(*s: tensortrade.feed.core.base.Stream[float][float]*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/utils.html#floor)[¶](#tensortrade.feed.api.float.utils.floor "Permalink to this definition")

Computes the floor of a float stream.

| Parameters: | **s** (Stream[float]) – A float stream. |

| Returns: | Stream[float] – The floor stream of s. |

`tensortrade.feed.api.float.utils.``log`(*s: tensortrade.feed.core.base.Stream[float][float]*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/utils.html#log)[¶](#tensortrade.feed.api.float.utils.log "Permalink to this definition")

Computes the log of a float stream.

| Parameters: | **s** (Stream[float]) – A float stream. |

| Returns: | Stream[float] – The log stream of s. |

`tensortrade.feed.api.float.utils.``pct_change`(*s: tensortrade.feed.core.base.Stream[float][float], periods: int = 1, fill\_method: str = 'pad'*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/utils.html#pct_change)[¶](#tensortrade.feed.api.float.utils.pct_change "Permalink to this definition")

Computes the percent change of a float stream.

| Parameters: | * **s** (Stream[float]) – A float stream.

* **periods** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1*) – The number of periods to lag for until computing the percent change.

* **fill\_method** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *default "pad"*) – The fill method to use for missing values.

 |

| Returns: | Stream[float] – The percent change stream of s. |

`tensortrade.feed.api.float.utils.``sqrt`(*s: tensortrade.feed.core.base.Stream[float][float]*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/utils.html#sqrt)[¶](#tensortrade.feed.api.float.utils.sqrt "Permalink to this definition")

Computes the square root of a float stream.

| Parameters: | **s** (Stream[float]) – A float stream. |

| Returns: | Stream[float] – The square root stream of s. |

`tensortrade.feed.api.float.utils.``square`(*s: tensortrade.feed.core.base.Stream[float][float]*) → tensortrade.feed.core.base.Stream[float][float][[source]](_modules/tensortrade/feed/api/float/utils.html#square)[¶](#tensortrade.feed.api.float.utils.square "Permalink to this definition")

Computes the square of a float stream.

| Parameters: | **s** (Stream[float]) – A float stream. |

| Returns: | Stream[float] – The square stream of s. |

######### tensortrade.feed.api.generic package[¶](#module-tensortrade.feed.api.generic "Permalink to this headline")

########## Submodules[¶](#submodules "Permalink to this headline")

########### tensortrade.feed.api.generic.imputation module[¶](#module-tensortrade.feed.api.generic.imputation "Permalink to this headline")

imputation.py contains classes for imputation stream operations.

*class* `tensortrade.feed.api.generic.imputation.``FillNa`(*fill\_value: T*)[[source]](_modules/tensortrade/feed/api/generic/imputation.html#FillNa)[¶](#tensortrade.feed.api.generic.imputation.FillNa "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](index.html#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

A stream operator that computes the padded imputation of a stream.

| Parameters: | **fill\_value** (T) – The fill value to use for missing values in the stream. |

`forward`() → T[[source]](_modules/tensortrade/feed/api/generic/imputation.html#FillNa.forward)[¶](#tensortrade.feed.api.generic.imputation.FillNa.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`generic_name` *= 'fillna'*[¶](#tensortrade.feed.api.generic.imputation.FillNa.generic_name "Permalink to this definition")

`has_next`() → bool[[source]](_modules/tensortrade/feed/api/generic/imputation.html#FillNa.has_next)[¶](#tensortrade.feed.api.generic.imputation.FillNa.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

*class* `tensortrade.feed.api.generic.imputation.``ForwardFill`[[source]](_modules/tensortrade/feed/api/generic/imputation.html#ForwardFill)[¶](#tensortrade.feed.api.generic.imputation.ForwardFill "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](index.html#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

A stream operator that computes the forward fill imputation of a stream.

`forward`() → T[[source]](_modules/tensortrade/feed/api/generic/imputation.html#ForwardFill.forward)[¶](#tensortrade.feed.api.generic.imputation.ForwardFill.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`generic_name` *= 'ffill'*[¶](#tensortrade.feed.api.generic.imputation.ForwardFill.generic_name "Permalink to this definition")

`has_next`() → bool[[source]](_modules/tensortrade/feed/api/generic/imputation.html#ForwardFill.has_next)[¶](#tensortrade.feed.api.generic.imputation.ForwardFill.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

########### tensortrade.feed.api.generic.operators module[¶](#module-tensortrade.feed.api.generic.operators "Permalink to this headline")

operators.py contains function for generic stream operators.

########### tensortrade.feed.api.generic.reduce module[¶](#module-tensortrade.feed.api.generic.reduce "Permalink to this headline")

reduce.py contains functions and classes for reducing multiple streams

into a single stream.

*class* `tensortrade.feed.api.generic.reduce.``Aggregate`(*func: Callable[[List[T]], T]*)[[source]](_modules/tensortrade/feed/api/generic/reduce.html#Aggregate)[¶](#tensortrade.feed.api.generic.reduce.Aggregate "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](index.html#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

A multi-stream operator for aggregating multiple streams into a single stream.

| Parameters: | **func** (Callable[[List[Stream]], T]) – A function for aggregating the value of multiple streams. |

`forward`() → T[[source]](_modules/tensortrade/feed/api/generic/reduce.html#Aggregate.forward)[¶](#tensortrade.feed.api.generic.reduce.Aggregate.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`generic_name` *= 'reduce'*[¶](#tensortrade.feed.api.generic.reduce.Aggregate.generic_name "Permalink to this definition")

`has_next`() → bool[[source]](_modules/tensortrade/feed/api/generic/reduce.html#Aggregate.has_next)[¶](#tensortrade.feed.api.generic.reduce.Aggregate.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

*class* `tensortrade.feed.api.generic.reduce.``Reduce`(*dtype: str = None*)[[source]](_modules/tensortrade/feed/api/generic/reduce.html#Reduce)[¶](#tensortrade.feed.api.generic.reduce.Reduce "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](index.html#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

A stream for reducing multiple streams of the same type.

| Parameters: | **dtype** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *optional*) – The data type of the aggregated stream. |

`agg`(*func: Callable[[List[T]], T]*) → tensortrade.feed.core.base.Stream[~T][T][[source]](_modules/tensortrade/feed/api/generic/reduce.html#Reduce.agg)[¶](#tensortrade.feed.api.generic.reduce.Reduce.agg "Permalink to this definition")

Computes the aggregation of the input streams.

| Returns: | Stream[T] – An aggregated stream of the input streams. |

`forward`() → List[T][[source]](_modules/tensortrade/feed/api/generic/reduce.html#Reduce.forward)[¶](#tensortrade.feed.api.generic.reduce.Reduce.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`has_next`() → bool[[source]](_modules/tensortrade/feed/api/generic/reduce.html#Reduce.has_next)[¶](#tensortrade.feed.api.generic.reduce.Reduce.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

`max`() → tensortrade.feed.core.base.Stream[~T][T][[source]](_modules/tensortrade/feed/api/generic/reduce.html#Reduce.max)[¶](#tensortrade.feed.api.generic.reduce.Reduce.max "Permalink to this definition")

Computes the reduced maximum of the input streams.

| Returns: | Stream[T] – A reduced maximum stream. |

`min`() → tensortrade.feed.core.base.Stream[~T][T][[source]](_modules/tensortrade/feed/api/generic/reduce.html#Reduce.min)[¶](#tensortrade.feed.api.generic.reduce.Reduce.min "Permalink to this definition")

Computes the reduced minimum of the input streams.

| Returns: | Stream[T] – A reduced minimum stream. |

`prod`() → tensortrade.feed.core.base.Stream[~T][T][[source]](_modules/tensortrade/feed/api/generic/reduce.html#Reduce.prod)[¶](#tensortrade.feed.api.generic.reduce.Reduce.prod "Permalink to this definition")

Computes the reduced product of the input streams.

| Returns: | Stream[T] – A reduced product stream. |

`sum`() → tensortrade.feed.core.base.Stream[~T][T][[source]](_modules/tensortrade/feed/api/generic/reduce.html#Reduce.sum)[¶](#tensortrade.feed.api.generic.reduce.Reduce.sum "Permalink to this definition")

Computes the reduced sum of the input streams.

| Returns: | Stream[T] – A reduced sum stream. |

########### tensortrade.feed.api.generic.warmup module[¶](#module-tensortrade.feed.api.generic.warmup "Permalink to this headline")

warmup.py contains classes for warm up stream operations.

*class* `tensortrade.feed.api.generic.warmup.``WarmUp`(*periods: int*)[[source]](_modules/tensortrade/feed/api/generic/warmup.html#WarmUp)[¶](#tensortrade.feed.api.generic.warmup.WarmUp "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](index.html#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

A stream operator for warming up a given stream.

| Parameters: | **periods** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – Number of periods to warm up. |

`forward`() → T[[source]](_modules/tensortrade/feed/api/generic/warmup.html#WarmUp.forward)[¶](#tensortrade.feed.api.generic.warmup.WarmUp.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`has_next`() → bool[[source]](_modules/tensortrade/feed/api/generic/warmup.html#WarmUp.has_next)[¶](#tensortrade.feed.api.generic.warmup.WarmUp.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

`reset`() → None[[source]](_modules/tensortrade/feed/api/generic/warmup.html#WarmUp.reset)[¶](#tensortrade.feed.api.generic.warmup.WarmUp.reset "Permalink to this definition")

Resets all inputs to and listeners of the stream and sets stream value to None.

######### tensortrade.feed.api.string package[¶](#module-tensortrade.feed.api.string "Permalink to this headline")

*class* `tensortrade.feed.api.string.``String`[[source]](_modules/tensortrade/feed/api/string.html#String)[¶](#tensortrade.feed.api.string.String "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

A class to register accessor and instance methods.

*classmethod* `register`(*names: List[str]*)[[source]](_modules/tensortrade/feed/api/string.html#String.register)[¶](#tensortrade.feed.api.string.String.register "Permalink to this definition")

A function decorator that adds accessor and instance methods for

specified data type.

| Parameters: | **names** (List[str]) – A list of names used to register the function as a method. |

| Returns: | *Callable* – A decorated function. |

*class* `tensortrade.feed.api.string.``StringMethods`(*stream: Stream*)[[source]](_modules/tensortrade/feed/api/string.html#StringMethods)[¶](#tensortrade.feed.api.string.StringMethods "Permalink to this definition")

Bases: [`tensortrade.feed.core.methods.Methods`](index.html#tensortrade.feed.core.methods.Methods "tensortrade.feed.core.methods.Methods")

`capitalize`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.string.StringMethods.capitalize "Permalink to this definition")

`cat`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.string.StringMethods.cat "Permalink to this definition")

`endswith`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.string.StringMethods.endswith "Permalink to this definition")

`lower`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.string.StringMethods.lower "Permalink to this definition")

`slice`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.string.StringMethods.slice "Permalink to this definition")

`startswith`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.string.StringMethods.startswith "Permalink to this definition")

`upper`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.string.StringMethods.upper "Permalink to this definition")

*class* `tensortrade.feed.api.string.``StringMixin`[[source]](_modules/tensortrade/feed/api/string.html#StringMixin)[¶](#tensortrade.feed.api.string.StringMixin "Permalink to this definition")

Bases: [`tensortrade.feed.core.mixins.DataTypeMixin`](index.html#tensortrade.feed.core.mixins.DataTypeMixin "tensortrade.feed.core.mixins.DataTypeMixin")

`capitalize`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.string.StringMixin.capitalize "Permalink to this definition")

`cat`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.string.StringMixin.cat "Permalink to this definition")

`endswith`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.string.StringMixin.endswith "Permalink to this definition")

`lower`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.string.StringMixin.lower "Permalink to this definition")

`slice`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.string.StringMixin.slice "Permalink to this definition")

`startswith`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.string.StringMixin.startswith "Permalink to this definition")

`upper`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.api.string.StringMixin.upper "Permalink to this definition")

########## Submodules[¶](#submodules "Permalink to this headline")

########### tensortrade.feed.api.string.operations module[¶](#module-tensortrade.feed.api.string.operations "Permalink to this headline")

operations.py contain functions for streaming string operations.

`tensortrade.feed.api.string.operations.``capitalize`(*s: tensortrade.feed.core.base.Stream[str][str]*) → tensortrade.feed.core.base.Stream[str][str][[source]](_modules/tensortrade/feed/api/string/operations.html#capitalize)[¶](#tensortrade.feed.api.string.operations.capitalize "Permalink to this definition")

Computes the capitalization of a stream.

| Parameters: | **s** (Stream[str]) – A string stream. |

| Returns: | Stream[str] – A capitalized string stream. |

`tensortrade.feed.api.string.operations.``cat`(*s: tensortrade.feed.core.base.Stream[str][str], word: str*) → tensortrade.feed.core.base.Stream[str][str][[source]](_modules/tensortrade/feed/api/string/operations.html#cat)[¶](#tensortrade.feed.api.string.operations.cat "Permalink to this definition")

Computes the concatenation of a stream with a word.

| Parameters: | * **s** (Stream[str]) – A string stream.

* **word** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – A word to concatenate with the s.

 |

| Returns: | Stream[str] – A concatenated string stream. |

`tensortrade.feed.api.string.operations.``endswith`(*s: tensortrade.feed.core.base.Stream[str][str], word: str*) → tensortrade.feed.core.base.Stream[bool][bool][[source]](_modules/tensortrade/feed/api/string/operations.html#endswith)[¶](#tensortrade.feed.api.string.operations.endswith "Permalink to this definition")

Computes the boolean stream of a string ending with a specific value.

| Parameters: | * **s** (Stream[str]) – A string stream.

* **word** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – A word that a string value can end with.

 |

| Returns: | Stream[bool] – A boolean stream. |

`tensortrade.feed.api.string.operations.``lower`(*s: tensortrade.feed.core.base.Stream[str][str]*) → tensortrade.feed.core.base.Stream[str][str][[source]](_modules/tensortrade/feed/api/string/operations.html#lower)[¶](#tensortrade.feed.api.string.operations.lower "Permalink to this definition")

Computes the lowercase of a string stream.

| Parameters: | **s** (Stream[str]) – A string stream. |

| Returns: | Stream[str] – A lowercase string stream. |

`tensortrade.feed.api.string.operations.``slice`(*s: tensortrade.feed.core.base.Stream[str][str], start: int, end: int*) → tensortrade.feed.core.base.Stream[str][str][[source]](_modules/tensortrade/feed/api/string/operations.html#slice)[¶](#tensortrade.feed.api.string.operations.slice "Permalink to this definition")

Computes the substring of a string stream.

| Parameters: | **s** (Stream[str]) – A string stream. |

| Returns: | Stream[str] – A substring stream. |

`tensortrade.feed.api.string.operations.``startswith`(*s: tensortrade.feed.core.base.Stream[str][str], word: str*) → tensortrade.feed.core.base.Stream[bool][bool][[source]](_modules/tensortrade/feed/api/string/operations.html#startswith)[¶](#tensortrade.feed.api.string.operations.startswith "Permalink to this definition")

Computes the boolean stream of a string starting with a specific value.

| Parameters: | * **s** (Stream[str]) – A string stream.

* **word** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – A word that a string value can start with.

 |

| Returns: | Stream[bool] – A boolean stream. |

`tensortrade.feed.api.string.operations.``upper`(*s: tensortrade.feed.core.base.Stream[str][str]*) → tensortrade.feed.core.base.Stream[str][str][[source]](_modules/tensortrade/feed/api/string/operations.html#upper)[¶](#tensortrade.feed.api.string.operations.upper "Permalink to this definition")

Computes the uppercase of a string stream.

| Parameters: | **s** (Stream[str]) – A string stream. |

| Returns: | Stream[str] – A uppercase string stream. |

####### tensortrade.feed.core package[¶](#module-tensortrade.feed.core "Permalink to this headline")

######## Submodules[¶](#submodules "Permalink to this headline")

######### tensortrade.feed.core.accessors module[¶](#module-tensortrade.feed.core.accessors "Permalink to this headline")

*class* `tensortrade.feed.core.accessors.``CachedAccessor`(*name: str*, *accessor*)[[source]](_modules/tensortrade/feed/core/accessors.html#CachedAccessor)[¶](#tensortrade.feed.core.accessors.CachedAccessor "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

Custom property-like object.

A descriptor for caching accessors.

| Parameters: | * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – Namespace that will be accessed under, e.g. `df.foo`.

* **accessor** (*cls*) – Class with the extension methods.

 |

References

| [1] | <https://github.com/pandas-dev/pandas/blob/v1.1.0/pandas/core/accessor.py#L285-L289> |

######### tensortrade.feed.core.base module[¶](#module-tensortrade.feed.core.base "Permalink to this headline")

*class* `tensortrade.feed.core.base.``Constant`(*value*, *dtype: str = None*)[[source]](_modules/tensortrade/feed/core/base.html#Constant)[¶](#tensortrade.feed.core.base.Constant "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

A stream that generates a constant value.

`forward`()[[source]](_modules/tensortrade/feed/core/base.html#Constant.forward)[¶](#tensortrade.feed.core.base.Constant.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`generic_name` *= 'constant'*[¶](#tensortrade.feed.core.base.Constant.generic_name "Permalink to this definition")

`has_next`()[[source]](_modules/tensortrade/feed/core/base.html#Constant.has_next)[¶](#tensortrade.feed.core.base.Constant.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

*class* `tensortrade.feed.core.base.``Group`[[source]](_modules/tensortrade/feed/core/base.html#Group)[¶](#tensortrade.feed.core.base.Group "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

A stream that groups together other streams into a dictionary.

`forward`() → Dict[T][[source]](_modules/tensortrade/feed/core/base.html#Group.forward)[¶](#tensortrade.feed.core.base.Group.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`has_next`() → bool[[source]](_modules/tensortrade/feed/core/base.html#Group.has_next)[¶](#tensortrade.feed.core.base.Group.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

*class* `tensortrade.feed.core.base.``IterableStream`(*source: Iterable[T], dtype: str = None*)[[source]](_modules/tensortrade/feed/core/base.html#IterableStream)[¶](#tensortrade.feed.core.base.IterableStream "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

A private class used the Stream class for creating data sources.

| Parameters: | * **source** (Iterable[T]) – The iterable to be used for providing the data.

* **dtype** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *optional*) – The data type of the source.

 |

`forward`() → T[[source]](_modules/tensortrade/feed/core/base.html#IterableStream.forward)[¶](#tensortrade.feed.core.base.IterableStream.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`generic_name` *= 'stream'*[¶](#tensortrade.feed.core.base.IterableStream.generic_name "Permalink to this definition")

`has_next`()[[source]](_modules/tensortrade/feed/core/base.html#IterableStream.has_next)[¶](#tensortrade.feed.core.base.IterableStream.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

`reset`()[[source]](_modules/tensortrade/feed/core/base.html#IterableStream.reset)[¶](#tensortrade.feed.core.base.IterableStream.reset "Permalink to this definition")

Resets all inputs to and listeners of the stream and sets stream value to None.

*class* `tensortrade.feed.core.base.``NameSpace`(*name: str*)[[source]](_modules/tensortrade/feed/core/base.html#NameSpace)[¶](#tensortrade.feed.core.base.NameSpace "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Named`](#tensortrade.feed.core.base.Named "tensortrade.feed.core.base.Named")

A class providing a context in which to create names.

This becomes useful in cases where Named object would like to use the

same name in a different context. In order to resolve naming conflicts in

a DataFeed, this class provides a way to solve it.

| Parameters: | **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The name for the NameSpace. |

*class* `tensortrade.feed.core.base.``Named`(*name: str = None*)[[source]](_modules/tensortrade/feed/core/base.html#Named)[¶](#tensortrade.feed.core.base.Named "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

A class for controlling the naming of objects.

The purpose of this class is to control the naming of objects with respect

to the NameSpace to which they belong to. This prevents conflicts that

arise in the naming of similar objects under different contexts.

| Parameters: | **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *optional*) – The name of the object. |

`name`[¶](#tensortrade.feed.core.base.Named.name "Permalink to this definition")

The name of the object.

| Type: | [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)"), optional |

`generic_name` *= 'generic'*[¶](#tensortrade.feed.core.base.Named.generic_name "Permalink to this definition")

`names` *= {}*[¶](#tensortrade.feed.core.base.Named.names "Permalink to this definition")

`namespaces` *= []*[¶](#tensortrade.feed.core.base.Named.namespaces "Permalink to this definition")

`rename`(*name: str*, *sep: str = ':/'*) → tensortrade.feed.core.base.Named[[source]](_modules/tensortrade/feed/core/base.html#Named.rename)[¶](#tensortrade.feed.core.base.Named.rename "Permalink to this definition")

Renames the instance with respect to the current NameSpace.

| Parameters: | * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The new name to give to the instance.

* **sep** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The separator to put between the name of the NameSpace and the

new name of the instance (e.g. ns:/example).

 |

| Returns: | Named – The instance that was renamed. |

*class* `tensortrade.feed.core.base.``Placeholder`(*dtype: str = None*)[[source]](_modules/tensortrade/feed/core/base.html#Placeholder)[¶](#tensortrade.feed.core.base.Placeholder "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

A stream that acts as a placeholder for data to be provided at later date.

`forward`() → T[[source]](_modules/tensortrade/feed/core/base.html#Placeholder.forward)[¶](#tensortrade.feed.core.base.Placeholder.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`generic_name` *= 'placeholder'*[¶](#tensortrade.feed.core.base.Placeholder.generic_name "Permalink to this definition")

`has_next`() → bool[[source]](_modules/tensortrade/feed/core/base.html#Placeholder.has_next)[¶](#tensortrade.feed.core.base.Placeholder.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

`push`(*value: T*) → None[[source]](_modules/tensortrade/feed/core/base.html#Placeholder.push)[¶](#tensortrade.feed.core.base.Placeholder.push "Permalink to this definition")

`reset`() → None[[source]](_modules/tensortrade/feed/core/base.html#Placeholder.reset)[¶](#tensortrade.feed.core.base.Placeholder.reset "Permalink to this definition")

Resets all inputs to and listeners of the stream and sets stream value to None.

*class* `tensortrade.feed.core.base.``Sensor`(*obj*, *func*, *dtype=None*)[[source]](_modules/tensortrade/feed/core/base.html#Sensor)[¶](#tensortrade.feed.core.base.Sensor "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

A stream that watches and generates from a particular object.

`forward`() → T[[source]](_modules/tensortrade/feed/core/base.html#Sensor.forward)[¶](#tensortrade.feed.core.base.Sensor.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`generic_name` *= 'sensor'*[¶](#tensortrade.feed.core.base.Sensor.generic_name "Permalink to this definition")

`has_next`()[[source]](_modules/tensortrade/feed/core/base.html#Sensor.has_next)[¶](#tensortrade.feed.core.base.Sensor.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

*class* `tensortrade.feed.core.base.``Stream`(*name: str = None*, *dtype: str = None*)[[source]](_modules/tensortrade/feed/core/base.html#Stream)[¶](#tensortrade.feed.core.base.Stream "Permalink to this definition")

Bases: [`typing.Generic`](https://docs.python.org/3/library/typing.html#typing.Generic "(in Python v3.9)"), [`tensortrade.feed.core.base.Named`](#tensortrade.feed.core.base.Named "tensortrade.feed.core.base.Named"), [`tensortrade.core.base.Observable`](index.html#tensortrade.core.base.Observable "tensortrade.core.base.Observable")

A class responsible for creating the inputs necessary to work in a

DataFeed.

| Parameters: | * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *optional*) – The name fo the stream.

* **dtype** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *optional*) – The data type of the stream.

 |

`source`(*iterable*, *dtype=None*)[[source]](_modules/tensortrade/feed/core/base.html#Stream.source)[¶](#tensortrade.feed.core.base.Stream.source "Permalink to this definition")

Creates a stream from an iterable.

`group`(*streams*)[[source]](_modules/tensortrade/feed/core/base.html#Stream.group)[¶](#tensortrade.feed.core.base.Stream.group "Permalink to this definition")

Creates a group of streams.

`sensor`(*obj*, *func*, *dtype=None*)[[source]](_modules/tensortrade/feed/core/base.html#Stream.sensor)[¶](#tensortrade.feed.core.base.Stream.sensor "Permalink to this definition")

Creates a stream from observing a value from an object.

`select`(*streams*, *func*)[[source]](_modules/tensortrade/feed/core/base.html#Stream.select)[¶](#tensortrade.feed.core.base.Stream.select "Permalink to this definition")

Selects a stream satisfying particular criteria from a list of

streams.

`constant`(*value*, *dtype*)[[source]](_modules/tensortrade/feed/core/base.html#Stream.constant)[¶](#tensortrade.feed.core.base.Stream.constant "Permalink to this definition")

Creates a stream to generate a constant value.

`asdtype`(*dtype*)[¶](#tensortrade.feed.core.base.Stream.asdtype "Permalink to this definition")

Converts the data type to dtype.

`__call__`(*\*inputs*) → tensortrade.feed.core.base.Stream[~T][T][[source]](_modules/tensortrade/feed/core/base.html#Stream.__call__)[¶](#tensortrade.feed.core.base.Stream.__call__ "Permalink to this definition")

Connects the inputs to this stream.

| Parameters: | **\*inputs** (*positional arguments*) – The positional arguments, each a stream to be connected as an input

to this stream. |

| Returns: | Stream[T] – The current stream inputs are being connected to. |

`accumulate`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.core.base.Stream.accumulate "Permalink to this definition")

`apply`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.core.base.Stream.apply "Permalink to this definition")

`astype`(*dtype: str*) → tensortrade.feed.core.base.Stream[~T][T][[source]](_modules/tensortrade/feed/core/base.html#Stream.astype)[¶](#tensortrade.feed.core.base.Stream.astype "Permalink to this definition")

Converts the data type to dtype.

| Parameters: | **dtype** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The data type to be converted to. |

| Returns: | Stream[T] – The same stream with the new underlying data type dtype. |

`bool`[¶](#tensortrade.feed.core.base.Stream.bool "Permalink to this definition")

alias of [`tensortrade.feed.api.boolean.BooleanMethods`](index.html#tensortrade.feed.api.boolean.BooleanMethods "tensortrade.feed.api.boolean.BooleanMethods")

*static* `constant`(*value: T*, *dtype: str = None*) → tensortrade.feed.core.base.Stream[~T][T][[source]](_modules/tensortrade/feed/core/base.html#Stream.constant)

Creates a stream to generate a constant value.

| Parameters: | * **value** (T) – The constant value to be streamed.

* **dtype** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *optional*) – The data type of the value.

 |

| Returns: | Stream[T] – A stream of the constant value. |

`copy`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.core.base.Stream.copy "Permalink to this definition")

*static* `extend_instance`(*instance: tensortrade.feed.core.base.Stream[~T][T], mixin: tensortrade.feed.core.mixins.DataTypeMixin*) → tensortrade.feed.core.base.Stream[~T][T][[source]](_modules/tensortrade/feed/core/base.html#Stream.extend_instance)[¶](#tensortrade.feed.core.base.Stream.extend_instance "Permalink to this definition")

Apply mix-ins to a class instance after creation.

| Parameters: | * **instance** (Stream[T]) – An instantiation of Stream to be injected with mixin methods.

* **mixin** (DataTypeMixin) – The mixin holding the methods to be injected into the instance.

 |

| Returns: | Stream[T] – The instance with the injected methods provided by the mixin. |

`float`[¶](#tensortrade.feed.core.base.Stream.float "Permalink to this definition")

alias of [`tensortrade.feed.api.float.FloatMethods`](index.html#tensortrade.feed.api.float.FloatMethods "tensortrade.feed.api.float.FloatMethods")

`forward`() → T[[source]](_modules/tensortrade/feed/core/base.html#Stream.forward)[¶](#tensortrade.feed.core.base.Stream.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`freeze`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.core.base.Stream.freeze "Permalink to this definition")

`gather`() → List[Tuple[tensortrade.feed.core.base.Stream, tensortrade.feed.core.base.Stream]][[source]](_modules/tensortrade/feed/core/base.html#Stream.gather)[¶](#tensortrade.feed.core.base.Stream.gather "Permalink to this definition")

Gathers all the edges of the DAG connected in ancestry with this

stream.

| Returns: | List[Tuple[Stream, Stream]] – The list of edges connected through ancestry to this stream. |

`generic_name` *= 'stream'*[¶](#tensortrade.feed.core.base.Stream.generic_name "Permalink to this definition")

*static* `group`(*streams: List[tensortrade.feed.core.base.Stream[~T][T]]*) → tensortrade.feed.core.base.Stream[dict][dict][[source]](_modules/tensortrade/feed/core/base.html#Stream.group)

Creates a group of streams.

| Parameters: | **streams** (List[Stream[T]]) – Streams to be grouped together. |

| Returns: | Stream[dict] – A stream of dictionaries with each stream as a key/value in the

dictionary being generated. |

`has_next`() → bool[[source]](_modules/tensortrade/feed/core/base.html#Stream.has_next)[¶](#tensortrade.feed.core.base.Stream.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

`lag`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.core.base.Stream.lag "Permalink to this definition")

*static* `placeholder`(*dtype: str = None*) → tensortrade.feed.core.base.Stream[~T][T][[source]](_modules/tensortrade/feed/core/base.html#Stream.placeholder)[¶](#tensortrade.feed.core.base.Stream.placeholder "Permalink to this definition")

Creates a placholder stream for data to provided to at a later date.

| Parameters: | **dtype** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The data type that will be provided. |

| Returns: | Stream[T] – A stream representing a placeholder. |

`reduce`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.core.base.Stream.reduce "Permalink to this definition")

*classmethod* `register_accessor`(*name: str*)[[source]](_modules/tensortrade/feed/core/base.html#Stream.register_accessor)[¶](#tensortrade.feed.core.base.Stream.register_accessor "Permalink to this definition")

A class decorator that registers an accessor providing useful

methods for a particular data type..

Sets the data type accessor to be an attribute of this class.

| Parameters: | **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The name of the data type. |

*classmethod* `register_generic_method`(*names: List[str]*)[[source]](_modules/tensortrade/feed/core/base.html#Stream.register_generic_method)[¶](#tensortrade.feed.core.base.Stream.register_generic_method "Permalink to this definition")

A function decorator that registers the decorated function with the

names provided as a method to the Stream class.

These methods can be used for any instance of Stream.

| Parameters: | **names** (List[str]) – The list of names to be used as aliases for the same method. |

*classmethod* `register_mixin`(*dtype: str*)[[source]](_modules/tensortrade/feed/core/base.html#Stream.register_mixin)[¶](#tensortrade.feed.core.base.Stream.register_mixin "Permalink to this definition")

A class decorator the registers a data type mixin providing useful

methods directly to the instance of the class.

| Parameters: | **dtype** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The name of the data type the mixin is being registered for. |

`reset`() → None[[source]](_modules/tensortrade/feed/core/base.html#Stream.reset)[¶](#tensortrade.feed.core.base.Stream.reset "Permalink to this definition")

Resets all inputs to and listeners of the stream and sets stream value to None.

`run`() → None[[source]](_modules/tensortrade/feed/core/base.html#Stream.run)[¶](#tensortrade.feed.core.base.Stream.run "Permalink to this definition")

Runs the underlying streams once and iterates forward.

*static* `select`(*streams: List[tensortrade.feed.core.base.Stream[~T][T]], func: Callable[[tensortrade.feed.core.base.Stream[~T][T]], bool]*) → tensortrade.feed.core.base.Stream[~T][T][[source]](_modules/tensortrade/feed/core/base.html#Stream.select)

Selects a stream satisfying particular criteria from a list of

streams.

| Parameters: | * **streams** (List[Stream[T]]) – A list of streams to select from.

* **func** (Callable[[Stream[T]], bool]) – The criteria to be used for finding the particular stream.

 |

| Returns: | Stream[T] – The particular stream being selected. |

| Raises: | [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception "(in Python v3.9)") – Raised if no stream is found to satisfy the given criteria. |

*static* `sensor`(*obj: Any, func: Callable[[Any], T], dtype: str = None*) → tensortrade.feed.core.base.Stream[~T][T][[source]](_modules/tensortrade/feed/core/base.html#Stream.sensor)

Creates a stream from observing a value from an object.

| Parameters: | * **obj** (Any) – An object to observe values from.

* **func** (Callable[[Any], T]) – A function to extract the data to be observed from the object being

watched.

* **dtype** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *optional*) – The data type of the stream.

 |

| Returns: | Stream[T] – The stream of values being observed from the object. |

*static* `source`(*iterable: Iterable[T], dtype: str = None*) → tensortrade.feed.core.base.Stream[~T][T][[source]](_modules/tensortrade/feed/core/base.html#Stream.source)

Creates a stream from an iterable.

| Parameters: | * **iterable** (Iterable[T]) – The iterable to create the stream from.

* **dtype** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *optional*) – The data type of the stream.

 |

| Returns: | Stream[T] – The stream with the data type dtype created from iterable. |

`str`[¶](#tensortrade.feed.core.base.Stream.str "Permalink to this definition")

alias of [`tensortrade.feed.api.string.StringMethods`](index.html#tensortrade.feed.api.string.StringMethods "tensortrade.feed.api.string.StringMethods")

*static* `toposort`(*edges: List[Tuple[tensortrade.feed.core.base.Stream, tensortrade.feed.core.base.Stream]]*) → List[tensortrade.feed.core.base.Stream][[source]](_modules/tensortrade/feed/core/base.html#Stream.toposort)[¶](#tensortrade.feed.core.base.Stream.toposort "Permalink to this definition")

Sorts the order in which streams should be run.

| Parameters: | **edges** (List[Tuple[Stream, Stream]]) – The connections that have been found in the DAG. |

| Returns: | List[Stream] – The list of streams sorted with respect to the order in which they

should be run. |

`warmup`(*\*args*, *\*\*kwargs*)[¶](#tensortrade.feed.core.base.Stream.warmup "Permalink to this definition")

######### tensortrade.feed.core.feed module[¶](#module-tensortrade.feed.core.feed "Permalink to this headline")

*class* `tensortrade.feed.core.feed.``DataFeed`(*streams: List[tensortrade.feed.core.base.Stream]*)[[source]](_modules/tensortrade/feed/core/feed.html#DataFeed)[¶](#tensortrade.feed.core.feed.DataFeed "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](index.html#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

A stream the compiles together streams to be run in an organized manner.

| Parameters: | **streams** (List[Stream]) – A list of streams to be used in the data feed. |

`compile`() → None[[source]](_modules/tensortrade/feed/core/feed.html#DataFeed.compile)[¶](#tensortrade.feed.core.feed.DataFeed.compile "Permalink to this definition")

Compiles all the given stream together.

Organizes the order in which streams should be run to get valid output.

`forward`() → dict[[source]](_modules/tensortrade/feed/core/feed.html#DataFeed.forward)[¶](#tensortrade.feed.core.feed.DataFeed.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`has_next`() → bool[[source]](_modules/tensortrade/feed/core/feed.html#DataFeed.has_next)[¶](#tensortrade.feed.core.feed.DataFeed.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

`next`() → dict[[source]](_modules/tensortrade/feed/core/feed.html#DataFeed.next)[¶](#tensortrade.feed.core.feed.DataFeed.next "Permalink to this definition")

`reset`() → None[[source]](_modules/tensortrade/feed/core/feed.html#DataFeed.reset)[¶](#tensortrade.feed.core.feed.DataFeed.reset "Permalink to this definition")

Resets all inputs to and listeners of the stream and sets stream value to None.

`run`() → None[[source]](_modules/tensortrade/feed/core/feed.html#DataFeed.run)[¶](#tensortrade.feed.core.feed.DataFeed.run "Permalink to this definition")

Runs all the streams in processing order.

*class* `tensortrade.feed.core.feed.``PushFeed`(*streams: List[tensortrade.feed.core.base.Stream]*)[[source]](_modules/tensortrade/feed/core/feed.html#PushFeed)[¶](#tensortrade.feed.core.feed.PushFeed "Permalink to this definition")

Bases: [`tensortrade.feed.core.feed.DataFeed`](#tensortrade.feed.core.feed.DataFeed "tensortrade.feed.core.feed.DataFeed")

A data feed for working with live data in an online manner.

All sources of data to be used with this feed must be a Placeholder. This

ensures that the user can wait until all of their data has been loaded for the

next time step.

| Parameters: | **streams** (List[Stream]) – A list of streams to be used in the data feed. |

`is_loaded`[¶](#tensortrade.feed.core.feed.PushFeed.is_loaded "Permalink to this definition")

`next`() → dict[[source]](_modules/tensortrade/feed/core/feed.html#PushFeed.next)[¶](#tensortrade.feed.core.feed.PushFeed.next "Permalink to this definition")

`push`(*data: dict*) → dict[[source]](_modules/tensortrade/feed/core/feed.html#PushFeed.push)[¶](#tensortrade.feed.core.feed.PushFeed.push "Permalink to this definition")

Generates the values from the data feed based on the values being

provided in data.

| Parameters: | **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)")) – The data to be pushed to each of the placholders in the feed. |

| Returns: | *dict* – The next data point generated from the feed based on data. |

######### tensortrade.feed.core.methods module[¶](#module-tensortrade.feed.core.methods "Permalink to this headline")

*class* `tensortrade.feed.core.methods.``Methods`(*stream: Stream*)[[source]](_modules/tensortrade/feed/core/methods.html#Methods)[¶](#tensortrade.feed.core.methods.Methods "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

A class used to hold the accessor methods for a particular data type.

| Parameters: | **stream** (*"Stream"*) – The stream to injected with the method accessor. |

*classmethod* `register_method`(*func: Callable, names: List[str]*)[[source]](_modules/tensortrade/feed/core/methods.html#Methods.register_method)[¶](#tensortrade.feed.core.methods.Methods.register_method "Permalink to this definition")

Injects an accessor into a specific stream instance.

| Parameters: | * **func** (Callable) – The function to be injected as an accessor method.

* **names** (List[str]) – The names to be given to the function.

 |

######### tensortrade.feed.core.mixins module[¶](#module-tensortrade.feed.core.mixins "Permalink to this headline")

*class* `tensortrade.feed.core.mixins.``DataTypeMixin`[[source]](_modules/tensortrade/feed/core/mixins.html#DataTypeMixin)[¶](#tensortrade.feed.core.mixins.DataTypeMixin "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

*classmethod* `register_method`(*func: Callable, names: List[str]*)[[source]](_modules/tensortrade/feed/core/mixins.html#DataTypeMixin.register_method)[¶](#tensortrade.feed.core.mixins.DataTypeMixin.register_method "Permalink to this definition")

Injects methods into a specific stream instance.

| Parameters: | * **func** (Callable) – The function to be injected as a method.

* **names** (List[str]) – The names to be given to the function.

 |

######### tensortrade.feed.core.operators module[¶](#module-tensortrade.feed.core.operators "Permalink to this headline")

*class* `tensortrade.feed.core.operators.``Accumulator`(*func: Callable[[T, T], T], dtype: str = None*)[[source]](_modules/tensortrade/feed/core/operators.html#Accumulator)[¶](#tensortrade.feed.core.operators.Accumulator "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](index.html#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

An operator stream that accumulates values of a given stream.

| Parameters: | * **func** (*Callable**[**[**T**,**T**]**,* *T**]*) – An accumulator function.

* **dtype** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The data type of accumulated value.

 |

`forward`()[[source]](_modules/tensortrade/feed/core/operators.html#Accumulator.forward)[¶](#tensortrade.feed.core.operators.Accumulator.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`has_next`() → bool[[source]](_modules/tensortrade/feed/core/operators.html#Accumulator.has_next)[¶](#tensortrade.feed.core.operators.Accumulator.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

`reset`() → None[[source]](_modules/tensortrade/feed/core/operators.html#Accumulator.reset)[¶](#tensortrade.feed.core.operators.Accumulator.reset "Permalink to this definition")

Resets all inputs to and listeners of the stream and sets stream value to None.

*class* `tensortrade.feed.core.operators.``Apply`(*func: Callable[[T], K], dtype: str = None*)[[source]](_modules/tensortrade/feed/core/operators.html#Apply)[¶](#tensortrade.feed.core.operators.Apply "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](index.html#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

An operator stream that applies a specific function to the values of

a given stream.

| Parameters: | * **func** (Callable[[T], …]) – A function to be applied to the values of a stream.

* **dtype** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *optional*) – The data type of the values after function is applied.

 |

`forward`() → K[[source]](_modules/tensortrade/feed/core/operators.html#Apply.forward)[¶](#tensortrade.feed.core.operators.Apply.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`has_next`() → bool[[source]](_modules/tensortrade/feed/core/operators.html#Apply.has_next)[¶](#tensortrade.feed.core.operators.Apply.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

*class* `tensortrade.feed.core.operators.``BinOp`(*op: Callable[[T, T], T], dtype: str = None*)[[source]](_modules/tensortrade/feed/core/operators.html#BinOp)[¶](#tensortrade.feed.core.operators.BinOp "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](index.html#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

A stream operator that combines the values of two given streams into

one value of the same type.

| Parameters: | * **op** (Callable[[T, T], T]) – The binary operation to be applied.

* **dtype** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *optional*) – The data type of the stream.

 |

`forward`() → T[[source]](_modules/tensortrade/feed/core/operators.html#BinOp.forward)[¶](#tensortrade.feed.core.operators.BinOp.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`generic_name` *= 'bin\_op'*[¶](#tensortrade.feed.core.operators.BinOp.generic_name "Permalink to this definition")

`has_next`() → bool[[source]](_modules/tensortrade/feed/core/operators.html#BinOp.has_next)[¶](#tensortrade.feed.core.operators.BinOp.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

*class* `tensortrade.feed.core.operators.``Copy`[[source]](_modules/tensortrade/feed/core/operators.html#Copy)[¶](#tensortrade.feed.core.operators.Copy "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](index.html#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

A stream operator that copies the values of a given stream.

`forward`() → T[[source]](_modules/tensortrade/feed/core/operators.html#Copy.forward)[¶](#tensortrade.feed.core.operators.Copy.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`generic_name` *= 'copy'*[¶](#tensortrade.feed.core.operators.Copy.generic_name "Permalink to this definition")

`has_next`() → bool[[source]](_modules/tensortrade/feed/core/operators.html#Copy.has_next)[¶](#tensortrade.feed.core.operators.Copy.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

*class* `tensortrade.feed.core.operators.``Freeze`[[source]](_modules/tensortrade/feed/core/operators.html#Freeze)[¶](#tensortrade.feed.core.operators.Freeze "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](index.html#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

A stream operator that freezes the value of a given stream and generates

that value.

`forward`() → T[[source]](_modules/tensortrade/feed/core/operators.html#Freeze.forward)[¶](#tensortrade.feed.core.operators.Freeze.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`generic_name` *= 'freeze'*[¶](#tensortrade.feed.core.operators.Freeze.generic_name "Permalink to this definition")

`has_next`() → bool[[source]](_modules/tensortrade/feed/core/operators.html#Freeze.has_next)[¶](#tensortrade.feed.core.operators.Freeze.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

`reset`() → None[[source]](_modules/tensortrade/feed/core/operators.html#Freeze.reset)[¶](#tensortrade.feed.core.operators.Freeze.reset "Permalink to this definition")

Resets all inputs to and listeners of the stream and sets stream value to None.

*class* `tensortrade.feed.core.operators.``Lag`(*lag: int = 1*, *dtype: str = None*)[[source]](_modules/tensortrade/feed/core/operators.html#Lag)[¶](#tensortrade.feed.core.operators.Lag "Permalink to this definition")

Bases: [`tensortrade.feed.core.base.Stream`](index.html#tensortrade.feed.core.base.Stream "tensortrade.feed.core.base.Stream")

An operator stream that returns the lagged value of a given stream.

| Parameters: | * **lag** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The number of steps to lag behind by

* **dtype** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *optional*) – The data type of the stream

 |

`forward`() → T[[source]](_modules/tensortrade/feed/core/operators.html#Lag.forward)[¶](#tensortrade.feed.core.operators.Lag.forward "Permalink to this definition")

Generates the next value from the underlying data streams.

| Returns: | T – The next value in the stream. |

`generic_name` *= 'lag'*[¶](#tensortrade.feed.core.operators.Lag.generic_name "Permalink to this definition")

`has_next`() → bool[[source]](_modules/tensortrade/feed/core/operators.html#Lag.has_next)[¶](#tensortrade.feed.core.operators.Lag.has_next "Permalink to this definition")

Checks if there is another value.

| Returns: | *bool* – If there is another value or not. |

`reset`() → None[[source]](_modules/tensortrade/feed/core/operators.html#Lag.reset)[¶](#tensortrade.feed.core.operators.Lag.reset "Permalink to this definition")

Resets all inputs to and listeners of the stream and sets stream value to None.

##### tensortrade.oms package[¶](#module-tensortrade.oms "Permalink to this headline")

###### Subpackages[¶](#subpackages "Permalink to this headline")

####### tensortrade.oms.exchanges package[¶](#module-tensortrade.oms.exchanges "Permalink to this headline")

######## Submodules[¶](#submodules "Permalink to this headline")

######### tensortrade.oms.exchanges.exchange module[¶](#module-tensortrade.oms.exchanges.exchange "Permalink to this headline")

*class* `tensortrade.oms.exchanges.exchange.``Exchange`(*name: str*, *service: Callable*, *options: tensortrade.oms.exchanges.exchange.ExchangeOptions = None*)[[source]](_modules/tensortrade/oms/exchanges/exchange.html#Exchange)[¶](#tensortrade.oms.exchanges.exchange.Exchange "Permalink to this definition")

Bases: [`tensortrade.core.component.Component`](index.html#tensortrade.core.component.Component "tensortrade.core.component.Component"), [`tensortrade.core.base.TimedIdentifiable`](index.html#tensortrade.core.base.TimedIdentifiable "tensortrade.core.base.TimedIdentifiable")

An abstract exchange for use within a trading environment.

| Parameters: | * **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The name of the exchange.

* **service** (Union[Callable, str]) – The service to be used for filling orders.

* **options** (ExchangeOptions) – The options used to specify the setting of the exchange.

 |

`__call__`(*\*streams*) → tensortrade.oms.exchanges.exchange.Exchange[[source]](_modules/tensortrade/oms/exchanges/exchange.html#Exchange.__call__)[¶](#tensortrade.oms.exchanges.exchange.Exchange.__call__ "Permalink to this definition")

Sets up the price streams used to generate the prices.

| Parameters: | **\*streams** – The positional arguments each being a price stream. |

| Returns: | Exchange – The exchange the price streams were passed in for. |

`execute_order`(*order: Order*, *portfolio: Portfolio*) → None[[source]](_modules/tensortrade/oms/exchanges/exchange.html#Exchange.execute_order)[¶](#tensortrade.oms.exchanges.exchange.Exchange.execute_order "Permalink to this definition")

Execute an order on the exchange.

| Parameters: | * **order** (Order) – The order to execute.

* **portfolio** (Portfolio) – The portfolio to use.

 |

`is_pair_tradable`(*trading\_pair: tensortrade.oms.instruments.trading\_pair.TradingPair*) → bool[[source]](_modules/tensortrade/oms/exchanges/exchange.html#Exchange.is_pair_tradable)[¶](#tensortrade.oms.exchanges.exchange.Exchange.is_pair_tradable "Permalink to this definition")

Whether or not the specified trading pair is tradable on this

exchange.

| Parameters: | **trading\_pair** (TradingPair) – The trading pair to test the tradability of. |

| Returns: | *bool* – Whether or not the pair is tradable. |

`quote_price`(*trading\_pair: tensortrade.oms.instruments.trading\_pair.TradingPair*) → decimal.Decimal[[source]](_modules/tensortrade/oms/exchanges/exchange.html#Exchange.quote_price)[¶](#tensortrade.oms.exchanges.exchange.Exchange.quote_price "Permalink to this definition")

The quote price of a trading pair on the exchange, denoted in the

core instrument.

| Parameters: | **trading\_pair** (TradingPair) – The trading pair to get the quote price for. |

| Returns: | Decimal – The quote price of the specified trading pair, denoted in the core instrument. |

`registered_name` *= 'exchanges'*[¶](#tensortrade.oms.exchanges.exchange.Exchange.registered_name "Permalink to this definition")

`streams`() → List[Stream[float]][[source]](_modules/tensortrade/oms/exchanges/exchange.html#Exchange.streams)[¶](#tensortrade.oms.exchanges.exchange.Exchange.streams "Permalink to this definition")

Gets the price streams for the exchange.

| Returns: | List[Stream[float]] – The price streams for the exchange. |

*class* `tensortrade.oms.exchanges.exchange.``ExchangeOptions`(*commission: float = 0.003*, *min\_trade\_size: float = 1e-06*, *max\_trade\_size: float = 1000000.0*, *min\_trade\_price: float = 1e-08*, *max\_trade\_price: float = 100000000.0*, *is\_live: bool = False*)[[source]](_modules/tensortrade/oms/exchanges/exchange.html#ExchangeOptions)[¶](#tensortrade.oms.exchanges.exchange.ExchangeOptions "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

An options class to specify the settings of an exchange.

| Parameters: | * **commission** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default 0.003*) – The percentage of the order size taken by the exchange.

* **min\_trade\_size** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default 1e-6*) – The minimum trade size an order can have.

* **max\_trade\_size** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default 1e6*) – The maximum trade size an order can have.

* **min\_trade\_price** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default 1e-8*) – The minimum price an exchange can have.

* **max\_trade\_price** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default 1e8*) – The maximum price an exchange can have.

* **is\_live** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default False*) – Whether live orders should be submitted to the exchange.

 |

####### tensortrade.oms.instruments package[¶](#module-tensortrade.oms.instruments "Permalink to this headline")

######## Submodules[¶](#submodules "Permalink to this headline")

######### tensortrade.oms.instruments.exchange\_pair module[¶](#module-tensortrade.oms.instruments.exchange_pair "Permalink to this headline")

*class* `tensortrade.oms.instruments.exchange_pair.``ExchangePair`(*exchange: Exchange*, *pair: TradingPair*)[[source]](_modules/tensortrade/oms/instruments/exchange_pair.html#ExchangePair)[¶](#tensortrade.oms.instruments.exchange_pair.ExchangePair "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

A pair of financial instruments to be traded on a specific exchange.

| Parameters: | * **exchange** (Exchange) – An exchange that contains the pair for trading.

* **pair** (TradingPair) – A trading pair available on the exchange.

 |

`inverse_price`[¶](#tensortrade.oms.instruments.exchange_pair.ExchangePair.inverse_price "Permalink to this definition")

The inverse price of the trading pair. ([`](#id1)Decimal, read-only)

`price`[¶](#tensortrade.oms.instruments.exchange_pair.ExchangePair.price "Permalink to this definition")

The quoted price of the trading pair. (Decimal, read-only)

######### tensortrade.oms.instruments.instrument module[¶](#module-tensortrade.oms.instruments.instrument "Permalink to this headline")

*class* `tensortrade.oms.instruments.instrument.``Instrument`(*symbol: str*, *precision: int*, *name: str = None*)[[source]](_modules/tensortrade/oms/instruments/instrument.html#Instrument)[¶](#tensortrade.oms.instruments.instrument.Instrument "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

A financial instrument for use in trading.

| Parameters: | * **symbol** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The symbol used on an exchange for a particular instrument.

(e.g. AAPL, BTC, TSLA)

* **precision** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The precision the amount of the instrument is denoted with.

(e.g. BTC=8, AAPL=1)

* **name** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *optional*) – The name of the instrument being created.

 |

`__eq__`(*other: Any*) → bool[[source]](_modules/tensortrade/oms/instruments/instrument.html#Instrument.__eq__)[¶](#tensortrade.oms.instruments.instrument.Instrument.__eq__ "Permalink to this definition")

Checks if two instruments are equal.

| Parameters: | **other** (Any) – The instrument being compared. |

| Returns: | *bool* – Whether the instruments are equal. |

`__ne__`(*other: Any*) → bool[[source]](_modules/tensortrade/oms/instruments/instrument.html#Instrument.__ne__)[¶](#tensortrade.oms.instruments.instrument.Instrument.__ne__ "Permalink to this definition")

Checks if two instruments are not equal.

| Parameters: | **other** (Any) – The instrument being compared. |

| Returns: | *bool* – Whether the instruments are not equal. |

`__rmul__`(*other: float*) → tensortrade.oms.instruments.quantity.Quantity[[source]](_modules/tensortrade/oms/instruments/instrument.html#Instrument.__rmul__)[¶](#tensortrade.oms.instruments.instrument.Instrument.__rmul__ "Permalink to this definition")

Enables reverse multiplication.

| Parameters: | **other** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The number used to create a quantity. |

| Returns: | Quantity – The quantity created by the number and the instrument involved with

this operation. |

`__truediv__`(*other: tensortrade.oms.instruments.instrument.Instrument*) → tensortrade.oms.instruments.trading\_pair.TradingPair[[source]](_modules/tensortrade/oms/instruments/instrument.html#Instrument.__truediv__)[¶](#tensortrade.oms.instruments.instrument.Instrument.__truediv__ "Permalink to this definition")

Creates a trading pair through division.

| Parameters: | **other** (Instrument) – The instrument that will be the quote of the pair. |

| Returns: | TradingPair – The trading pair created from the two instruments. |

| Raises: | * `InvalidTradingPair` – Raised if other is the same instrument as self.

* [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception "(in Python v3.9)") – Raised if other is not an instrument.

 |

######### tensortrade.oms.instruments.quantity module[¶](#module-tensortrade.oms.instruments.quantity "Permalink to this headline")

*class* `tensortrade.oms.instruments.quantity.``Quantity`(*instrument: Instrument, size: Union[decimal.Decimal, numbers.Number], path\_id: str = None*)[[source]](_modules/tensortrade/oms/instruments/quantity.html#Quantity)[¶](#tensortrade.oms.instruments.quantity.Quantity "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

A size of a financial instrument for use in trading.

| Parameters: | * **instrument** (Instrument) – The unit of the quantity.

* **size** (Union[float, Decimal]) – The number of units of the instrument.

* **path\_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *optional*) – The path order\_id that this quantity is allocated for and associated

with.

 |

| Raises: | `InvalidNegativeQuantity` – Raised if the size of the quantity being created is negative. |

`as_float`() → float[[source]](_modules/tensortrade/oms/instruments/quantity.html#Quantity.as_float)[¶](#tensortrade.oms.instruments.quantity.Quantity.as_float "Permalink to this definition")

Gets the size as a float.

| Returns: | *float* – The size as a floating point number. |

`contain`(*exchange\_pair: ExchangePair*)[[source]](_modules/tensortrade/oms/instruments/quantity.html#Quantity.contain)[¶](#tensortrade.oms.instruments.quantity.Quantity.contain "Permalink to this definition")

Contains the size of the quantity to be compatible with the settings

of a given exchange.

| Parameters: | **exchange\_pair** (ExchangePair) – The exchange pair containing the exchange the quantity must be

compatible with. |

| Returns: | Quantity – A quantity compatible with the given exchange. |

`convert`(*exchange\_pair: ExchangePair*) → Quantity[[source]](_modules/tensortrade/oms/instruments/quantity.html#Quantity.convert)[¶](#tensortrade.oms.instruments.quantity.Quantity.convert "Permalink to this definition")

Converts the quantity into the value of another instrument based

on its exchange rate from an exchange.

| Parameters: | **exchange\_pair** (ExchangePair) – The exchange pair to use for getting the quoted price to perform

the conversion. |

| Returns: | Quantity – The value of the current quantity in terms of the quote instrument. |

`free`() → tensortrade.oms.instruments.quantity.Quantity[[source]](_modules/tensortrade/oms/instruments/quantity.html#Quantity.free)[¶](#tensortrade.oms.instruments.quantity.Quantity.free "Permalink to this definition")

Gets the free version of this quantity.

| Returns: | Quantity – The free version of the quantity. |

`is_locked`[¶](#tensortrade.oms.instruments.quantity.Quantity.is_locked "Permalink to this definition")

If quantity is locked for an order. (bool, read-only)

`lock_for`(*path\_id: str*) → tensortrade.oms.instruments.quantity.Quantity[[source]](_modules/tensortrade/oms/instruments/quantity.html#Quantity.lock_for)[¶](#tensortrade.oms.instruments.quantity.Quantity.lock_for "Permalink to this definition")

Locks a quantity for an Order identified associated with path\_id.

| Parameters: | **path\_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The identification of the order path. |

| Returns: | Quantity – A locked quantity for an order path. |

`quantize`() → tensortrade.oms.instruments.quantity.Quantity[[source]](_modules/tensortrade/oms/instruments/quantity.html#Quantity.quantize)[¶](#tensortrade.oms.instruments.quantity.Quantity.quantize "Permalink to this definition")

Computes the quantization of current quantity in terms of the instrument’s

precision.

| Returns: | Quantity – The quantized quantity. |

*static* `validate`(*left: Union[tensortrade.oms.instruments.quantity.Quantity, numbers.Number], right: Union[tensortrade.oms.instruments.quantity.Quantity, numbers.Number]*) → Tuple[tensortrade.oms.instruments.quantity.Quantity, tensortrade.oms.instruments.quantity.Quantity][[source]](_modules/tensortrade/oms/instruments/quantity.html#Quantity.validate)[¶](#tensortrade.oms.instruments.quantity.Quantity.validate "Permalink to this definition")

Validates the given left and right arguments of a numeric or boolean

operation.

| Parameters: | * **left** (Union[Quantity, Number]) – The left argument of an operation.

* **right** (Union[Quantity, Number]) – The right argument of an operation.

 |

| Returns: | Tuple[Quantity, Quantity] – The validated quantity arguments to use in a numeric or boolean

operation. |

| Raises: | * `IncompatibleInstrumentOperation` – Raised if the instruments left and right quantities are not equal.

* `QuantityOpPathMismatch` – Raised if

	+ One argument is locked and the other argument is not.

	+ Both arguments are locked quantities with unequal path\_ids.

* `InvalidNonNumericQuantity` – Raised if either argument is a non-numeric object.

* [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception "(in Python v3.9)") – If the operation is not valid.

 |

######### tensortrade.oms.instruments.trading\_pair module[¶](#module-tensortrade.oms.instruments.trading_pair "Permalink to this headline")

*class* `tensortrade.oms.instruments.trading_pair.``TradingPair`(*base: Instrument*, *quote: Instrument*)[[source]](_modules/tensortrade/oms/instruments/trading_pair.html#TradingPair)[¶](#tensortrade.oms.instruments.trading_pair.TradingPair "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

A pair of financial instruments to be traded on an exchange.

| Parameters: | * **base** (Instrument) – The base instrument of the trading pair.

* **quote** (Instrument) – The quote instrument of the trading pair.

 |

| Raises: | `InvalidTradingPair` – Raises if base and quote instrument are equal. |

####### tensortrade.oms.orders package[¶](#module-tensortrade.oms.orders "Permalink to this headline")

######## Submodules[¶](#submodules "Permalink to this headline")

######### tensortrade.oms.orders.broker module[¶](#module-tensortrade.oms.orders.broker "Permalink to this headline")

*class* `tensortrade.oms.orders.broker.``Broker`[[source]](_modules/tensortrade/oms/orders/broker.html#Broker)[¶](#tensortrade.oms.orders.broker.Broker "Permalink to this definition")

Bases: [`tensortrade.oms.orders.order\_listener.OrderListener`](index.html#tensortrade.oms.orders.order_listener.OrderListener "tensortrade.oms.orders.order_listener.OrderListener"), [`tensortrade.core.base.TimeIndexed`](index.html#tensortrade.core.base.TimeIndexed "tensortrade.core.base.TimeIndexed")

A broker for handling the execution of orders on multiple exchanges.

Orders are kept in a virtual order book until they are ready to be executed.

`unexecuted`[¶](#tensortrade.oms.orders.broker.Broker.unexecuted "Permalink to this definition")

The list of orders the broker is waiting to execute, when their

criteria is satisfied.

| Type: | List[Order] |

`executed`[¶](#tensortrade.oms.orders.broker.Broker.executed "Permalink to this definition")

The dictionary of orders the broker has executed since resetting,

organized by order id.

| Type: | Dict[str, Order] |

`trades`[¶](#tensortrade.oms.orders.broker.Broker.trades "Permalink to this definition")

The dictionary of trades the broker has executed since resetting,

organized by order id.

| Type: | Dict[str, Trade] |

`cancel`(*order: tensortrade.oms.orders.order.Order*) → None[[source]](_modules/tensortrade/oms/orders/broker.html#Broker.cancel)[¶](#tensortrade.oms.orders.broker.Broker.cancel "Permalink to this definition")

Cancels an order.

| Parameters: | **order** (Order) – The order to be canceled. |

`on_fill`(*order: Order*, *trade: Trade*) → None[[source]](_modules/tensortrade/oms/orders/broker.html#Broker.on_fill)[¶](#tensortrade.oms.orders.broker.Broker.on_fill "Permalink to this definition")

Updates the broker after an order has been filled.

| Parameters: | * **order** (Order) – The order that is being filled.

* **trade** (Trade) – The trade that is being made to fill the order.

 |

`reset`() → None[[source]](_modules/tensortrade/oms/orders/broker.html#Broker.reset)[¶](#tensortrade.oms.orders.broker.Broker.reset "Permalink to this definition")

Resets the broker.

`submit`(*order: tensortrade.oms.orders.order.Order*) → None[[source]](_modules/tensortrade/oms/orders/broker.html#Broker.submit)[¶](#tensortrade.oms.orders.broker.Broker.submit "Permalink to this definition")

Submits an order to the broker.

Adds order to the queue of orders waiting to be executed.

| Parameters: | **order** (Order) – The order to be submitted. |

`update`() → None[[source]](_modules/tensortrade/oms/orders/broker.html#Broker.update)[¶](#tensortrade.oms.orders.broker.Broker.update "Permalink to this definition")

Updates the brokers order management system.

The broker will look through the unexecuted orders and if an order

is ready to be executed the broker will submit it to the executed

list and execute the order.

Then the broker will find any orders that are active, but expired, and

proceed to cancel them.

######### tensortrade.oms.orders.create module[¶](#module-tensortrade.oms.orders.create "Permalink to this headline")

`tensortrade.oms.orders.create.``hidden_limit_order`(*side: tensortrade.oms.orders.trade.TradeSide*, *exchange\_pair: tensortrade.oms.instruments.exchange\_pair.ExchangePair*, *limit\_price: float*, *size: float*, *portfolio: tensortrade.oms.wallets.portfolio.Portfolio*, *start: int = None*, *end: int = None*)[[source]](_modules/tensortrade/oms/orders/create.html#hidden_limit_order)[¶](#tensortrade.oms.orders.create.hidden_limit_order "Permalink to this definition")

Creates a hidden limit order.

| Parameters: | * **side** (TradeSide) – The side of the order.

* **exchange\_pair** (ExchangePair) – The exchange pair to perform the order for.

* **limit\_price** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The limit price of the order.

* **size** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The size of the order.

* **portfolio** (Portfolio) – The portfolio being used in the order.

* **start** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *optional*) – The start time of the order.

* **end** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *optional*) – The end time of the order.

 |

| Returns: | Order – A hidden limit order. |

`tensortrade.oms.orders.create.``limit_order`(*side: tensortrade.oms.orders.trade.TradeSide*, *exchange\_pair: tensortrade.oms.instruments.exchange\_pair.ExchangePair*, *limit\_price: float*, *size: float*, *portfolio: tensortrade.oms.wallets.portfolio.Portfolio*, *start: int = None*, *end: int = None*)[[source]](_modules/tensortrade/oms/orders/create.html#limit_order)[¶](#tensortrade.oms.orders.create.limit_order "Permalink to this definition")

Creates a limit order.

| Parameters: | * **side** (TradeSide) – The side of the order.

* **exchange\_pair** (ExchangePair) – The exchange pair to perform the order for.

* **limit\_price** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The limit price of the order.

* **size** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The size of the order.

* **portfolio** (Portfolio) – The portfolio being used in the order.

* **start** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *optional*) – The start time of the order.

* **end** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *optional*) – The end time of the order.

 |

| Returns: | Order – A limit order. |

`tensortrade.oms.orders.create.``market_order`(*side: tensortrade.oms.orders.trade.TradeSide*, *exchange\_pair: tensortrade.oms.instruments.exchange\_pair.ExchangePair*, *price: float*, *size: float*, *portfolio: tensortrade.oms.wallets.portfolio.Portfolio*) → tensortrade.oms.orders.order.Order[[source]](_modules/tensortrade/oms/orders/create.html#market_order)[¶](#tensortrade.oms.orders.create.market_order "Permalink to this definition")

Creates a market order.

| Parameters: | * **side** (TradeSide) – The side of the order.

* **exchange\_pair** (ExchangePair) – The exchange pair to perform the order for.

* **price** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The current price.

* **size** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The size of the order.

* **portfolio** (Portfolio) – The portfolio being used in the order.

 |

| Returns: | Order – A market order. |

`tensortrade.oms.orders.create.``proportion_order`(*portfolio: Portfolio*, *source: Wallet*, *target: Wallet*, *proportion: float*) → Order[[source]](_modules/tensortrade/oms/orders/create.html#proportion_order)[¶](#tensortrade.oms.orders.create.proportion_order "Permalink to this definition")

Creates an order that sends a proportion of funds from one wallet to

another.

| Parameters: | * **portfolio** (Portfolio) – The portfolio that contains both wallets.

* **source** (Wallet) – The source wallet for the funds.

* **target** (Wallet) – The target wallet for the funds.

* **proportion** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The proportion of funds to send.

 |

`tensortrade.oms.orders.create.``risk_managed_order`(*side: TradeSide*, *trade\_type: TradeType*, *exchange\_pair: ExchangePair*, *price: float*, *quantity: Quantity*, *down\_percent: float*, *up\_percent: float*, *portfolio: Portfolio*, *start: int = None*, *end: int = None*)[[source]](_modules/tensortrade/oms/orders/create.html#risk_managed_order)[¶](#tensortrade.oms.orders.create.risk_managed_order "Permalink to this definition")

Create a stop order that manages for percentages above and below the

entry price of the order.

| Parameters: | * **side** (TradeSide) – The side of the order.

* **trade\_type** (TradeType) – The type of trade to make when going in.

* **exchange\_pair** (ExchangePair) – The exchange pair to perform the order for.

* **price** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The current price.

* **down\_percent** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The percentage the price is allowed to drop before exiting.

* **up\_percent** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The percentage the price is allowed to rise before exiting.

* **quantity** (Quantity) – The quantity of the order.

* **portfolio** (Portfolio) – The portfolio being used in the order.

* **start** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *optional*) – The start time of the order.

* **end** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *optional*) – The end time of the order.

 |

| Returns: | Order – A stop order controlling for the percentages above and below the entry

price. |

######### tensortrade.oms.orders.criteria module[¶](#module-tensortrade.oms.orders.criteria "Permalink to this headline")

*class* `tensortrade.oms.orders.criteria.``Criteria`[[source]](_modules/tensortrade/oms/orders/criteria.html#Criteria)[¶](#tensortrade.oms.orders.criteria.Criteria "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

A criteria to be satisfied before an order will be executed.

`check`(*order: tensortrade.oms.orders.order.Order*, *exchange: tensortrade.oms.exchanges.exchange.Exchange*) → bool[[source]](_modules/tensortrade/oms/orders/criteria.html#Criteria.check)[¶](#tensortrade.oms.orders.criteria.Criteria.check "Permalink to this definition")

Checks whether the order is executable on exchange.

| Parameters: | * **order** (Order) – An order.

* **exchange** (Exchange) – The exchange to check.

 |

| Returns: | *bool* – Whether order is executable on exchange. |

*class* `tensortrade.oms.orders.criteria.``CriteriaBinOp`(*left: Callable[[tensortrade.oms.orders.order.Order, tensortrade.oms.exchanges.exchange.Exchange], bool], right: Callable[[tensortrade.oms.orders.order.Order, tensortrade.oms.exchanges.exchange.Exchange], bool], op: Callable[[bool, bool], bool], op\_str: str*)[[source]](_modules/tensortrade/oms/orders/criteria.html#CriteriaBinOp)[¶](#tensortrade.oms.orders.criteria.CriteriaBinOp "Permalink to this definition")

Bases: [`tensortrade.oms.orders.criteria.Criteria`](#tensortrade.oms.orders.criteria.Criteria "tensortrade.oms.orders.criteria.Criteria")

A class for using a binary operation for criteria.

| Parameters: | * **left** (Callable[[Order, Exchange], bool]) – The left criteria argument.

* **right** (Callable[[Order, Exchange], bool]) – The right criteria argument.

* **op** (Callable[[bool, bool], bool]) – The binary boolean operation.

* **op\_str** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The string representing the op.

 |

`check`(*order: tensortrade.oms.orders.order.Order*, *exchange: tensortrade.oms.exchanges.exchange.Exchange*) → bool[[source]](_modules/tensortrade/oms/orders/criteria.html#CriteriaBinOp.check)[¶](#tensortrade.oms.orders.criteria.CriteriaBinOp.check "Permalink to this definition")

Checks whether the order is executable on exchange.

| Parameters: | * **order** (Order) – An order.

* **exchange** (Exchange) – The exchange to check.

 |

| Returns: | *bool* – Whether order is executable on exchange. |

*class* `tensortrade.oms.orders.criteria.``Limit`(*limit\_price: float*)[[source]](_modules/tensortrade/oms/orders/criteria.html#Limit)[¶](#tensortrade.oms.orders.criteria.Limit "Permalink to this definition")

Bases: [`tensortrade.oms.orders.criteria.Criteria`](#tensortrade.oms.orders.criteria.Criteria "tensortrade.oms.orders.criteria.Criteria")

An order criteria that allows execution when the quote price for a

trading pair is at or below a specific price, hidden from the public

order book.

| Parameters: | **limit\_price** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The quote price to check for execution. |

`check`(*order: tensortrade.oms.orders.order.Order*, *exchange: tensortrade.oms.exchanges.exchange.Exchange*) → bool[[source]](_modules/tensortrade/oms/orders/criteria.html#Limit.check)[¶](#tensortrade.oms.orders.criteria.Limit.check "Permalink to this definition")

Checks whether the order is executable on exchange.

| Parameters: | * **order** (Order) – An order.

* **exchange** (Exchange) – The exchange to check.

 |

| Returns: | *bool* – Whether order is executable on exchange. |

*class* `tensortrade.oms.orders.criteria.``NotCriteria`(*criteria: Callable[[tensortrade.oms.orders.order.Order, tensortrade.oms.exchanges.exchange.Exchange], bool]*)[[source]](_modules/tensortrade/oms/orders/criteria.html#NotCriteria)[¶](#tensortrade.oms.orders.criteria.NotCriteria "Permalink to this definition")

Bases: [`tensortrade.oms.orders.criteria.Criteria`](#tensortrade.oms.orders.criteria.Criteria "tensortrade.oms.orders.criteria.Criteria")

A criteria to invert the truth value of another criteria.

| Parameters: | **criteria** (Callable[[Order, Exchange], bool]) – The criteria to invert the truth value of. |

`check`(*order: tensortrade.oms.orders.order.Order*, *exchange: tensortrade.oms.exchanges.exchange.Exchange*) → bool[[source]](_modules/tensortrade/oms/orders/criteria.html#NotCriteria.check)[¶](#tensortrade.oms.orders.criteria.NotCriteria.check "Permalink to this definition")

Checks whether the order is executable on exchange.

| Parameters: | * **order** (Order) – An order.

* **exchange** (Exchange) – The exchange to check.

 |

| Returns: | *bool* – Whether order is executable on exchange. |

*class* `tensortrade.oms.orders.criteria.``Stop`(*direction: Union[tensortrade.oms.orders.criteria.StopDirection, str], percent: float*)[[source]](_modules/tensortrade/oms/orders/criteria.html#Stop)[¶](#tensortrade.oms.orders.criteria.Stop "Permalink to this definition")

Bases: [`tensortrade.oms.orders.criteria.Criteria`](#tensortrade.oms.orders.criteria.Criteria "tensortrade.oms.orders.criteria.Criteria")

An order criteria that allows execution when the quote price for a

trading pair is above or below a specific price.

| Parameters: | * **direction** (Union[StopDirection, str]) – The direction to watch for the stop criteria.

* **percent** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The percentage of the current price to use for watching.

 |

`check`(*order: tensortrade.oms.orders.order.Order*, *exchange: tensortrade.oms.exchanges.exchange.Exchange*) → bool[[source]](_modules/tensortrade/oms/orders/criteria.html#Stop.check)[¶](#tensortrade.oms.orders.criteria.Stop.check "Permalink to this definition")

Checks whether the order is executable on exchange.

| Parameters: | * **order** (Order) – An order.

* **exchange** (Exchange) – The exchange to check.

 |

| Returns: | *bool* – Whether order is executable on exchange. |

*class* `tensortrade.oms.orders.criteria.``StopDirection`[[source]](_modules/tensortrade/oms/orders/criteria.html#StopDirection)[¶](#tensortrade.oms.orders.criteria.StopDirection "Permalink to this definition")

Bases: [`enum.Enum`](https://docs.python.org/3/library/enum.html#enum.Enum "(in Python v3.9)")

An enumeration for the directions of a stop criteria.

`DOWN` *= 'down'*[¶](#tensortrade.oms.orders.criteria.StopDirection.DOWN "Permalink to this definition")

`UP` *= 'up'*[¶](#tensortrade.oms.orders.criteria.StopDirection.UP "Permalink to this definition")

*class* `tensortrade.oms.orders.criteria.``Timed`(*duration: float*)[[source]](_modules/tensortrade/oms/orders/criteria.html#Timed)[¶](#tensortrade.oms.orders.criteria.Timed "Permalink to this definition")

Bases: [`tensortrade.oms.orders.criteria.Criteria`](#tensortrade.oms.orders.criteria.Criteria "tensortrade.oms.orders.criteria.Criteria")

An order criteria for waiting a certain amount of time for execution.

| Parameters: | **duration** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The amount of time to wait. |

`check`(*order: tensortrade.oms.orders.order.Order*, *exchange: tensortrade.oms.exchanges.exchange.Exchange*)[[source]](_modules/tensortrade/oms/orders/criteria.html#Timed.check)[¶](#tensortrade.oms.orders.criteria.Timed.check "Permalink to this definition")

Checks whether the order is executable on exchange.

| Parameters: | * **order** (Order) – An order.

* **exchange** (Exchange) – The exchange to check.

 |

| Returns: | *bool* – Whether order is executable on exchange. |

######### tensortrade.oms.orders.order module[¶](#module-tensortrade.oms.orders.order "Permalink to this headline")

*class* `tensortrade.oms.orders.order.``Order`(*step: int, side: tensortrade.oms.orders.trade.TradeSide, trade\_type: tensortrade.oms.orders.trade.TradeType, exchange\_pair: ExchangePair, quantity: Quantity, portfolio: Portfolio, price: float, criteria: Callable[[Order, Exchange], bool] = None, path\_id: str = None, start: int = None, end: int = None*)[[source]](_modules/tensortrade/oms/orders/order.html#Order)[¶](#tensortrade.oms.orders.order.Order "Permalink to this definition")

Bases: [`tensortrade.core.base.TimedIdentifiable`](index.html#tensortrade.core.base.TimedIdentifiable "tensortrade.core.base.TimedIdentifiable"), [`tensortrade.core.base.Observable`](index.html#tensortrade.core.base.Observable "tensortrade.core.base.Observable")

A class to represent ordering an amount of a financial instrument.

Responsibilities of the Order:

1. Confirming its own validity.

2. Tracking its trades and reporting it back to the broker.

3. Managing movement of quantities from order to order.

4. Generating the next order in its path given that there is a

‘OrderSpec’ for how to make the next order.

5. Managing its own state changes when it can.

| Parameters: | **side** (TradeSide) – The side of the order. |

exchange\_pair : ExchangePair

The exchange pair to perform the order for.

price : float

The price of the order.

trade\_type : TradeType

The type of trade being made.

exchange\_pair : ExchangePair

The exchange pair that the order is made for.

quantity : Quantity

The quantity of the order.

portfolio : Portfolio

The portfolio being used in the order.

criteria : Callable[[Order, Exchange], bool], optional

The criteria under which the order will be considered executable.

path\_id : str, optional

The path order id.

start : int, optional

The start time of the order.

end : int, optional

The end time of the order.

| Raises: | `InvalidOrderQuantity` – Raised if the given quantity has a size of 0. |

`add_order_spec`(*order\_spec: OrderSpec*) → Order[[source]](_modules/tensortrade/oms/orders/order.html#Order.add_order_spec)[¶](#tensortrade.oms.orders.order.Order.add_order_spec "Permalink to this definition")

Adds an order specification to the order.

| Parameters: | **order\_spec** (OrderSpec) – An order specification. |

| Returns: | Order – The current order. |

`base_instrument`[¶](#tensortrade.oms.orders.order.Order.base_instrument "Permalink to this definition")

The base instrument of the pair being traded.

`cancel`(*reason: str = 'CANCELLED'*) → None[[source]](_modules/tensortrade/oms/orders/order.html#Order.cancel)[¶](#tensortrade.oms.orders.order.Order.cancel "Permalink to this definition")

Cancels an order.

| Parameters: | **reason** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *default 'CANCELLED'*) – The reason for canceling the order. |

`complete`() → tensortrade.oms.orders.order.Order[[source]](_modules/tensortrade/oms/orders/order.html#Order.complete)[¶](#tensortrade.oms.orders.order.Order.complete "Permalink to this definition")

Completes an order.

| Returns: | Order – The completed order. |

`execute`() → None[[source]](_modules/tensortrade/oms/orders/order.html#Order.execute)[¶](#tensortrade.oms.orders.order.Order.execute "Permalink to this definition")

Executes the order.

`fill`(*trade: tensortrade.oms.orders.trade.Trade*) → None[[source]](_modules/tensortrade/oms/orders/order.html#Order.fill)[¶](#tensortrade.oms.orders.order.Order.fill "Permalink to this definition")

Fills the order.

| Parameters: | **trade** (Trade) – A trade to fill the order. |

`is_active`[¶](#tensortrade.oms.orders.order.Order.is_active "Permalink to this definition")

If this order is active. (bool, read-only)

`is_buy`[¶](#tensortrade.oms.orders.order.Order.is_buy "Permalink to this definition")

If this is a buy order. (bool, read-only)

`is_cancelled`[¶](#tensortrade.oms.orders.order.Order.is_cancelled "Permalink to this definition")

If this order is cancelled. (bool, read-only)

`is_complete`[¶](#tensortrade.oms.orders.order.Order.is_complete "Permalink to this definition")

If this order is complete. (bool, read-only)

`is_executable`[¶](#tensortrade.oms.orders.order.Order.is_executable "Permalink to this definition")

If this order is executable. (bool, read-only)

`is_expired`[¶](#tensortrade.oms.orders.order.Order.is_expired "Permalink to this definition")

If this order is expired. (bool, read-only)

`is_limit_order`[¶](#tensortrade.oms.orders.order.Order.is_limit_order "Permalink to this definition")

If this is a limit order. (bool, read-only)

`is_market_order`[¶](#tensortrade.oms.orders.order.Order.is_market_order "Permalink to this definition")

If this is a market order. (bool, read-only)

`is_sell`[¶](#tensortrade.oms.orders.order.Order.is_sell "Permalink to this definition")

If this is a sell order. (bool, read-only)

`pair`[¶](#tensortrade.oms.orders.order.Order.pair "Permalink to this definition")

The trading pair of the order. (TradingPair, read-only)

`quote_instrument`[¶](#tensortrade.oms.orders.order.Order.quote_instrument "Permalink to this definition")

The quote instrument of the pair being traded.

`release`(*reason: str = 'RELEASE (NO REASON)'*) → None[[source]](_modules/tensortrade/oms/orders/order.html#Order.release)[¶](#tensortrade.oms.orders.order.Order.release "Permalink to this definition")

Releases all quantities from every wallet that have been allocated

for this order.

| Parameters: | **reason** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *default 'RELEASE* *(**NO REASON**)**'*) – The reason for releasing all locked quantities associated with the

order. |

`size`[¶](#tensortrade.oms.orders.order.Order.size "Permalink to this definition")

The size of the order. (Decimal, read-only)

`to_dict`() → dict[[source]](_modules/tensortrade/oms/orders/order.html#Order.to_dict)[¶](#tensortrade.oms.orders.order.Order.to_dict "Permalink to this definition")

Creates a dictionary representation of the order.

| Returns: | *dict* – The dictionary representation of the order. |

`to_json`() → dict[[source]](_modules/tensortrade/oms/orders/order.html#Order.to_json)[¶](#tensortrade.oms.orders.order.Order.to_json "Permalink to this definition")

Creates a json dictionary representation of the order.

| Returns: | *dict* – The json dictionary representation of the order |

*class* `tensortrade.oms.orders.order.``OrderStatus`[[source]](_modules/tensortrade/oms/orders/order.html#OrderStatus)[¶](#tensortrade.oms.orders.order.OrderStatus "Permalink to this definition")

Bases: [`enum.Enum`](https://docs.python.org/3/library/enum.html#enum.Enum "(in Python v3.9)")

An enumeration for the status of an order.

`CANCELLED` *= 'cancelled'*[¶](#tensortrade.oms.orders.order.OrderStatus.CANCELLED "Permalink to this definition")

`FILLED` *= 'filled'*[¶](#tensortrade.oms.orders.order.OrderStatus.FILLED "Permalink to this definition")

`OPEN` *= 'open'*[¶](#tensortrade.oms.orders.order.OrderStatus.OPEN "Permalink to this definition")

`PARTIALLY_FILLED` *= 'partially\_filled'*[¶](#tensortrade.oms.orders.order.OrderStatus.PARTIALLY_FILLED "Permalink to this definition")

`PENDING` *= 'pending'*[¶](#tensortrade.oms.orders.order.OrderStatus.PENDING "Permalink to this definition")

######### tensortrade.oms.orders.order\_listener module[¶](#module-tensortrade.oms.orders.order_listener "Permalink to this headline")

*class* `tensortrade.oms.orders.order_listener.``OrderListener`[[source]](_modules/tensortrade/oms/orders/order_listener.html#OrderListener)[¶](#tensortrade.oms.orders.order_listener.OrderListener "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

A callback class for an order.

`on_cancel`(*order: Order*) → None[[source]](_modules/tensortrade/oms/orders/order_listener.html#OrderListener.on_cancel)[¶](#tensortrade.oms.orders.order_listener.OrderListener.on_cancel "Permalink to this definition")

Callback for an order after cancellation.

| Parameters: | **order** (Order) – The cancelled order. |

`on_complete`(*order: Order*) → None[[source]](_modules/tensortrade/oms/orders/order_listener.html#OrderListener.on_complete)[¶](#tensortrade.oms.orders.order_listener.OrderListener.on_complete "Permalink to this definition")

Callback for an order after being completed.

| Parameters: | **order** (Order) – The completed order. |

`on_execute`(*order: Order*) → None[[source]](_modules/tensortrade/oms/orders/order_listener.html#OrderListener.on_execute)[¶](#tensortrade.oms.orders.order_listener.OrderListener.on_execute "Permalink to this definition")

Callback for an order after execution.

| Parameters: | **order** (Order) – The executed order. |

`on_fill`(*order: Order*, *trade: Trade*) → None[[source]](_modules/tensortrade/oms/orders/order_listener.html#OrderListener.on_fill)[¶](#tensortrade.oms.orders.order_listener.OrderListener.on_fill "Permalink to this definition")

Callback for an order after being filled.

| Parameters: | * **order** (Order) – The order being filled.

* **trade** (Trade) – The trade that is filling the order.

 |

######### tensortrade.oms.orders.order\_spec module[¶](#module-tensortrade.oms.orders.order_spec "Permalink to this headline")

*class* `tensortrade.oms.orders.order_spec.``OrderSpec`(*side: TradeSide, trade\_type: TradeType, exchange\_pair: ExchangePair, criteria: Callable[[Order, Exchange], bool] = None*)[[source]](_modules/tensortrade/oms/orders/order_spec.html#OrderSpec)[¶](#tensortrade.oms.orders.order_spec.OrderSpec "Permalink to this definition")

Bases: [`tensortrade.core.base.Identifiable`](index.html#tensortrade.core.base.Identifiable "tensortrade.core.base.Identifiable")

A class for order creation following an order being complete.

| Parameters: | * **side** (TradeSide) – The trading side of the specification.

* **trade\_type** (TradeType) – The type of trade for the specification.

* **exchange\_pair** (ExchangePair) – The exchange pair for the specification.

* **criteria** (Callable[[Order, Exchange], bool]) – The criteria for executing the order after its been created.

 |

`create_order`(*order: tensortrade.oms.orders.order.Order*) → tensortrade.oms.orders.order.Order[[source]](_modules/tensortrade/oms/orders/order_spec.html#OrderSpec.create_order)[¶](#tensortrade.oms.orders.order_spec.OrderSpec.create_order "Permalink to this definition")

Creates an order following from another order.

| Parameters: | **order** (Order) – The previous order in the order path. |

| Returns: | Order – The order created from the specification parameters and the

parameters of order. |

`to_dict`() → dict[[source]](_modules/tensortrade/oms/orders/order_spec.html#OrderSpec.to_dict)[¶](#tensortrade.oms.orders.order_spec.OrderSpec.to_dict "Permalink to this definition")

Creates dictionary representation of specification.

| Returns: | *dict* – The dictionary representation of specification. |

######### tensortrade.oms.orders.trade module[¶](#module-tensortrade.oms.orders.trade "Permalink to this headline")

*class* `tensortrade.oms.orders.trade.``Trade`(*order\_id: str*, *step: int*, *exchange\_pair: ExchangePair*, *side: tensortrade.oms.orders.trade.TradeSide*, *trade\_type: tensortrade.oms.orders.trade.TradeType*, *quantity: Quantity*, *price: float*, *commission: Quantity*)[[source]](_modules/tensortrade/oms/orders/trade.html#Trade)[¶](#tensortrade.oms.orders.trade.Trade "Permalink to this definition")

Bases: [`tensortrade.core.base.TimedIdentifiable`](index.html#tensortrade.core.base.TimedIdentifiable "tensortrade.core.base.TimedIdentifiable")

A trade object for use within trading environments.

`__init__`(*order\_id: str*, *step: int*, *exchange\_pair: ExchangePair*, *side: tensortrade.oms.orders.trade.TradeSide*, *trade\_type: tensortrade.oms.orders.trade.TradeType*, *quantity: Quantity*, *price: float*, *commission: Quantity*)[[source]](_modules/tensortrade/oms/orders/trade.html#Trade.__init__)[¶](#tensortrade.oms.orders.trade.Trade.__init__ "Permalink to this definition")

| Parameters: | * **order\_id** – The id of the order that created the trade.

* **step** – The timestep the trade was made during the trading episode.

* **exchange\_pair** – The exchange pair of instruments in the trade.

* **BTC/USDT****,** **ETH/BTC****,** **ADA/BTC****,** **AAPL/USD****,** **NQ1!/USD****,** **CAD/USD****,** **etc****)** (*(**e.g.*) –

* **side** – Whether the quote instrument is being bought or sold.

* **BUY = trade the base\_instrument for the quote\_instrument in the pair. SELL = trade the quote\_instrument for the base\_instrument****)** (*(**e.g.*) –

* **size** – The size of the core instrument in the trade.

* **1000 shares****,** **6.50 satoshis****,** **2.3 contracts****,** **etc****)** (*(**e.g.*) –

* **price** – The price paid per quote instrument in terms of the core instrument.

* **10000 represents $10****,****000.00 if the base\_instrument is "USD"****)** (*(**e.g.*) –

* **commission** – The commission paid for the trade in terms of the core instrument.

* **10000 represents $10****,****000.00 if the base\_instrument is "USD"****)** –

 |

`base_instrument`[¶](#tensortrade.oms.orders.trade.Trade.base_instrument "Permalink to this definition")

`commission`[¶](#tensortrade.oms.orders.trade.Trade.commission "Permalink to this definition")

`is_buy`[¶](#tensortrade.oms.orders.trade.Trade.is_buy "Permalink to this definition")

`is_limit_order`[¶](#tensortrade.oms.orders.trade.Trade.is_limit_order "Permalink to this definition")

`is_market_order`[¶](#tensortrade.oms.orders.trade.Trade.is_market_order "Permalink to this definition")

`is_sell`[¶](#tensortrade.oms.orders.trade.Trade.is_sell "Permalink to this definition")

`price`[¶](#tensortrade.oms.orders.trade.Trade.price "Permalink to this definition")

`quote_instrument`[¶](#tensortrade.oms.orders.trade.Trade.quote_instrument "Permalink to this definition")

`size`[¶](#tensortrade.oms.orders.trade.Trade.size "Permalink to this definition")

`to_dict`()[[source]](_modules/tensortrade/oms/orders/trade.html#Trade.to_dict)[¶](#tensortrade.oms.orders.trade.Trade.to_dict "Permalink to this definition")

`to_json`()[[source]](_modules/tensortrade/oms/orders/trade.html#Trade.to_json)[¶](#tensortrade.oms.orders.trade.Trade.to_json "Permalink to this definition")

*class* `tensortrade.oms.orders.trade.``TradeSide`[[source]](_modules/tensortrade/oms/orders/trade.html#TradeSide)[¶](#tensortrade.oms.orders.trade.TradeSide "Permalink to this definition")

Bases: [`enum.Enum`](https://docs.python.org/3/library/enum.html#enum.Enum "(in Python v3.9)")

An enumeration.

`BUY` *= 'buy'*[¶](#tensortrade.oms.orders.trade.TradeSide.BUY "Permalink to this definition")

`SELL` *= 'sell'*[¶](#tensortrade.oms.orders.trade.TradeSide.SELL "Permalink to this definition")

`instrument`(*pair: TradingPair*) → Instrument[[source]](_modules/tensortrade/oms/orders/trade.html#TradeSide.instrument)[¶](#tensortrade.oms.orders.trade.TradeSide.instrument "Permalink to this definition")

*class* `tensortrade.oms.orders.trade.``TradeType`[[source]](_modules/tensortrade/oms/orders/trade.html#TradeType)[¶](#tensortrade.oms.orders.trade.TradeType "Permalink to this definition")

Bases: [`enum.Enum`](https://docs.python.org/3/library/enum.html#enum.Enum "(in Python v3.9)")

An enumeration.

`LIMIT` *= 'limit'*[¶](#tensortrade.oms.orders.trade.TradeType.LIMIT "Permalink to this definition")

`MARKET` *= 'market'*[¶](#tensortrade.oms.orders.trade.TradeType.MARKET "Permalink to this definition")

####### tensortrade.oms.services package[¶](#module-tensortrade.oms.services "Permalink to this headline")

######## Subpackages[¶](#subpackages "Permalink to this headline")

######### tensortrade.oms.services.execution package[¶](#module-tensortrade.oms.services.execution "Permalink to this headline")

########## Submodules[¶](#submodules "Permalink to this headline")

########### tensortrade.oms.services.execution.ccxt module[¶](#module-tensortrade.oms.services.execution.ccxt "Permalink to this headline")

########### tensortrade.oms.services.execution.interactive\_brokers module[¶](#module-tensortrade.oms.services.execution.interactive_brokers "Permalink to this headline")

########### tensortrade.oms.services.execution.robinhood module[¶](#module-tensortrade.oms.services.execution.robinhood "Permalink to this headline")

########### tensortrade.oms.services.execution.simulated module[¶](#module-tensortrade.oms.services.execution.simulated "Permalink to this headline")

`tensortrade.oms.services.execution.simulated.``execute_buy_order`(*order: tensortrade.oms.orders.order.Order*, *base\_wallet: tensortrade.oms.wallets.wallet.Wallet*, *quote\_wallet: tensortrade.oms.wallets.wallet.Wallet*, *current\_price: float*, *options: tensortrade.oms.exchanges.exchange.ExchangeOptions*, *clock: tensortrade.core.clock.Clock*) → tensortrade.oms.orders.trade.Trade[[source]](_modules/tensortrade/oms/services/execution/simulated.html#execute_buy_order)[¶](#tensortrade.oms.services.execution.simulated.execute_buy_order "Permalink to this definition")

Executes a buy order on the exchange.

| Parameters: | * **order** (Order) – The order that is being filled.

* **base\_wallet** (Wallet) – The wallet of the base instrument.

* **quote\_wallet** (Wallet) – The wallet of the quote instrument.

* **current\_price** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The current price of the exchange pair.

* **options** (ExchangeOptions) – The exchange options.

* **clock** (Clock) – The clock for the trading process..

 |

| Returns: | Trade – The executed trade that was made. |

`tensortrade.oms.services.execution.simulated.``execute_order`(*order: Order*, *base\_wallet: Wallet*, *quote\_wallet: Wallet*, *current\_price: float*, *options: Options*, *clock: Clock*) → Trade[[source]](_modules/tensortrade/oms/services/execution/simulated.html#execute_order)[¶](#tensortrade.oms.services.execution.simulated.execute_order "Permalink to this definition")

Executes an order on the exchange.

| Parameters: | * **order** (Order) – The order that is being filled.

* **base\_wallet** (Wallet) – The wallet of the base instrument.

* **quote\_wallet** (Wallet) – The wallet of the quote instrument.

* **current\_price** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The current price of the exchange pair.

* **options** (ExchangeOptions) – The exchange options.

* **clock** (Clock) – The clock for the trading process..

 |

| Returns: | Trade – The executed trade that was made. |

`tensortrade.oms.services.execution.simulated.``execute_sell_order`(*order: tensortrade.oms.orders.order.Order*, *base\_wallet: tensortrade.oms.wallets.wallet.Wallet*, *quote\_wallet: tensortrade.oms.wallets.wallet.Wallet*, *current\_price: float*, *options: tensortrade.oms.exchanges.exchange.ExchangeOptions*, *clock: tensortrade.core.clock.Clock*) → tensortrade.oms.orders.trade.Trade[[source]](_modules/tensortrade/oms/services/execution/simulated.html#execute_sell_order)[¶](#tensortrade.oms.services.execution.simulated.execute_sell_order "Permalink to this definition")

Executes a sell order on the exchange.

| Parameters: | * **order** (Order) – The order that is being filled.

* **base\_wallet** (Wallet) – The wallet of the base instrument.

* **quote\_wallet** (Wallet) – The wallet of the quote instrument.

* **current\_price** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The current price of the exchange pair.

* **options** (ExchangeOptions) – The exchange options.

* **clock** (Clock) – The clock for the trading process..

 |

| Returns: | Trade – The executed trade that was made. |

######### tensortrade.oms.services.slippage package[¶](#module-tensortrade.oms.services.slippage "Permalink to this headline")

`tensortrade.oms.services.slippage.``get`(*identifier: str*) → tensortrade.oms.services.slippage.slippage\_model.SlippageModel[[source]](_modules/tensortrade/oms/services/slippage.html#get)[¶](#tensortrade.oms.services.slippage.get "Permalink to this definition")

Gets the SlippageModel that matches with the identifier.

| Parameters: | **identifier** – The identifier for the SlippageModel |

| Raises: | [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError "(in Python v3.9)") – if identifier is not associated with any SlippageModel |

########## Submodules[¶](#submodules "Permalink to this headline")

########### tensortrade.oms.services.slippage.random\_slippage\_model module[¶](#module-tensortrade.oms.services.slippage.random_slippage_model "Permalink to this headline")

*class* `tensortrade.oms.services.slippage.random_slippage_model.``RandomUniformSlippageModel`(*max\_slippage\_percent: float = 3.0*)[[source]](_modules/tensortrade/oms/services/slippage/random_slippage_model.html#RandomUniformSlippageModel)[¶](#tensortrade.oms.services.slippage.random_slippage_model.RandomUniformSlippageModel "Permalink to this definition")

Bases: [`tensortrade.oms.services.slippage.slippage\_model.SlippageModel`](index.html#tensortrade.oms.services.slippage.slippage_model.SlippageModel "tensortrade.oms.services.slippage.slippage_model.SlippageModel")

A uniform random slippage model.

| Parameters: | **max\_slippage\_percent** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default 3.0*) – The maximum random slippage to be applied to the fill price. |

`adjust_trade`(*trade: tensortrade.oms.orders.trade.Trade*, *\*\*kwargs*) → tensortrade.oms.orders.trade.Trade[[source]](_modules/tensortrade/oms/services/slippage/random_slippage_model.html#RandomUniformSlippageModel.adjust_trade)[¶](#tensortrade.oms.services.slippage.random_slippage_model.RandomUniformSlippageModel.adjust_trade "Permalink to this definition")

Simulate slippage on a trade ordered on a specific exchange.

| Parameters: | * **trade** (Trade) – The trade executed on the exchange.

* **\*\*kwargs** (*keyword arguments*) – Any other arguments necessary for the model.

 |

| Returns: | Trade – A filled trade with the price and size adjusted for slippage. |

########### tensortrade.oms.services.slippage.slippage\_model module[¶](#module-tensortrade.oms.services.slippage.slippage_model "Permalink to this headline")

*class* `tensortrade.oms.services.slippage.slippage_model.``SlippageModel`[[source]](_modules/tensortrade/oms/services/slippage/slippage_model.html#SlippageModel)[¶](#tensortrade.oms.services.slippage.slippage_model.SlippageModel "Permalink to this definition")

Bases: [`tensortrade.core.component.Component`](index.html#tensortrade.core.component.Component "tensortrade.core.component.Component")

A model for simulating slippage on an exchange trade.

`adjust_trade`(*trade: tensortrade.oms.orders.trade.Trade*, *\*\*kwargs*) → tensortrade.oms.orders.trade.Trade[[source]](_modules/tensortrade/oms/services/slippage/slippage_model.html#SlippageModel.adjust_trade)[¶](#tensortrade.oms.services.slippage.slippage_model.SlippageModel.adjust_trade "Permalink to this definition")

Simulate slippage on a trade ordered on a specific exchange.

| Parameters: | * **trade** (Trade) – The trade executed on the exchange.

* **\*\*kwargs** (*keyword arguments*) – Any other arguments necessary for the model.

 |

| Returns: | Trade – A filled trade with the price and size adjusted for slippage. |

`registered_name` *= 'slippage'*[¶](#tensortrade.oms.services.slippage.slippage_model.SlippageModel.registered_name "Permalink to this definition")

####### tensortrade.oms.wallets package[¶](#module-tensortrade.oms.wallets "Permalink to this headline")

`tensortrade.oms.wallets.``get`(*identifier: str*) → tensortrade.oms.wallets.portfolio.Portfolio[[source]](_modules/tensortrade/oms/wallets.html#get)[¶](#tensortrade.oms.wallets.get "Permalink to this definition")

Gets the TradingStrategy that matches with the identifier.

| Parameters: | **identifier** – The identifier for the TradingStrategy |

| Raises: | [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError "(in Python v3.9)") – if identifier is not associated with any TradingStrategy |

######## Submodules[¶](#submodules "Permalink to this headline")

######### tensortrade.oms.wallets.ledger module[¶](#module-tensortrade.oms.wallets.ledger "Permalink to this headline")

*class* `tensortrade.oms.wallets.ledger.``Ledger`[[source]](_modules/tensortrade/oms/wallets/ledger.html#Ledger)[¶](#tensortrade.oms.wallets.ledger.Ledger "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

A ledger to keep track of transactions that occur in the order

management system.

`as_frame`(*sort\_by\_order\_seq: bool = False*) → pandas.core.frame.DataFrame[[source]](_modules/tensortrade/oms/wallets/ledger.html#Ledger.as_frame)[¶](#tensortrade.oms.wallets.ledger.Ledger.as_frame "Permalink to this definition")

Converts the ledger records into a data frame.

| Parameters: | **sort\_by\_order\_seq** ([*bool*](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)")*,* *default False*) – If records should be sorted by each order path. |

| Returns: | pd.DataFrame – A data frame containing all the records in the ledger. |

`commit`(*wallet: Wallet*, *quantity: Quantity*, *source: str*, *target: str*, *memo: str*) → None[[source]](_modules/tensortrade/oms/wallets/ledger.html#Ledger.commit)[¶](#tensortrade.oms.wallets.ledger.Ledger.commit "Permalink to this definition")

Commits a transaction to the ledger records.

| Parameters: | * **wallet** (Wallet) – The wallet involved in this transaction.

* **quantity** (Quantity) – The amount being used.

* **source** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The source of funds being transferred.

* **target** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The destination the funds are being transferred to.

* **memo** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – A description of the transaction.

 |

`reset`()[[source]](_modules/tensortrade/oms/wallets/ledger.html#Ledger.reset)[¶](#tensortrade.oms.wallets.ledger.Ledger.reset "Permalink to this definition")

Resets the ledger.

*class* `tensortrade.oms.wallets.ledger.``Transaction`(*poid*, *step*, *source*, *target*, *memo*, *amount*, *free*, *locked*, *locked\_poid*)[¶](#tensortrade.oms.wallets.ledger.Transaction "Permalink to this definition")

Bases: [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)")

`amount`[¶](#tensortrade.oms.wallets.ledger.Transaction.amount "Permalink to this definition")

Alias for field number 5

`free`[¶](#tensortrade.oms.wallets.ledger.Transaction.free "Permalink to this definition")

Alias for field number 6

`locked`[¶](#tensortrade.oms.wallets.ledger.Transaction.locked "Permalink to this definition")

Alias for field number 7

`locked_poid`[¶](#tensortrade.oms.wallets.ledger.Transaction.locked_poid "Permalink to this definition")

Alias for field number 8

`memo`[¶](#tensortrade.oms.wallets.ledger.Transaction.memo "Permalink to this definition")

Alias for field number 4

`poid`[¶](#tensortrade.oms.wallets.ledger.Transaction.poid "Permalink to this definition")

Alias for field number 0

`source`[¶](#tensortrade.oms.wallets.ledger.Transaction.source "Permalink to this definition")

Alias for field number 2

`step`[¶](#tensortrade.oms.wallets.ledger.Transaction.step "Permalink to this definition")

Alias for field number 1

`target`[¶](#tensortrade.oms.wallets.ledger.Transaction.target "Permalink to this definition")

Alias for field number 3

######### tensortrade.oms.wallets.portfolio module[¶](#module-tensortrade.oms.wallets.portfolio "Permalink to this headline")

*class* `tensortrade.oms.wallets.portfolio.``Portfolio`(*base\_instrument: tensortrade.oms.instruments.instrument.Instrument, wallets: List[WalletType] = None, order\_listener: Optional[tensortrade.oms.orders.order\_listener.OrderListener] = None, performance\_listener: Callable[[collections.OrderedDict], None] = None*)[[source]](_modules/tensortrade/oms/wallets/portfolio.html#Portfolio)[¶](#tensortrade.oms.wallets.portfolio.Portfolio "Permalink to this definition")

Bases: [`tensortrade.core.component.Component`](index.html#tensortrade.core.component.Component "tensortrade.core.component.Component"), [`tensortrade.core.base.TimedIdentifiable`](index.html#tensortrade.core.base.TimedIdentifiable "tensortrade.core.base.TimedIdentifiable")

A portfolio of wallets on exchanges.

| Parameters: | * **base\_instrument** (Instrument) – The exchange instrument used to measure value and performance statistics.

* **wallets** (List[WalletType]) – The wallets to be used in the portfolio.

* **order\_listener** (OrderListener) – The order listener to set for all orders executed by this portfolio.

* **performance\_listener** (Callable[[OrderedDict], None]) – The performance listener to send all portfolio updates to.

 |

`add`(*wallet: WalletType*) → None[[source]](_modules/tensortrade/oms/wallets/portfolio.html#Portfolio.add)[¶](#tensortrade.oms.wallets.portfolio.Portfolio.add "Permalink to this definition")

Adds a wallet to the portfolio.

| Parameters: | **wallet** (WalletType) – The wallet to add to the portfolio. |

`balance`(*instrument: tensortrade.oms.instruments.instrument.Instrument*) → tensortrade.oms.instruments.quantity.Quantity[[source]](_modules/tensortrade/oms/wallets/portfolio.html#Portfolio.balance)[¶](#tensortrade.oms.wallets.portfolio.Portfolio.balance "Permalink to this definition")

Gets the total balance of the portfolio in a specific instrument

available for use.

| Parameters: | **instrument** (Instrument) – The instrument to compute the balance for. |

| Returns: | Quantity – The balance of the instrument over all wallets. |

`balances`[¶](#tensortrade.oms.wallets.portfolio.Portfolio.balances "Permalink to this definition")

The current unlocked balance of each instrument over all wallets. (List[Quantity], read-only)

`base_balance`[¶](#tensortrade.oms.wallets.portfolio.Portfolio.base_balance "Permalink to this definition")

The current balance of the base instrument over all wallets. (Quantity, read-only)

`exchange_pairs`[¶](#tensortrade.oms.wallets.portfolio.Portfolio.exchange_pairs "Permalink to this definition")

All the exchange pairs in the portfolio. (List[ExchangePair], read-only)

`exchanges`[¶](#tensortrade.oms.wallets.portfolio.Portfolio.exchanges "Permalink to this definition")

All the exchanges in the portfolio. (List[Exchange], read-only)

`get_wallet`(*exchange\_id: str*, *instrument: tensortrade.oms.instruments.instrument.Instrument*) → tensortrade.oms.wallets.wallet.Wallet[[source]](_modules/tensortrade/oms/wallets/portfolio.html#Portfolio.get_wallet)[¶](#tensortrade.oms.wallets.portfolio.Portfolio.get_wallet "Permalink to this definition")

Gets wallet by the exchange\_id and instrument.

| Parameters: | * **exchange\_id** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The exchange id used to identify the wallet.

* **instrument** (Instrument) – The instrument used to identify the wallet.

 |

| Returns: | Wallet – The wallet associated with exchange\_id and instrument. |

`initial_balance`[¶](#tensortrade.oms.wallets.portfolio.Portfolio.initial_balance "Permalink to this definition")

The initial balance of the base instrument over all wallets. (Quantity, read-only)

`initial_net_worth`[¶](#tensortrade.oms.wallets.portfolio.Portfolio.initial_net_worth "Permalink to this definition")

The initial net worth of the portfolio. (float, read-only)

`ledger`[¶](#tensortrade.oms.wallets.portfolio.Portfolio.ledger "Permalink to this definition")

The ledger that keeps track of transactions. (Ledger, read-only)

`locked_balance`(*instrument: tensortrade.oms.instruments.instrument.Instrument*) → tensortrade.oms.instruments.quantity.Quantity[[source]](_modules/tensortrade/oms/wallets/portfolio.html#Portfolio.locked_balance)[¶](#tensortrade.oms.wallets.portfolio.Portfolio.locked_balance "Permalink to this definition")

Gets the total balance a specific instrument locked in orders over

the entire portfolio.

| Parameters: | **instrument** (Instrument) – The instrument to find locked balances for. |

| Returns: | Quantity – The total locked balance of the instrument. |

`locked_balances`[¶](#tensortrade.oms.wallets.portfolio.Portfolio.locked_balances "Permalink to this definition")

The current locked balance of each instrument over all wallets. (List[Quantity], read-only)

`net_worth`[¶](#tensortrade.oms.wallets.portfolio.Portfolio.net_worth "Permalink to this definition")

The current net worth of the portfolio. (float, read-only)

`on_next`(*data: dict*) → None[[source]](_modules/tensortrade/oms/wallets/portfolio.html#Portfolio.on_next)[¶](#tensortrade.oms.wallets.portfolio.Portfolio.on_next "Permalink to this definition")

Updates the performance metrics.

| Parameters: | **data** ([*dict*](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)")) – The data produced from the observer feed that is used to

update the performance metrics. |

`performance`[¶](#tensortrade.oms.wallets.portfolio.Portfolio.performance "Permalink to this definition")

The performance of the portfolio since the last reset. (OrderedDict, read-only)

`profit_loss`[¶](#tensortrade.oms.wallets.portfolio.Portfolio.profit_loss "Permalink to this definition")

The percent loss in net worth since the last reset. (float, read-only)

`registered_name` *= 'portfolio'*[¶](#tensortrade.oms.wallets.portfolio.Portfolio.registered_name "Permalink to this definition")

`remove`(*wallet: tensortrade.oms.wallets.wallet.Wallet*) → None[[source]](_modules/tensortrade/oms/wallets/portfolio.html#Portfolio.remove)[¶](#tensortrade.oms.wallets.portfolio.Portfolio.remove "Permalink to this definition")

Removes a wallet from the portfolio.

| Parameters: | **wallet** (Wallet) – The wallet to be removed. |

`remove_pair`(*exchange: tensortrade.oms.exchanges.exchange.Exchange*, *instrument: tensortrade.oms.instruments.instrument.Instrument*) → None[[source]](_modules/tensortrade/oms/wallets/portfolio.html#Portfolio.remove_pair)[¶](#tensortrade.oms.wallets.portfolio.Portfolio.remove_pair "Permalink to this definition")

Removes a wallet from the portfolio by exchange and instrument.

| Parameters: | * **exchange** (Exchange) – The exchange of the wallet to be removed.

* **instrument** (Instrument) – The instrument of the wallet to be removed.

 |

`reset`() → None[[source]](_modules/tensortrade/oms/wallets/portfolio.html#Portfolio.reset)[¶](#tensortrade.oms.wallets.portfolio.Portfolio.reset "Permalink to this definition")

Resets the portfolio.

`total_balance`(*instrument: tensortrade.oms.instruments.instrument.Instrument*) → tensortrade.oms.instruments.quantity.Quantity[[source]](_modules/tensortrade/oms/wallets/portfolio.html#Portfolio.total_balance)[¶](#tensortrade.oms.wallets.portfolio.Portfolio.total_balance "Permalink to this definition")

Gets the total balance of a specific instrument over the portfolio,

both available for use and locked in orders.

| Parameters: | **instrument** (Instrument) – The instrument to get total balance of. |

| Returns: | Quantity – The total balance of instrument over the portfolio. |

`total_balances`[¶](#tensortrade.oms.wallets.portfolio.Portfolio.total_balances "Permalink to this definition")

The current total balance of each instrument over all wallets. (List[Quantity], read-only)

`wallets`[¶](#tensortrade.oms.wallets.portfolio.Portfolio.wallets "Permalink to this definition")

All the wallets in the portfolio. (List[Wallet], read-only)

######### tensortrade.oms.wallets.wallet module[¶](#module-tensortrade.oms.wallets.wallet "Permalink to this headline")

*class* `tensortrade.oms.wallets.wallet.``Transfer`(*quantity*, *commission*, *price*)[¶](#tensortrade.oms.wallets.wallet.Transfer "Permalink to this definition")

Bases: [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)")

`commission`[¶](#tensortrade.oms.wallets.wallet.Transfer.commission "Permalink to this definition")

Alias for field number 1

`price`[¶](#tensortrade.oms.wallets.wallet.Transfer.price "Permalink to this definition")

Alias for field number 2

`quantity`[¶](#tensortrade.oms.wallets.wallet.Transfer.quantity "Permalink to this definition")

Alias for field number 0

*class* `tensortrade.oms.wallets.wallet.``Wallet`(*exchange: tensortrade.oms.exchanges.exchange.Exchange*, *balance: tensortrade.oms.instruments.quantity.Quantity*)[[source]](_modules/tensortrade/oms/wallets/wallet.html#Wallet)[¶](#tensortrade.oms.wallets.wallet.Wallet "Permalink to this definition")

Bases: [`tensortrade.core.base.Identifiable`](index.html#tensortrade.core.base.Identifiable "tensortrade.core.base.Identifiable")

A wallet stores the balance of a specific instrument on a specific exchange.

| Parameters: | * **exchange** (Exchange) – The exchange associated with this wallet.

* **balance** (Quantity) – The initial balance quantity for the wallet.

 |

`deposit`(*quantity: tensortrade.oms.instruments.quantity.Quantity*, *reason: str*) → tensortrade.oms.instruments.quantity.Quantity[[source]](_modules/tensortrade/oms/wallets/wallet.html#Wallet.deposit)[¶](#tensortrade.oms.wallets.wallet.Wallet.deposit "Permalink to this definition")

Deposits funds into the wallet.

| Parameters: | * **quantity** (Quantity) – The amount to deposit into this wallet.

* **reason** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The reason for depositing the amount.

 |

| Returns: | Quantity – The deposited amount. |

*classmethod* `from_tuple`(*wallet\_tuple: Tuple[tensortrade.oms.exchanges.exchange.Exchange, tensortrade.oms.instruments.instrument.Instrument, float]*) → tensortrade.oms.wallets.wallet.Wallet[[source]](_modules/tensortrade/oms/wallets/wallet.html#Wallet.from_tuple)[¶](#tensortrade.oms.wallets.wallet.Wallet.from_tuple "Permalink to this definition")

Creates a wallet from a wallet tuple.

| Parameters: | **wallet\_tuple** (Tuple[Exchange, Instrument, float]) – A tuple containing an exchange, instrument, and amount. |

| Returns: | Wallet – A wallet corresponding to the arguments given in the tuple. |

`ledger` *= <tensortrade.oms.wallets.ledger.Ledger object>*[¶](#tensortrade.oms.wallets.wallet.Wallet.ledger "Permalink to this definition")

`lock`(*quantity*, *order: tensortrade.oms.orders.order.Order*, *reason: str*) → tensortrade.oms.instruments.quantity.Quantity[[source]](_modules/tensortrade/oms/wallets/wallet.html#Wallet.lock)[¶](#tensortrade.oms.wallets.wallet.Wallet.lock "Permalink to this definition")

Locks funds for specified order.

| Parameters: | * **quantity** (Quantity) – The amount of funds to lock for the order.

* **order** (Order) – The order funds will be locked for.

* **reason** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The reason for locking funds.

 |

| Returns: | Quantity – The locked quantity for order. |

| Raises: | * `DoubleLockedQuantity` – Raised if the given amount is already a locked quantity.

* `InsufficientFunds` – Raised if amount is greater the current balance.

 |

`locked`[¶](#tensortrade.oms.wallets.wallet.Wallet.locked "Permalink to this definition")

The current quantities that are locked for orders. (Dict[str, Quantity], read-only)

`locked_balance`[¶](#tensortrade.oms.wallets.wallet.Wallet.locked_balance "Permalink to this definition")

The total balance of the wallet locked in orders. (Quantity, read-only)

`reset`() → None[[source]](_modules/tensortrade/oms/wallets/wallet.html#Wallet.reset)[¶](#tensortrade.oms.wallets.wallet.Wallet.reset "Permalink to this definition")

Resets the wallet.

`total_balance`[¶](#tensortrade.oms.wallets.wallet.Wallet.total_balance "Permalink to this definition")

The total balance of the wallet available for use and locked in orders. (Quantity, read-only)

*static* `transfer`(*source: tensortrade.oms.wallets.wallet.Wallet*, *target: tensortrade.oms.wallets.wallet.Wallet*, *quantity: tensortrade.oms.instruments.quantity.Quantity*, *commission: tensortrade.oms.instruments.quantity.Quantity*, *exchange\_pair: tensortrade.oms.instruments.exchange\_pair.ExchangePair*, *reason: str*) → tensortrade.oms.wallets.wallet.Transfer[[source]](_modules/tensortrade/oms/wallets/wallet.html#Wallet.transfer)[¶](#tensortrade.oms.wallets.wallet.Wallet.transfer "Permalink to this definition")

Transfers funds from one wallet to another.

| Parameters: | * **source** (Wallet) – The wallet in which funds will be transferred from

* **target** (Wallet) – The wallet in which funds will be transferred to

* **quantity** (Quantity) – The quantity to be transferred from the source to the target.

In terms of the instrument of the source wallet.

* **commission** (Quantity) – The commission to be taken from the source wallet for performing

the transfer of funds.

* **exchange\_pair** (ExchangePair) – The exchange pair associated with the transfer

* **reason** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The reason for transferring the funds.

 |

| Returns: | Transfer – A transfer object describing the transaction. |

| Raises: | [`Exception`](https://docs.python.org/3/library/exceptions.html#Exception "(in Python v3.9)") – Raised if an equation that describes the conservation of funds

is broken. |

`unlock`(*quantity: tensortrade.oms.instruments.quantity.Quantity*, *reason: str*) → tensortrade.oms.instruments.quantity.Quantity[[source]](_modules/tensortrade/oms/wallets/wallet.html#Wallet.unlock)[¶](#tensortrade.oms.wallets.wallet.Wallet.unlock "Permalink to this definition")

Unlocks a certain amount from the locked funds of the wallet that

are associated with the given quantity path id.

| Parameters: | * **quantity** (Quantity) – The quantity to unlock from the funds.

* **reason** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The reason for unlocking funds.

 |

| Returns: | Quantity – The free quantity. |

| Raises: | * `DoubleUnlockedFunds` – Raised if quantity is not a locked quantity.

* `QuantityNotLocked` – Raised if quantity has a path id that is not currently allocated

in this wallet.

* `InsufficientFunds` – Raised if quantity is greater than the amount currently allocated

for the associated path id.

 |

`withdraw`(*quantity: tensortrade.oms.instruments.quantity.Quantity*, *reason: str*) → tensortrade.oms.instruments.quantity.Quantity[[source]](_modules/tensortrade/oms/wallets/wallet.html#Wallet.withdraw)[¶](#tensortrade.oms.wallets.wallet.Wallet.withdraw "Permalink to this definition")

Withdraws funds from the wallet.

| Parameters: | * **quantity** (Quantity) – The amount to withdraw from this wallet.

* **reason** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The reason for withdrawing the amount.

 |

| Returns: | Quantity – The withdrawn amount. |

##### tensortrade.stochastic package[¶](#module-tensortrade.stochastic "Permalink to this headline")

###### Subpackages[¶](#subpackages "Permalink to this headline")

####### tensortrade.stochastic.processes package[¶](#module-tensortrade.stochastic.processes "Permalink to this headline")

######## Submodules[¶](#submodules "Permalink to this headline")

######### tensortrade.stochastic.processes.brownian\_motion module[¶](#module-tensortrade.stochastic.processes.brownian_motion "Permalink to this headline")

`tensortrade.stochastic.processes.brownian_motion.``brownian_motion_levels`(*params: tensortrade.stochastic.utils.parameters.ModelParameters*) → numpy.array[[source]](_modules/tensortrade/stochastic/processes/brownian_motion.html#brownian_motion_levels)[¶](#tensortrade.stochastic.processes.brownian_motion.brownian_motion_levels "Permalink to this definition")

Constructs a price sequence whose returns evolve according to brownian

motion.

| Parameters: | **params** (ModelParameters) – The parameters for the stochastic model. |

| Returns: | np.array – A price sequence which follows brownian motion. |

`tensortrade.stochastic.processes.brownian_motion.``brownian_motion_log_returns`(*params: tensortrade.stochastic.utils.parameters.ModelParameters*) → numpy.array[[source]](_modules/tensortrade/stochastic/processes/brownian_motion.html#brownian_motion_log_returns)[¶](#tensortrade.stochastic.processes.brownian_motion.brownian_motion_log_returns "Permalink to this definition")

Constructs a Wiener process (Brownian Motion).

| Parameters: | **params** (ModelParameters) – The parameters for the stochastic model. |

| Returns: | np.array – Brownian motion log returns. |

References

[1] <http://en.wikipedia.org/wiki/Wiener_process>

######### tensortrade.stochastic.processes.cox module[¶](#module-tensortrade.stochastic.processes.cox "Permalink to this headline")

`tensortrade.stochastic.processes.cox.``cox`(*base\_price: int = 1*, *base\_volume: int = 1*, *start\_date: str = '2010-01-01'*, *start\_date\_format: str = '%Y-%m-%d'*, *times\_to\_generate: int = 1000*, *time\_frame: str = '1h'*, *params: Optional[tensortrade.stochastic.utils.parameters.ModelParameters] = None*) → pandas.core.frame.DataFrame[[source]](_modules/tensortrade/stochastic/processes/cox.html#cox)[¶](#tensortrade.stochastic.processes.cox.cox "Permalink to this definition")

Generates price data from the CIR process.

| Parameters: | * **base\_price** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1*) – The base price to use for price generation.

* **base\_volume** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1*) – The base volume to use for volume generation.

* **start\_date** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *default '2010-01-01'*) – The start date of the generated data

* **start\_date\_format** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *default '%Y-%m-%d'*) – The format for the start date of the generated data.

* **times\_to\_generate** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1000*) – The number of bars to make.

* **time\_frame** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *default '1h'*) – The time frame.

* **params** (ModelParameters, optional) – The model parameters.

 |

| Returns: | pd.DataFrame – The generated data frame containing the OHLCV bars. |

References

[1] <https://en.wikipedia.org/wiki/Cox%E2%80%93Ingersoll%E2%80%93Ross_model>

`tensortrade.stochastic.processes.cox.``cox_ingersoll_ross_levels`(*params: tensortrade.stochastic.utils.parameters.ModelParameters*) → numpy.array[[source]](_modules/tensortrade/stochastic/processes/cox.html#cox_ingersoll_ross_levels)[¶](#tensortrade.stochastic.processes.cox.cox_ingersoll_ross_levels "Permalink to this definition")

Constructs the rate levels of a mean-reverting Cox-Ingersoll-Ross process.

Used to model interest rates as well as stochastic volatility in the Heston

model. We pass a correlated Brownian motion process into the method from

which the interest rate levels are constructed because the returns between

the underlying and the stochastic volatility should be correlated. The other

correlated process is used in the Heston model.

| Parameters: | **params** (ModelParameters) – The parameters for the stochastic model. |

| Returns: | np.array – The interest rate levels for the CIR process. |

######### tensortrade.stochastic.processes.fbm module[¶](#module-tensortrade.stochastic.processes.fbm "Permalink to this headline")

`tensortrade.stochastic.processes.fbm.``fbm`(*base\_price: int = 1*, *base\_volume: int = 1*, *start\_date: str = '2010-01-01'*, *start\_date\_format: str = '%Y-%m-%d'*, *times\_to\_generate: int = 1000*, *hurst: float = 0.61*, *time\_frame: str = '1h'*) → pandas.core.frame.DataFrame[[source]](_modules/tensortrade/stochastic/processes/fbm.html#fbm)[¶](#tensortrade.stochastic.processes.fbm.fbm "Permalink to this definition")

Generates price data from the FBM process.

| Parameters: | * **base\_price** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1*) – The base price to use for price generation.

* **base\_volume** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1*) – The base volume to use for volume generation.

* **start\_date** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *default '2010-01-01'*) – The start date of the generated data

* **start\_date\_format** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *default '%Y-%m-%d'*) – The format for the start date of the generated data.

* **times\_to\_generate** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1000*) – The number of bars to make.

* **hurst** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default 0.61*) – The hurst parameter for the FBM process.

* **time\_frame** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *default '1h'*) – The time frame.

 |

| Returns: | pd.DataFrame – The generated data frame containing the OHLCV bars. |

References

[1] <https://en.wikipedia.org/wiki/Fractional_Brownian_motion>

######### tensortrade.stochastic.processes.gbm module[¶](#module-tensortrade.stochastic.processes.gbm "Permalink to this headline")

`tensortrade.stochastic.processes.gbm.``gbm`(*base\_price: int = 1*, *base\_volume: int = 1*, *start\_date: str = '2010-01-01'*, *start\_date\_format: str = '%Y-%m-%d'*, *times\_to\_generate: int = 1000*, *time\_frame: str = '1h'*, *params: Optional[tensortrade.stochastic.utils.parameters.ModelParameters] = None*) → pandas.core.frame.DataFrame[[source]](_modules/tensortrade/stochastic/processes/gbm.html#gbm)[¶](#tensortrade.stochastic.processes.gbm.gbm "Permalink to this definition")

Generates price data from a GBM process.

| Parameters: | * **base\_price** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1*) – The base price to use for price generation.

* **base\_volume** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1*) – The base volume to use for volume generation.

* **start\_date** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *default '2010-01-01'*) – The start date of the generated data

* **start\_date\_format** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *default '%Y-%m-%d'*) – The format for the start date of the generated data.

* **times\_to\_generate** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1000*) – The number of bars to make.

* **time\_frame** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *default '1h'*) – The time frame.

* **params** (ModelParameters, optional) – The model parameters.

 |

| Returns: | pd.DataFrame – The generated data frame containing the OHLCV bars. |

References

[1] <https://en.wikipedia.org/wiki/Geometric_Brownian_motion>

`tensortrade.stochastic.processes.gbm.``geometric_brownian_motion_levels`(*params: tensortrade.stochastic.utils.parameters.ModelParameters*)[[source]](_modules/tensortrade/stochastic/processes/gbm.html#geometric_brownian_motion_levels)[¶](#tensortrade.stochastic.processes.gbm.geometric_brownian_motion_levels "Permalink to this definition")

Constructs a sequence of price levels for an asset which evolves

according to a geometric brownian motion process.

| Parameters: | **params** ([*ModelParameters*](index.html#tensortrade.stochastic.utils.parameters.ModelParameters "tensortrade.stochastic.utils.parameters.ModelParameters")) – The parameters for the stochastic model. |

| Returns: | np.array – The price levels for the asset |

`tensortrade.stochastic.processes.gbm.``geometric_brownian_motion_log_returns`(*params: tensortrade.stochastic.utils.parameters.ModelParameters*) → numpy.array[[source]](_modules/tensortrade/stochastic/processes/gbm.html#geometric_brownian_motion_log_returns)[¶](#tensortrade.stochastic.processes.gbm.geometric_brownian_motion_log_returns "Permalink to this definition")

Constructs a sequence of log returns.

When log returns are exponentiated, it produces a random Geometric

Brownian Motion (GBM). The GBM is the stochastic process underlying

the Black-Scholes options pricing formula.

| Parameters: | **params** (ModelParameters) – The parameters for the stochastic model. |

| Returns: | np.array – The log returns of a geometric brownian motion process |

######### tensortrade.stochastic.processes.heston module[¶](#module-tensortrade.stochastic.processes.heston "Permalink to this headline")

`tensortrade.stochastic.processes.heston.``cox_ingersoll_ross_heston`(*params: tensortrade.stochastic.utils.parameters.ModelParameters*) → numpy.array[[source]](_modules/tensortrade/stochastic/processes/heston.html#cox_ingersoll_ross_heston)[¶](#tensortrade.stochastic.processes.heston.cox_ingersoll_ross_heston "Permalink to this definition")

Constructs the rate levels of a mean-reverting cox ingersoll ross process.

Used to model interest rates as well as stochastic volatility in the Heston

model. The returns between the underlying and the stochastic volatility

should be correlated we pass a correlated Brownian motion process into the

method from which the interest rate levels are constructed. The other

correlated process are used in the Heston model.

| Parameters: | **params** ([*ModelParameters*](index.html#tensortrade.stochastic.utils.parameters.ModelParameters "tensortrade.stochastic.utils.parameters.ModelParameters")) – The parameters for the stochastic model. |

| Returns: | np.array – The interest rate levels for the CIR process |

`tensortrade.stochastic.processes.heston.``geometric_brownian_motion_jump_diffusion_levels`(*params: tensortrade.stochastic.utils.parameters.ModelParameters*) → numpy.array[[source]](_modules/tensortrade/stochastic/processes/heston.html#geometric_brownian_motion_jump_diffusion_levels)[¶](#tensortrade.stochastic.processes.heston.geometric_brownian_motion_jump_diffusion_levels "Permalink to this definition")

Converts a sequence of gbm jmp returns into a price sequence which

evolves according to a geometric brownian motion but can contain jumps

at any point in time.

| Parameters: | **params** ([*ModelParameters*](index.html#tensortrade.stochastic.utils.parameters.ModelParameters "tensortrade.stochastic.utils.parameters.ModelParameters")) – The parameters for the stochastic model. |

| Returns: | np.array – The price levels. |

`tensortrade.stochastic.processes.heston.``geometric_brownian_motion_jump_diffusion_log_returns`(*params: tensortrade.stochastic.utils.parameters.ModelParameters*) → numpy.array[[source]](_modules/tensortrade/stochastic/processes/heston.html#geometric_brownian_motion_jump_diffusion_log_returns)[¶](#tensortrade.stochastic.processes.heston.geometric_brownian_motion_jump_diffusion_log_returns "Permalink to this definition")

Constructs combines a geometric brownian motion process (log returns)

with a jump diffusion process (log returns) to produce a sequence of gbm

jump returns.

| Parameters: | **params** ([*ModelParameters*](index.html#tensortrade.stochastic.utils.parameters.ModelParameters "tensortrade.stochastic.utils.parameters.ModelParameters")) – The parameters for the stochastic model. |

| Returns: | np.array – A GBM process with jumps in it |

`tensortrade.stochastic.processes.heston.``get_correlated_geometric_brownian_motions`(*params: tensortrade.stochastic.utils.parameters.ModelParameters*, *correlation\_matrix: numpy.array*, *n: int*) → numpy.array[[source]](_modules/tensortrade/stochastic/processes/heston.html#get_correlated_geometric_brownian_motions)[¶](#tensortrade.stochastic.processes.heston.get_correlated_geometric_brownian_motions "Permalink to this definition")

Constructs a basket of correlated asset paths using the Cholesky

decomposition method.

| Parameters: | * **params** (ModelParameters) – The parameters for the stochastic model.

* **correlation\_matrix** (np.array) – An n x n correlation matrix.

* **n** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – Number of assets (number of paths to return)

 |

| Returns: | np.array – n correlated log return geometric brownian motion processes. |

`tensortrade.stochastic.processes.heston.``heston`(*base\_price: int = 1*, *base\_volume: int = 1*, *start\_date: str = '2010-01-01'*, *start\_date\_format: str = '%Y-%m-%d'*, *times\_to\_generate: int = 1000*, *time\_frame: str = '1h'*, *params: Optional[tensortrade.stochastic.utils.parameters.ModelParameters] = None*) → pandas.core.frame.DataFrame[[source]](_modules/tensortrade/stochastic/processes/heston.html#heston)[¶](#tensortrade.stochastic.processes.heston.heston "Permalink to this definition")

Generates price data from the Heston model.

| Parameters: | * **base\_price** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1*) – The base price to use for price generation.

* **base\_volume** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1*) – The base volume to use for volume generation.

* **start\_date** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *default '2010-01-01'*) – The start date of the generated data

* **start\_date\_format** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *default '%Y-%m-%d'*) – The format for the start date of the generated data.

* **times\_to\_generate** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1000*) – The number of bars to make.

* **time\_frame** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *default '1h'*) – The time frame.

* **params** (ModelParameters, optional) – The model parameters.

 |

| Returns: | pd.DataFrame – The generated data frame containing the OHLCV bars. |

`tensortrade.stochastic.processes.heston.``heston_construct_correlated_path`(*params: tensortrade.stochastic.utils.parameters.ModelParameters*, *brownian\_motion\_one: numpy.array*) → numpy.array[[source]](_modules/tensortrade/stochastic/processes/heston.html#heston_construct_correlated_path)[¶](#tensortrade.stochastic.processes.heston.heston_construct_correlated_path "Permalink to this definition")

A simplified version of the Cholesky decomposition method for just two

assets. It does not make use of matrix algebra and is therefore quite easy

to implement.

| Parameters: | * **params** ([*ModelParameters*](index.html#tensortrade.stochastic.utils.parameters.ModelParameters "tensortrade.stochastic.utils.parameters.ModelParameters")) – The parameters for the stochastic model.

* **brownian\_motion\_one** (np.array) – (Not filled)

 |

| Returns: | np.array – A correlated brownian motion path. |

`tensortrade.stochastic.processes.heston.``heston_model_levels`(*params: tensortrade.stochastic.utils.parameters.ModelParameters*) → numpy.array[[source]](_modules/tensortrade/stochastic/processes/heston.html#heston_model_levels)[¶](#tensortrade.stochastic.processes.heston.heston_model_levels "Permalink to this definition")

Generates price levels corresponding to the Heston model.

The Heston model is the geometric brownian motion model with stochastic

volatility. This stochastic volatility is given by the cox ingersoll ross

process. Step one on this method is to construct two correlated GBM

processes. One is used for the underlying asset prices and the other is used

for the stochastic volatility levels.

| Parameters: | **params** ([*ModelParameters*](index.html#tensortrade.stochastic.utils.parameters.ModelParameters "tensortrade.stochastic.utils.parameters.ModelParameters")) – The parameters for the stochastic model. |

| Returns: | np.array – The prices for an underlying following a Heston process |

Warning

This method is dodgy! Need to debug!

`tensortrade.stochastic.processes.heston.``jump_diffusion_process`(*params: tensortrade.stochastic.utils.parameters.ModelParameters*) → numpy.array[[source]](_modules/tensortrade/stochastic/processes/heston.html#jump_diffusion_process)[¶](#tensortrade.stochastic.processes.heston.jump_diffusion_process "Permalink to this definition")

Produces a sequence of Jump Sizes which represent a jump diffusion

process.

These jumps are combined with a geometric brownian motion (log returns)

to produce the Merton model.

| Parameters: | **params** ([*ModelParameters*](index.html#tensortrade.stochastic.utils.parameters.ModelParameters "tensortrade.stochastic.utils.parameters.ModelParameters")) – The parameters for the stochastic model. |

| Returns: | np.array – The jump sizes for each point in time (mostly zeroes if jumps are

infrequent). |

######### tensortrade.stochastic.processes.merton module[¶](#module-tensortrade.stochastic.processes.merton "Permalink to this headline")

`tensortrade.stochastic.processes.merton.``merton`(*base\_price: int = 1*, *base\_volume: int = 1*, *start\_date: str = '2010-01-01'*, *start\_date\_format: str = '%Y-%m-%d'*, *times\_to\_generate: int = 1000*, *time\_frame: str = '1h'*, *params: Optional[tensortrade.stochastic.utils.parameters.ModelParameters] = None*) → pandas.core.frame.DataFrame[[source]](_modules/tensortrade/stochastic/processes/merton.html#merton)[¶](#tensortrade.stochastic.processes.merton.merton "Permalink to this definition")

Generates price data from the Merton Jump Diffusion model.

| Parameters: | * **base\_price** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1*) – The base price to use for price generation.

* **base\_volume** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1*) – The base volume to use for volume generation.

* **start\_date** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *default '2010-01-01'*) – The start date of the generated data

* **start\_date\_format** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *default '%Y-%m-%d'*) – The format for the start date of the generated data.

* **times\_to\_generate** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1000*) – The number of bars to make.

* **time\_frame** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *default '1h'*) – The time frame.

* **params** (ModelParameters, optional) – The model parameters.

 |

| Returns: | pd.DataFrame – The generated data frame containing the OHLCV bars. |

######### tensortrade.stochastic.processes.ornstein\_uhlenbeck module[¶](#module-tensortrade.stochastic.processes.ornstein_uhlenbeck "Permalink to this headline")

`tensortrade.stochastic.processes.ornstein_uhlenbeck.``ornstein`(*base\_price: int = 1*, *base\_volume: int = 1*, *start\_date: str = '2010-01-01'*, *start\_date\_format: str = '%Y-%m-%d'*, *times\_to\_generate: int = 1000*, *time\_frame: str = '1h'*, *params: Optional[tensortrade.stochastic.utils.parameters.ModelParameters] = None*) → pandas.core.frame.DataFrame[[source]](_modules/tensortrade/stochastic/processes/ornstein_uhlenbeck.html#ornstein)[¶](#tensortrade.stochastic.processes.ornstein_uhlenbeck.ornstein "Permalink to this definition")

Generates price data from the OU process.

| Parameters: | * **base\_price** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1*) – The base price to use for price generation.

* **base\_volume** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1*) – The base volume to use for volume generation.

* **start\_date** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *default '2010-01-01'*) – The start date of the generated data

* **start\_date\_format** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *default '%Y-%m-%d'*) – The format for the start date of the generated data.

* **times\_to\_generate** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1000*) – The number of bars to make.

* **time\_frame** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *default '1h'*) – The time frame.

* **params** (ModelParameters, optional) – The model parameters.

 |

| Returns: | pd.DataFrame – The generated data frame containing the OHLCV bars. |

References

[1] <https://en.wikipedia.org/wiki/Ornstein%E2%80%93Uhlenbeck_process>

`tensortrade.stochastic.processes.ornstein_uhlenbeck.``ornstein_uhlenbeck_levels`(*params: tensortrade.stochastic.utils.parameters.ModelParameters*) → numpy.array[[source]](_modules/tensortrade/stochastic/processes/ornstein_uhlenbeck.html#ornstein_uhlenbeck_levels)[¶](#tensortrade.stochastic.processes.ornstein_uhlenbeck.ornstein_uhlenbeck_levels "Permalink to this definition")

Constructs the rate levels of a mean-reverting Ornstein-Uhlenbeck

process.

| Parameters: | **params** ([*ModelParameters*](index.html#tensortrade.stochastic.utils.parameters.ModelParameters "tensortrade.stochastic.utils.parameters.ModelParameters")) – The parameters for the stochastic model. |

| Returns: | np.array – The interest rate levels for the Ornstein Uhlenbeck process |

####### tensortrade.stochastic.utils package[¶](#module-tensortrade.stochastic.utils "Permalink to this headline")

######## Submodules[¶](#submodules "Permalink to this headline")

######### tensortrade.stochastic.utils.helpers module[¶](#module-tensortrade.stochastic.utils.helpers "Permalink to this headline")

`tensortrade.stochastic.utils.helpers.``convert_to_prices`(*param: tensortrade.stochastic.utils.parameters.ModelParameters*, *log\_returns: numpy.array*) → numpy.array[[source]](_modules/tensortrade/stochastic/utils/helpers.html#convert_to_prices)[¶](#tensortrade.stochastic.utils.helpers.convert_to_prices "Permalink to this definition")

Converts a sequence of log returns into normal returns (exponentiation)

and then computes a price sequence given a starting price, param.all\_s0.

| Parameters: | * **param** (ModelParameters) – The model parameters.

* **log\_returns** (np.array) – The log returns.

 |

| Returns: | np.array – The price sequence. |

`tensortrade.stochastic.utils.helpers.``generate`(*price\_fn: Callable[[tensortrade.stochastic.utils.parameters.ModelParameters], numpy.array], base\_price: int = 1, base\_volume: int = 1, start\_date: str = '2010-01-01', start\_date\_format: str = '%Y-%m-%d', times\_to\_generate: int = 1000, time\_frame: str = '1h', params: tensortrade.stochastic.utils.parameters.ModelParameters = None*) → pandas.core.frame.DataFrame[[source]](_modules/tensortrade/stochastic/utils/helpers.html#generate)[¶](#tensortrade.stochastic.utils.helpers.generate "Permalink to this definition")

Generates a data frame of OHLCV data based on the price model specified.

| Parameters: | * **price\_fn** (Callable[[ModelParameters], np.array]) – The price function generate the prices based on the chosen model.

* **base\_price** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1*) – The base price to use for price generation.

* **base\_volume** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1*) – The base volume to use for volume generation.

* **start\_date** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *default '2010-01-01'*) – The start date of the generated data

* **start\_date\_format** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *default '%Y-%m-%d'*) – The format for the start date of the generated data.

* **times\_to\_generate** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")*,* *default 1000*) – The number of bars to make.

* **time\_frame** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")*,* *default '1h'*) – The time frame.

* **params** (ModelParameters, optional) – The model parameters.

 |

| Returns: | pd.DataFrame – The data frame containing the OHLCV bars. |

`tensortrade.stochastic.utils.helpers.``get_delta`(*time\_frame: str*) → float[[source]](_modules/tensortrade/stochastic/utils/helpers.html#get_delta)[¶](#tensortrade.stochastic.utils.helpers.get_delta "Permalink to this definition")

Gets the time delta for a given time frame.

| Parameters: | **time\_frame** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The time frame for generating.

(e.g. 1h, 1min, 1w, 1d) |

| Returns: | *float* – The time delta for the given time frame. |

`tensortrade.stochastic.utils.helpers.``scale_times_to_generate`(*times\_to\_generate: int*, *time\_frame: str*) → int[[source]](_modules/tensortrade/stochastic/utils/helpers.html#scale_times_to_generate)[¶](#tensortrade.stochastic.utils.helpers.scale_times_to_generate "Permalink to this definition")

Adjusts the number of times to generate the prices based on a time frame.

| Parameters: | * **times\_to\_generate** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The number of time to generate prices.

* **time\_frame** ([*str*](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)")) – The time frame for generating.

(e.g. 1h, 1min, 1w, 1d)

 |

| Returns: | *int* – The adjusted number of times to generate. |

| Raises: | [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.9)") – Raised if the time\_frame provided does not match the correct format. |

######### tensortrade.stochastic.utils.parameters module[¶](#module-tensortrade.stochastic.utils.parameters "Permalink to this headline")

*class* `tensortrade.stochastic.utils.parameters.``ModelParameters`(*all\_s0: float*, *all\_time: int*, *all\_delta: float*, *all\_sigma: float*, *gbm\_mu: float*, *jumps\_lambda: float = 0.0*, *jumps\_sigma: float = 0.0*, *jumps\_mu: float = 0.0*, *cir\_a: float = 0.0*, *cir\_mu: float = 0.0*, *all\_r0: float = 0.0*, *cir\_rho: float = 0.0*, *ou\_a: float = 0.0*, *ou\_mu: float = 0.0*, *heston\_a: float = 0.0*, *heston\_mu: float = 0.0*, *heston\_vol0: float = 0.0*)[[source]](_modules/tensortrade/stochastic/utils/parameters.html#ModelParameters)[¶](#tensortrade.stochastic.utils.parameters.ModelParameters "Permalink to this definition")

Bases: [`object`](https://docs.python.org/3/library/functions.html#object "(in Python v3.9)")

Defines the model parameters of different stock price models.

| Parameters: | * **all\_s0** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The initial asset value.

* **all\_time** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The amount of time to simulate for.

* **all\_delta** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The rate of time.

(e.g. 1/252 = daily, 1/12 = monthly)

* **all\_sigma** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The volatility of the stochastic processes.

* **gbm\_mu** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The annual drift factor for geometric brownian motion.

* **jumps\_lambda** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default 0.0*) – The probability of a jump happening at each point in time.

* **jumps\_sigma** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default 0.0*) – The volatility of the jump size.

* **jumps\_mu** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default 0.0*) – The average jump size.

* **cir\_a** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default 0.0*) – The rate of mean reversion for Cox Ingersoll Ross.

* **cir\_mu** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default 0.0*) – The long run average interest rate for Cox Ingersoll Ross.

* **all\_r0** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default 0.0*) – The starting interest rate value.

* **cir\_rho** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default 0.0*) – The correlation between the wiener processes of the Heston model.

* **ou\_a** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default 0.0*) – The rate of mean reversion for Ornstein Uhlenbeck.

* **ou\_mu** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default 0.0*) – The long run average interest rate for Ornstein Uhlenbeck.

* **heston\_a** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default 0.0*) – The rate of mean reversion for volatility in the Heston model.

* **heston\_mu** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default 0.0*) – The long run average volatility for the Heston model.

* **heston\_vol0** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")*,* *default 0.0*) – The starting volatility value for the Heston model.

 |

`tensortrade.stochastic.utils.parameters.``default`(*base\_price: float*, *t\_gen: int*, *delta: float*) → tensortrade.stochastic.utils.parameters.ModelParameters[[source]](_modules/tensortrade/stochastic/utils/parameters.html#default)[¶](#tensortrade.stochastic.utils.parameters.default "Permalink to this definition")

Creates a basic model parameter set with key parameters specified default

parameters.

| Parameters: | * **base\_price** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The base price to use for price generation.

* **t\_gen** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The number of bars to generate.

* **delta** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The time delta to use.

 |

| Returns: | ModelParameters – The default model parameters to use. |

`tensortrade.stochastic.utils.parameters.``random`(*base\_price: float*, *t\_gen: int*, *delta: float*) → tensortrade.stochastic.utils.parameters.ModelParameters[[source]](_modules/tensortrade/stochastic/utils/parameters.html#random)[¶](#tensortrade.stochastic.utils.parameters.random "Permalink to this definition")

Creates a random model parameter set with key parameters specified

default parameters.

| Parameters: | * **base\_price** ([*float*](https://docs.python.org/3/library/functions.html#float "(in Python v3.9)")) – The base price to use for price generation.

* **t\_gen** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The number of bars to generate.

* **delta** ([*int*](https://docs.python.org/3/library/functions.html#int "(in Python v3.9)")) – The time delta to use.

 |

| Returns: | ModelParameters – The random model parameters to use. |

#### Submodules[¶](#submodules "Permalink to this headline")

##### tensortrade.version module[¶](#module-tensortrade.version "Permalink to this headline")

