예제 #1
0
def create_env(config, train="train"):
    cdd = CryptoDataDownload()
    data = cdd.fetch("Bitstamp", "USD", "BTC", "1h")
    if False:
        data.close = data.close / 20 + range(len(data))
        print("genenrating fake increase")
    if train == "train":
        data = data[0:int(len(data) / 2)]  # training
        print("using first half for training")
    elif train == "eval":
        data = data[int(len(data) / 2):]  # validation
        print("using second half for eval")
    else:
        print("using all data")

    pclose = Stream.source(list(data.close), dtype="float").rename("USD-BTC")
    pmin = Stream.source(list(data.low), dtype="float").rename("USD-BTClow")
    pmax = Stream.source(list(data.high), dtype="float").rename("USD-BTChigh")

    pmin = Stream.source(list(data.low), dtype="float").rename("USD-BTClow")
    pmax = Stream.source(list(data.high), dtype="float").rename("USD-BTChigh")

    pmin3 = pmin.rolling(window=3).min()
    pmin10 = pmin.rolling(window=10).min()
    pmin20 = pmin.rolling(window=20).min()
    pmax3 = pmax.rolling(window=3).max()
    pmax10 = pmax.rolling(window=10).max()
    pmax20 = pmax.rolling(window=20).max()

    eo = ExchangeOptions(commission=0.002)  #
    coinbase = Exchange("coinbase", service=execute_order, options=eo)(
        pclose
    )

    cash = Wallet(coinbase, 100000 * USD)
    asset = Wallet(coinbase, 0 * BTC)

    portfolio = Portfolio(USD, [
        cash,
        asset
    ])

    feed = DataFeed([

        (pclose.log() - pmin3.log()).fillna(0).rename("relmin3"),
        (pclose.log() - pmin10.log()).fillna(0).rename("relmin10"),
        (pclose.log() - pmin20.log()).fillna(0).rename("relmin20"),
        (pclose.log() - pmax3.log()).fillna(0).rename("relmax3"),
        (pclose.log() - pmax10.log()).fillna(0).rename("relmax10"),
        (pclose.log() - pmax20.log()).fillna(0).rename("relmax20"),

    ])

    action_scheme = BSH(cash=cash, asset=asset)

    renderer_feed = DataFeed([
        Stream.source(list(data.close), dtype="float").rename("price"),
        Stream.sensor(action_scheme, lambda s: s.action, dtype="float").rename("action")  # only works for BSH
    ])

    environment = default.create(

        feed=feed,
        portfolio=portfolio,
        action_scheme=action_scheme,
        reward_scheme="simple",
        renderer_feed=renderer_feed,
        renderer=PositionChangeChart(),
        window_size=config["window_size"],
        min_periods=20,
        max_allowed_loss=0.6
    )
    return environment
예제 #2
0
# %%
import sys
sys.path.append("/Users/fodrh1201/Workspace/tensortrade")
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

# %%
cdd = CryptoDataDownload()

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


# %%
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,
예제 #3
0
sys.path.insert(0, os.path.abspath("../../tensortrade"))

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

DOWNLOAD = False

if DOWNLOAD:
    cdd = CryptoDataDownload()
    bitstamp_btc = cdd.fetch("Bitstamp", "USD", "BTC", "1h")
    bitstamp_eth = cdd.fetch("Bitstamp", "USD", "ETH", "1h")
    bitstamp_ltc = cdd.fetch("Bitstamp", "USD", "LTC", "1h")

    bitstamp_btc.to_csv("data/bitstamp_btc_hourly.csv")
    bitstamp_eth.to_csv("data/bitstamp_eth_hourly.csv")
    bitstamp_ltc.to_csv("data/bitstamp_ltc_hourly.csv")

bitstamp_btc = pandas.read_csv("data/bitstamp_btc_hourly.csv")
bitstamp_eth = pandas.read_csv("data/bitstamp_eth_hourly.csv")
bitstamp_ltc = pandas.read_csv("data/bitstamp_ltc_hourly.csv")

# Inspec transactions of Simple orders

bitstamp = Exchange("bitstamp",
예제 #4
0
def create_recent_coinbase_env(config):
    cdd = CryptoDataDownload()
    data = cdd.fetch("gemini", "USD", "BTC", "1h")
    return create_env(data, config)
import ta
import pandas as pd
from tensortrade.data.cdd import CryptoDataDownload
from tensortrade.feed.core import Stream, DataFeed, NameSpace


cdd = CryptoDataDownload()


def rsi(price: Stream[float], period: float) -> Stream[float]:
    """
    Relative strength index
    The relative strength index (RSI) is a momentum indicator used in technical analysis that measures the
    magnitude of recent price changes to evaluate overbought or oversold conditions in the price of a stock or
    other asset
    :param price:
    :param period:
    :return:
    """
    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]:
    """
    Moving Average Convergence Divergence
    This technical indicator is a tool that’s used to identify moving averages that are indicating a new trend,
    whether it’s bullish or bearish.
예제 #6
0
    def create_env(config):

        cdd = CryptoDataDownload()
        # Head for beginning of data
        # Tail for end of data
        if config["train"] == True:
            df = cdd.fetch("Bitfinex", "USD", "BTC", "d")[-600:-100]
        else: #for testing
            df = cdd.fetch("Bitfinex", "USD", "BTC", "d")[-100:]
        price_history = df[['date', 'open', 'high', 'low', 'close', 'volume']]  # chart data

        # OBSERVER
        p =  Stream.source(price_history['close'].tolist(), dtype="float").rename("USD-BTC")

        bitfinex = Exchange("bitfinex", service=execute_order)(
            p
        )

        # ORDER MANAGEMENT SYSTEM
        #start with 100.000 usd and 0 assets
        cash = Wallet(bitfinex, 100000 * USD)
        asset = Wallet(bitfinex, 0 * BTC)

        portfolio = Portfolio(USD, [
            cash,
            asset
        ])

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

        with NameSpace("bitfinex"):
            streams = [Stream.source(df[c].tolist(), dtype="float").rename(c) for c in df.columns]

        feed = DataFeed(streams)

        # REWARDSCHEME
        #use PBR as reward_scheme
        #'SimpleProfit' object has no attribute 'on_action'
        reward_scheme = PBR(price=p) #SimpleProfit()#RiskAdjustedReturns()

        # ACTIONSCHEME
        #use BSH as action_scheme
        action_scheme = BSH(#ManagedRiskOrders()
            cash=cash,
            asset=asset
        ).attach(reward_scheme) 

        # RENDERER
        renderer_feed = DataFeed(
            [Stream.source(price_history[c].tolist(), dtype="float").rename(c) for c in price_history]
        )

        #create the environment
        environment = default.create(
            feed=feed,
            portfolio=portfolio,
            action_scheme=action_scheme,
            reward_scheme=reward_scheme,
            renderer_feed=renderer_feed,
            renderer= PlotlyTradingChart(), #PositionChangeChart(), #
            window_size=config["window_size"], #part of OBSERVER
            max_allowed_loss=config["max_allowed_loss"] #STOPPER
        )
        return environment