How to use the tensortrade.features.feature_transformer.FeatureTransformer function in tensortrade

To help you get started, we’ve selected a few tensortrade examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github notadamking / tensortrade / tests / tensortrade / features / test_injection.py View on Github external
import pandas as pd

from gym import Space
from typing import List
from itertools import repeat


from tensortrade import TradingContext
from tensortrade.features.feature_transformer import FeatureTransformer
from tensortrade.features.feature_pipeline import FeaturePipeline


class Identity(FeatureTransformer):
    def transform(self, X: pd.DataFrame) -> pd.DataFrame:
        return X


def test_injects_feature_transformation_with_context():

    config = {
        'features': {
            'shape': (90, 70)
        }
    }

    with TradingContext(**config):

        transformer = Identity()
github notadamking / tensortrade / tensortrade / features / scalers / percent_change_normalizer.py View on Github external
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License

import pandas as pd
import numpy as np

from gym import Space
from copy import copy
from typing import Union, List, Tuple, Dict

from tensortrade.features.feature_transformer import FeatureTransformer


class PercentChangeNormalizer(FeatureTransformer):
    """
    A transformer for normalizing values within a feature pipeline by the percent change of the previous value.
    This would be used in cases where you want to generalize away from values where specific values have a meaning.
    For example, if you are thinking about this on the close price, it has an advantage and a disadvantage:
        - advantage: the price jump from 100 to 101 will be normalized the same as the price jump from 101 to 102.1
        - disadvantage: the system will have a harder time with action dependent on specific values, like the price
                        is constantly attracted to 100.
    """

    def __init__(self,
                 columns: Union[List[str], str, None] = None,
                 feature_min: float = 0,
                 feature_max: float = 1,
                 inplace: bool = True):
        """
        Arguments:
github notadamking / tensortrade / tensortrade / features / scalers / min_max_normalizer.py View on Github external
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License

import random
import pandas as pd
import numpy as np

from gym import Space
from copy import copy
from typing import Union, List, Tuple, Dict

from tensortrade.features.feature_transformer import FeatureTransformer


class MinMaxNormalizer(FeatureTransformer):
    """A transformer for normalizing values within a feature pipeline by the column-wise extrema."""

    def __init__(self,
                 columns: Union[List[str], str, None] = None,
                 feature_min: float = 0,
                 feature_max: float = 1,
                 inplace: bool = True):
        """
        Arguments:
            columns (optional): A list of column names to normalize.
            feature_min (optional): The minimum `float` in the range to scale to. Defaults to 0.
            feature_max (optional): The maximum `float` in the range to scale to. Defaults to 1.
            inplace (optional): If `False`, a new column will be added to the output for each input column.
        """
        super().__init__(columns=columns, inplace=inplace)
github notadamking / tensortrade / tensortrade / features / scalers / standard_normalizer.py View on Github external
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License

import pandas as pd
import numpy as np

from gym import Space
from copy import copy
from typing import Union, List, Tuple

from tensortrade.features.feature_transformer import FeatureTransformer


class StandardNormalizer(FeatureTransformer):
    """A transformer for normalizing values within a feature pipeline by removing the mean and scaling to unit variance."""

    def __init__(self, columns: Union[List[str], str, None] = None, inplace=True):
        """
        Arguments:
            columns (optional): A list of column names to normalize.
            inplace (optional): If `False`, a new column will be added to the output for each input column.
        """
        super().__init__(columns=columns, inplace=inplace)

        self._history = {}

    def reset(self):
        self._history = {}

    def transform(self, X: pd.DataFrame) -> pd.DataFrame:
github notadamking / tensortrade / tensortrade / features / indicators / ta_indicator.py View on Github external
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import ta
import numpy as np
import pandas as pd

from abc import abstractmethod
from typing import Union, List, Callable

from tensortrade.features.feature_transformer import FeatureTransformer


class TAIndicator(FeatureTransformer):
    """Adds one or more TA indicators to a data frame, based on existing open, high, low, close, and 'volume from'
     column values.."""

    def __init__(self,
                 indicators: Union[List[str], str, None] = None,
                 lows: Union[List[float], List[int]] = None,
                 highs: Union[List[float], List[int]] = None):

        if isinstance(indicators, str):
            indicators = [indicators]

        self._indicator_names = [x.lower() for x in indicators]
        self._indicators = [getattr(ta, indicator_name) for indicator_name in self._indicator_names]
        self._lows = lows or np.zeros(len(indicators))
        self._highs = highs or np.ones(len(indicators))
github notadamking / tensortrade / tensortrade / features / scalers / comparison_normalizer.py View on Github external
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License

import pandas as pd
import numpy as np

from gym import Space
from copy import copy
from typing import Union, List, Tuple, Dict

from tensortrade.features.feature_transformer import FeatureTransformer


class ComparisonNormalizer(FeatureTransformer):
    """
    A transformer for normalizing values within a feature pipeline using a comparison column.
    This is useful for normalizing values against a base column, for example technical analysis indicators
    such as moving averages or bollinger bands against the close price. Can also be used with open, high, low, close.
    This normalizer converts by default to a scale of [0,1]. A value equal to the comparison column will receive a value of 0.5.
    Value above the comparison column will be in the range 0.5-1 and values below will be in the range 0-0.5.
    Items which are more than 100% of the comparison column will be clipped to 1 and items which are of opposite sign (negative) will be clipped to 0.
    """

    def __init__(self,
                 columns: Union[List[str], str, None] = None,
                 comparison_column: str = 'close',
                 feature_min: float = 0,
                 feature_max: float = 1,
                 inplace: bool = True):
        """
