Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# 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 typing import List, Union, Callable
from tensortrade import Component
from .feature_transformer import FeatureTransformer
class FeaturePipeline(Component):
"""An pipeline for transforming observation data frames into features for learning."""
registered_name = "features"
def __init__(self, steps: List[FeatureTransformer], **kwargs):
"""
Arguments:
dtype: The `dtype` elements in the pipeline should be cast to.
"""
self._steps = steps
self._dtype: Union[type, str] = self.default('dtype', np.float32, kwargs)
@property
def steps(self) -> List[FeatureTransformer]:
"""A list of feature transformations to apply to observations."""
return self._steps
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# 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
from abc import abstractmethod
from tensortrade import Component
class RewardScheme(Component):
registered_name = "rewards"
def reset(self):
"""Optionally implementable method for resetting stateful schemes."""
pass
@abstractmethod
def get_reward(self, portfolio: 'Portfolio', current_step: int) -> float:
"""
Arguments:
portfolio: The portfolio being used by the environment.
current_step: The environments's current timestep.
Returns:
A float corresponding to the benefit earned by the action taken this timestep.
import pandas as pd
import numpy as np
from abc import abstractmethod
from typing import Dict, Union, List
from gym.spaces import Box
from tensortrade import Component
from tensortrade.trades import Trade
from tensortrade.features import FeaturePipeline
from tensortrade.account import Portfolio
TypeString = Union[type, str]
class Exchange(Component):
"""An abstract exchange for use within a trading environments.
Arguments:
base_instrument: The exchange symbol of the instrument to store/measure value in.
dtype: A type or str corresponding to the dtype of the `observation_space`.
feature_pipeline: A pipeline of feature transformations for transforming observations.
"""
registered_name = "exchanges"
def __init__(self, dtype: TypeString = np.float32, feature_pipeline: FeaturePipeline = None, portfolio: Portfolio = None, **kwargs):
self._dtype = self.default('dtype', dtype)
self._feature_pipeline = self.default('feature_pipeline', feature_pipeline)
self._window_size = self.default('window_size', 1, kwargs)
self._min_trade_amount = self.default('min_trade_amount', 1e-6, kwargs)
self._max_trade_amount = self.default('max_trade_amount', 1e6, kwargs)
self._min_trade_price = self.default('min_trade_price', 1e-8, kwargs)
import pandas as pd
from typing import Union, List, Dict
from tensortrade import Component
class Portfolio(Component):
"""A account of wallets for use on an Exchange."""
registered_name = "account"
def __init__(self):
self._base_instrument = self.context.base_instrument
self._wallets = {}
@property
def base_instrument(self) -> 'Instrument':
"""The exchange instrument used to measure value and performance statistics."""
return self._base_instrument
@base_instrument.setter
def base_instrument(self, base_instrument: 'Instrument'):
self._base_instrument = base_instrument
# 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 numpy as np
from abc import abstractmethod, ABCMeta
from typing import Union, List
from itertools import product
from gym.spaces import Discrete
from tensortrade import Component
from tensortrade.orders import Order
class ActionScheme(Component, metaclass=ABCMeta):
"""A discrete action scheme for determining the action to take at each timestep within a trading environments."""
registered_name = "actions"
def __init__(self):
pass
@property
@abstractmethod
def action_space(self) -> Discrete:
"""The discrete action space produced by the action scheme."""
raise NotImplementedError()
def reset(self):
"""An optional reset method, which will be called each time the environment is reset."""
pass
import pandas as pd
import numpy as np
from typing import Callable, Tuple, Union, List, Dict, NewType
from tensortrade import Component, TimedIdentifiable
from tensortrade.instruments import Instrument, Quantity, TradingPair
from .wallet import Wallet
WalletType = Union['Wallet', Tuple['Exchange', Instrument, float]]
class Portfolio(Component, TimedIdentifiable):
"""A portfolio of wallets on exchanges."""
registered_name = "portfolio"
def __init__(self,
base_instrument: Instrument,
wallets: List[WalletType] = None,
order_listener: 'OrderListener' = None,
performance_listener: Callable[[pd.DataFrame], None] = None):
wallets = wallets or []
self._base_instrument = self.default('base_instrument', base_instrument)
self._order_listener = self.default('order_listener', order_listener)
self._performance_listener = self.default('performance_listener', performance_listener)
self._wallets = {}
# 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 copy import copy
from typing import List, Union
from abc import ABCMeta, abstractmethod
from tensortrade import Component
class FeatureTransformer(Component, metaclass=ABCMeta):
"""An abstract feature transformer for use within feature pipelines."""
registered_name = "features"
def __init__(self, columns: Union[List[str], str, None] = None, inplace: bool = True, **kwargs):
"""
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.
"""
self.columns = self.default('columns', columns)
self._inplace = self.default('inplace', inplace)
@property
def columns(self) -> List[str]:
return self._columns
import pandas as pd
from typing import Callable, Tuple, Union, List, Dict
from tensortrade import Component
from tensortrade.instruments import Instrument, Quantity, TradingPair
from .wallet import Wallet
class Portfolio(Component):
"""A portfolio of wallets on exchanges."""
registered_name = "portfolio"
def __init__(self,
base_instrument: Instrument,
wallets: List['Wallet'] = [],
wallet_tuples: List[Tuple['Exchange', Instrument, float]] = []):
self._base_instrument = self.default('base_instrument', base_instrument)
self._wallets = {}
for wallet in wallets:
self.add(wallet)
for wallet_tuple in wallet_tuples:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# 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.
from abc import abstractmethod
from tensortrade import Component
from tensortrade.trades import Trade
class SlippageModel(Component):
"""A model for simulating slippage on an exchange trade."""
registered_name = "slippage"
def __init__(self):
pass
@abstractmethod
def adjust_trade(self, trade: Trade, **kwargs) -> Trade:
"""Simulate slippage on a trade ordered on a specific exchange.
Arguments:
trade: The trade executed on the exchange.
**kwargs: Any other arguments necessary for the model.
Returns: