<jupyter_start><jupyter_text>Install TensorTrade<jupyter_code>!python3 -m pip install -e .. -U
# Load the TensorBoard notebook extension
%load_ext tensorboard<jupyter_output><empty_output><jupyter_text>Setup Data Fetching<jupyter_code>import ssl
import pandas as pd

ssl._create_default_https_context = ssl._create_unverified_context # Only used if pandas gives a SSLError

def fetch(exchange_name, symbol, timeframe):
    url = "https://www.cryptodatadownload.com/cdd/"
    filename = "{}_{}USD_{}.csv".format(exchange_name, symbol, timeframe)
    volume_column = "Volume {}".format(symbol)
    new_volume_column = "Volume_{}".format(symbol)
    
    df = pd.read_csv(url + filename, skiprows=1)
    df = df[::-1]
    df = df.drop(["Symbol"], axis=1)
    df = df.rename({"Volume USD": "volume", volume_column: new_volume_column}, axis=1)
    df = df.set_index("Date")
    df.columns = [symbol + ":" + name.lower() for name in df.columns]
                     
    return df<jupyter_output><empty_output><jupyter_text>Setup Trading Environment<jupyter_code>from tensortrade.exchanges import Exchange
from tensortrade.exchanges.services.execution.simulated import execute_order
from tensortrade.data import Stream, DataFeed, Module
from tensortrade.instruments import USD, BTC, ETH, LTC
from tensortrade.wallets import Wallet, Portfolio
from tensortrade.environments import TradingEnvironment

coinbase_data = pd.concat([
    fetch("Coinbase", "BTC", "1h"),
    fetch("Coinbase", "ETH", "1h")
], axis=1)

coinbase = Exchange("coinbase", service=execute_order)(
    Stream("USD-BTC", list(coinbase_data['BTC:close'])),
    Stream("USD-ETH", list(coinbase_data['ETH:close']))
)

coinbase_btc = coinbase_data.loc[:, [name.startswith("BTC") for name in coinbase_data.columns]]

with Module("coinbase") as coinbase_ns:
    nodes = [Stream(name, list(coinbase_data[name])) for name in coinbase_data.columns]

feed = DataFeed([coinbase_ns])

portfolio = Portfolio(USD, [
    Wallet(coinbase, 10000 * USD),
    Wallet(coinbase, 10 * BTC),
    Wallet(coinbase, 5 * ETH),
])

env = TradingEnvironment(
    feed=feed,
    portfolio=portfolio,
    action_scheme='managed-risk',
    reward_scheme='risk-adjusted',
    window_size=20,
    disable_tensorflow_logger=False
)<jupyter_output>/usr/local/lib/python3.6/dist-packages/gym/logger.py:30: UserWarning:

[33mWARN: Box bound precision lowered by casting to float32[0m<jupyter_text>Example Data Feed Observation<jupyter_code>env.feed.next()<jupyter_output><empty_output><jupyter_text>Setup and Train DQN Agent<jupyter_code>%tensorboard --logdir agents --host 192.168.1.220 --port 8008
from tensortrade.agents import DQNAgent

agent = DQNAgent(env)

agent.train(n_steps=200, save_every=200, save_path="agents/", log_path="logs/")<jupyter_output>====      AGENT ID: 7c6db2fd-2f57-49ea-823d-b49940d19a3f      ====<jupyter_text>Plot Performance<jupyter_code>%matplotlib inline

portfolio.performance.plot()
portfolio.performance.net_worth.plot()<jupyter_output><empty_output><jupyter_text>Setup and Train A2C Agent<jupyter_code>from tensortrade.agents import A2CAgent

agent = A2CAgent(env)

agent.train(n_steps=200, save_path="agents/")
portfolio.performance.plot()
portfolio.performance.net_worth.plot()<jupyter_output><empty_output><jupyter_text>Setup and Train Parallel DQN Agent<jupyter_code>from tensortrade.agents import ParallelDQNAgent

def create_env():
    feed = DataFeed([coinbase_ns])

    portfolio = Portfolio(USD, [
        Wallet(coinbase, 10000 * USD),
        Wallet(coinbase, 10 * BTC),
        Wallet(coinbase, 5 * ETH),
    ])
    
    env = TradingEnvironment(
        feed=feed,
        portfolio=portfolio,
        action_scheme='managed-risk',
        reward_scheme='risk-adjusted',
        window_size=20
    )
    
    return env

agent = ParallelDQNAgent(create_env)

agent.train(n_envs=4, n_steps=200, save_path="examples/agents/")<jupyter_output>====      EPISODE ID (0/2147483647): 0a15a273-c1e9-4f8e-9a50-6ea95795b484      ====
====      EPISODE ID (0/2147483647): d311dbdc-33d7-4704-b394-9468481e8c68      ====
====      EPISODE ID (0/2147483647): 9bca0f01-925f-4e73-86eb-c91ba8f9d20c      ====
====      EPISODE ID (0/2147483647): 3d12e8dd-674e-45c9-9009-59ab235342af      ====
{'fraction_non_alphanumeric': 0.13061896916921628, 'fraction_numerical': 0.0506001412096964, 'mean_word_length': 4.886426592797784, 'pattern_counts': {'":': 2, '<': 30, '<?xml version=': 0, '>': 30, 'https://': 1, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 1, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '553458', 'license': 'Apache-2.0', 'n_tokens_mistral': 1672, 'n_tokens_neox': 1514, 'n_words': 266, 'path': 'examples/train_and_evaluate.ipynb', 'repo_name': 'owodunni/tensortrade', 'size': '4249'}