github notadamking / tensortrade / tensortrade / features / stationarity / fractional_difference.py View on Github external
# limitations under the License
#
# Reference Source: Marcos Lopez De Prado - Advances in Financial Machine Learning
#                   Chapter 5 (Pg. 82) - Fractionally Differentiated Features

import pandas as pd
import numpy as np

from gym import Space
from copy import copy
from typing import Union, List, Tuple

from tensortrade.features.feature_transformer import FeatureTransformer


class FractionalDifference(FeatureTransformer):
    """A transformer for differencing values within a feature pipeline by a fractional order."""

    def __init__(self,
                 columns: Union[List[str], str, None] = None,
                 difference_order: float = 0.5,
                 difference_threshold: float = 0.1,
                 inplace: bool = True):
        """
        Arguments:
            columns (optional): A list of column names to difference.
            difference_order (optional): The fractional difference order. Defaults to 0.5.
            difference_threshold (optional): The fractional difference threshold. Defaults to 0.1.
            inplace (optional): If `False`, a new column will be added to the output for each input column.
        """
        super().__init__(columns=columns, inplace=inplace)
github notadamking / tensortrade / tensortrade / features / indicators / simple_moving_average.py View on Github external
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License

import pandas as pd
import numpy as np

from gym import Space
from copy import copy
from typing import Union, List, Tuple, Dict

from tensortrade.features.feature_transformer import FeatureTransformer


class SimpleMovingAverage(FeatureTransformer):
    """A transformer to add the simple moving average of a column to a feature pipeline."""

    def __init__(self, columns: Union[List[str], str, None] = None, window_size: int = 20, inplace: bool = True, **kwargs):
        """
        Arguments:
            columns (optional): A list of column names to normalize.
            window_size (optional): The length of the moving average window. Defaults to 20.
            inplace (optional): If `False`, a new column will be added to the output for each input column.
        """
        super().__init__(columns=columns, inplace=inplace)

        self._window_size = window_size

    def transform(self, X: pd.DataFrame, input_space: Space) -> pd.DataFrame:
        if self.columns is None:
            self.columns = list(X.columns)