Ejemplo n.º 1
0
    def test_run_examples(self):
        folder = join('..', '..', '..', 'catalyst', 'examples')
        files = [f for f in listdir(folder) if isfile(join(folder, f))]

        algo_list = []
        for filename in files:
            name = os.path.basename(filename)
            if filter_algos and name not in filter_algos:
                continue

            module_name = 'catalyst.examples.{}'.format(
                name.replace('.py', '')
            )
            algo_list.append(module_name)

        for module_name in algo_list:
            algo = importlib.import_module(module_name)
            namespace = module_name.replace('.', '_')

            log_catcher = TestHandler()
            with log_catcher:
                run_algorithm(
                    capital_base=0.1,
                    data_frequency='minute',
                    initialize=algo.initialize,
                    handle_data=algo.handle_data,
                    analyze=TestSuiteAlgo.analyze,
                    exchange_name='poloniex',
                    algo_namespace='test_{}'.format(namespace),
                    base_currency='eth',
                    start=pd.to_datetime('2017-10-01', utc=True),
                    end=pd.to_datetime('2017-10-02', utc=True),
                    # output=out
                )
                warnings = [record for record in log_catcher.records if
                            record.level == WARNING]

                if len(warnings) > 0:
                    print('WARNINGS:\n{}'.format(warnings))
            pass
Ejemplo n.º 2
0
def run_example(example_name, environ):
    """
    Run an example module from catalyst.examples.
    """
    mod = EXAMPLE_MODULES[example_name]

    register_calendar("YAHOO", get_calendar("NYSE"), force=True)

    return run_algorithm(
        initialize=getattr(mod, 'initialize', None),
        handle_data=getattr(mod, 'handle_data', None),
        before_trading_start=getattr(mod, 'before_trading_start', None),
        analyze=getattr(mod, 'analyze', None),
        bundle='test',
        environ=environ,
        # Provide a default capital base, but allow the test to override.
        **merge({'capital_base': 1e7}, mod._test_args())
    )
Ejemplo n.º 3
0
    To see which assets are available on each exchange, visit:
    https://www.enigma.co/catalyst/status
'''
from catalyst import run_algorithm
from catalyst.api import order, record, symbol
import pandas as pd


def initialize(context):
    context.asset = symbol('btc_usdt')


def handle_data(context, data):
    order(context.asset, 1)
    record(btc=data.current(context.asset, 'price'))


if __name__ == '__main__':
    run_algorithm(
        capital_base=10000,
        data_frequency='daily',
        initialize=initialize,
        handle_data=handle_data,
        exchange_name='poloniex',
        algo_namespace='buy_btc_simple',
        base_currency='usdt',
        start=pd.to_datetime('2015-03-01', utc=True),
        end=pd.to_datetime('2017-10-31', utc=True),
    )
Ejemplo n.º 4
0
    # context.telegram_bot.initialize(TELEGRAM_TOKEN, context)


if __name__ == '__main__':
    # Parameters:
    parameters = SimulationParameters()
    start_date = pd.to_datetime(parameters.START_DATE, utc=True)
    end_date = pd.to_datetime(parameters.END_DATE, utc=True)

    if parameters.MODE == 'backtest':
        results = run_algorithm(capital_base=parameters.CAPITAL_BASE,
                                data_frequency=parameters.DATA_FREQUECY,
                                initialize=initialize,
                                handle_data=default_handle_data,
                                analyze=default_analyze,
                                exchange_name=parameters.EXCHANGE_NAME,
                                algo_namespace=parameters.ALGO_NAMESPACE,
                                quote_currency=parameters.QUOTE_CURRENCY,
                                start=start_date,
                                end=end_date,
                                live=False,
                                live_graph=False)

        returns_daily = results
        results.to_csv('{}'.format(parameters.ALGO_NAMESPACE_RESULTS_TABLE))

        # returns_daily = returns_minutely.add(1).groupby(
        #   pd.TimeGrouper('24H')).prod().add(-1)

        # FIXME: pyfolio integration
        # pf_data = pyfolio.utils.extract_rets_pos_txn_from_zipline(results)
        # pf_data = pyfolio.utils.extract_rets_pos_txn_from_zipline(
Ejemplo n.º 5
0
        frequency='5T',
    )
    print(df)
    print(data.current(context.asset1, 'close'))
    print(data.current(context.asset2, 'close'))
    exit(0)


if __name__ == '__main__':
    LIVE = True
    if LIVE:
        run_algorithm(
            capital_base=1,
            initialize=initialize,
            handle_data=handle_data,
            exchange_name='poloniex',
            algo_namespace='test_multi_assets',
            quote_currency='usdt',
            live=True,
            simulate_orders=True,
        )
    else:
        run_algorithm(
            capital_base=1,
            data_frequency='minute',
            initialize=initialize,
            handle_data=handle_data,
            exchange_name='poloniex',
            algo_namespace='test_multi_assets',
            quote_currency='usdt',
            live=False,
            start=pd.to_datetime('2017-12-1', utc=True),
Ejemplo n.º 6
0
        perf.loc[:, "rsi"].plot(ax=ax5, label="RSI")
        ax5.set_ylabel("RSI")
        start, end = ax5.get_ylim()
        ax5.yaxis.set_ticks(np.arange(0, end, end / 5))

        plt.show()


if __name__ == "__main__":
    if LIVE:
        run_algorithm(
            capital_base=1000,
            data_frequency="minute",
            initialize=initialize,
            simulate_orders=True,
            handle_data=handle_data,
            exchange_name="bitfinex",
            algo_namespace=NAMESPACE,
            quote_currency="usd",
            live=True,
        )
    else:
        run_algorithm(
            # How much cash
            capital_base=1000,
            data_frequency="minute",
            initialize=initialize,
            handle_data=handle_data,
            exchange_name="bitfinex",
            analyze=analyze,
            algo_namespace=NAMESPACE,
Ejemplo n.º 7
0
    plt.show()
    pass


if __name__ == '__main__':
    # The execution mode: backtest or live
    live = True

    if live:
        run_algorithm(
            capital_base=0.1,
            initialize=initialize,
            handle_data=handle_data,
            analyze=analyze,
            exchange_name='binance',
            live=True,
            algo_namespace=NAMESPACE,
            quote_currency='eth',
            live_graph=False,
            simulate_orders=False,
            stats_output=None,
            # auth_aliases=dict(poloniex='auth2')
        )

    else:
        folder = os.path.join(tempfile.gettempdir(), 'catalyst', NAMESPACE)
        ensure_directory(folder)

        timestr = time.strftime('%Y%m%d-%H%M%S')
        out = os.path.join(folder, '{}.p'.format(timestr))
        # catalyst run -f catalyst/examples/mean_reversion_simple.py \
        #    -x bitfinex -s 2017-10-1 -e 2017-11-10 -c usdt -n mean-reversion \
Ejemplo n.º 8
0
        # we iterate for every pair in the current universe
        for coin in context.coins:
            pair = str(coin.symbol)

            price = data.current(coin, 'price')
            print(today, pair, price)


def analyze(context=None, results=None):
    pass


if __name__ == '__main__':
    start_date = pd.to_datetime('2018-01-17', utc=True)
    end_date = pd.to_datetime('2018-01-18', utc=True)

    performance = run_algorithm(
        capital_base=1.0,
        # amount of base_currency, not always in dollars unless usd
        initialize=initialize,
        handle_data=handle_data,
        analyze=analyze,
        exchange_name='cryptopia',
        data_frequency='minute',
        base_currency='btc',
        live=True,
        live_graph=False,
        simulate_orders=True,
        algo_namespace='simple_universe'
    )
Ejemplo n.º 9
0
    plt.show()
    pass


if __name__ == '__main__':
    # The execution mode: backtest or live
    live = True

    if live:
        run_algorithm(
            capital_base=0.1,
            initialize=initialize,
            handle_data=handle_data,
            analyze=analyze,
            exchange_name='binance',
            live=True,
            algo_namespace=NAMESPACE,
            base_currency='eth',
            live_graph=False,
            simulate_orders=False,
            stats_output=None,
            # auth_aliases=dict(poloniex='auth2')
        )

    else:
        folder = os.path.join(
            tempfile.gettempdir(), 'catalyst', NAMESPACE
        )
        ensure_directory(folder)

        timestr = time.strftime('%Y%m%d-%H%M%S')
        out = os.path.join(folder, '{}.p'.format(timestr))
Ejemplo n.º 10
0
    if not transaction_df.empty:
        ax2.scatter(transaction_df.index.to_pydatetime(),
                    perf.loc[transaction_df.index, 'price'],
                    marker='x',
                    s=150,
                    c='black',
                    label='')

    # Plot our cash
    ax3 = plt.subplot(313, sharex=ax1)
    perf.cash.plot(ax=ax3)
    ax3.set_ylabel('Cash\n({})'.format(quote_currency))
    start, end = ax3.get_ylim()
    ax3.yaxis.set_ticks(np.arange(0, end, end / 5))

    plt.show()


if __name__ == '__main__':
    run_algorithm(
        capital_base=10000,
        analyze=analyze,
        data_frequency='minute',
        initialize=initialize,
        handle_data=handle_data,
        exchange_name='poloniex',
        quote_currency='usdt',
        live=False,
        start=pd.to_datetime('2018-07-30', utc=True),
        end=pd.to_datetime('2018-08-31', utc=True),
    )
Ejemplo n.º 11
0
    results[[
        'treasury',
        'algorithm',
        'benchmark',
    ]].plot(ax=ax5)
    ax5.set_ylabel('Percent Change')

    ax6 = plt.subplot(616, sharex=ax1)
    results[['volume']].plot(ax=ax6)
    ax6.set_ylabel('Volume (mCoins/5min)')

    plt.legend(loc=3)

    # Show the plot.
    plt.gcf().set_size_inches(18, 8)
    plt.show()


if __name__ == '__main__':
    run_algorithm(
        capital_base=10000,
        data_frequency='daily',
        initialize=initialize,
        handle_data=handle_data,
        analyze=analyze,
        exchange_name='bitfinex',
        algo_namespace='buy_and_hodl',
        base_currency='usd',
        start=pd.to_datetime('2015-03-01', utc=True),
        end=pd.to_datetime('2017-10-31', utc=True),
    )
Ejemplo n.º 12
0
        return series.replace([np.inf, -np.inf], np.nan).ffill().bfill()
    elif isinstance(series, np.ndarray):
        return pd.Series(series).replace([np.inf, -np.inf],
                                         np.nan).ffill().bfill().values
    else:
        return series


if __name__ == '__main__':
    start_date = pd.to_datetime('2017-11-10', utc=True)
    end_date = pd.to_datetime('2017-11-13', utc=True)

    performance = run_algorithm(
        start=start_date,
        end=end_date,
        capital_base=
        100.0,  # amount of base_currency, not always in dollars unless usd
        initialize=initialize,
        handle_data=handle_data,
        analyze=analyze,
        exchange_name='bitfinex',
        data_frequency='minute',
        base_currency='btc',
        live=False,
        live_graph=False,
        algo_namespace='simple_universe')
"""
Run in Terminal (inside catalyst environment):
python simple_universe.py
"""
Ejemplo n.º 13
0
    log.info('- sma_test:       {}'.format(getLast(analysis, 'sma_test')))
    log.info('- macd_test:      {}'.format(getLast(analysis, 'macd_test')))

    log.info('- stoch_over_bought:   {}'.format(
        getLast(analysis, 'stoch_over_bought')))
    log.info(
        '- stoch_over_sold:   {}'.format(getLast(analysis, 'stoch_over_sold')))

    log.info('- rsi_over_bought:       {}'.format(
        getLast(analysis, 'rsi_over_bought')))
    log.info(
        '- rsi_over_sold:       {}'.format(getLast(analysis, 'rsi_over_sold')))


def getLast(arr, name):
    return arr[name][arr[name].index[-1]]


if __name__ == '__main__':
    run_algorithm(
        capital_base=10000,
        data_frequency='daily',
        initialize=initialize,
        handle_data=handle_data,
        analyze=analyze,
        exchange_name='poloniex',
        base_currency='usdt',
        start=pd.to_datetime('2016-11-1', utc=True),
        end=pd.to_datetime('2017-11-10', utc=True),
    )
Ejemplo n.º 14
0
    high = fill(data.history(context.asset,
                             'high',
                             bar_count=lookback,
                             frequency='240T')).values
    low = fill(data.history(context.asset,
                            'low',
                            bar_count=lookback,
                            frequency='240T')).values
    close = fill(data.history(context.asset,
                              'price',
                              bar_count=lookback,
                              frequency='240T')).values
    volume = fill(data.history(context.asset,
                               'volume',
                               bar_count=lookback,
                               frequency='240T')).values


if __name__ == '__main__':
    run_algorithm(
        capital_base=1000,
        data_frequency='minute',
        initialize=initialize,
        handle_data=handle_data,
        exchange_name='poloniex',
        algo_namespace='momentum',
        quote_currency='usd',
        live=False,
        start=pd.to_datetime('2017-09-20', utc=True),
        end=pd.to_datetime('2018-03-23', utc=True),
    )
Ejemplo n.º 15
0
    ax3 = plt.subplot(212)
    idx = pd.IndexSlice
    df = context.github.loc[START:END].loc[
            idx[:, [b'XMR']], ['commits']].reset_index(
                level='symbol', drop=True)
    df.plot(ax=ax3, color='blue')
    ax3.legend(loc=2)
    ax3.set_title('Monero')
    ax4 = ax3.twinx()
    context.xmr['price'].loc[START:END].plot(ax=ax4, color='green')
    ax4.legend(loc=1)

    plt.show()


if __name__ == '__main__':
    run_algorithm(
            capital_base=1000,
            data_frequency='daily',
            initialize=initialize,
            handle_data=handle_data,
            analyze=analyze,
            exchange_name='poloniex',
            algo_namespace='algo-github',
            base_currency='usdt',
            live=False,
            start=pd.to_datetime(END, utc=True),
            end=pd.to_datetime(END, utc=True),
        )
Ejemplo n.º 16
0
    perf.loc[:, ['algorithm_period_return', 'price_change']].plot(ax=ax3)
    ax3.legend_.remove()
    ax3.set_ylabel('Percent Change')
    start, end = ax3.get_ylim()
    ax3.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    # Fourth chart: Plot our cash
    ax4 = plt.subplot(414, sharex=ax1)
    perf.cash.plot(ax=ax4)
    ax4.set_ylabel('Cash\n({})'.format(base_currency))
    start, end = ax4.get_ylim()
    ax4.yaxis.set_ticks(np.arange(0, end, end / 5))

    plt.show()


if __name__ == '__main__':
    
    run_algorithm(
            capital_base=1000,
            data_frequency='minute',
            initialize=initialize,
            handle_data=handle_data,
            analyze=analyze,
            exchange_name='bitfinex',
            algo_namespace=NAMESPACE,
            base_currency='usd',
            start=pd.to_datetime('2017-9-22', utc=True),
            end=pd.to_datetime('2017-9-23', utc=True),
        )
Ejemplo n.º 17
0
    ax4.set_xlabel('Time')
    ax4.set_ylabel('Amount')

    # Plot amount of asset in portfolio
    ax5 = f.add_subplot(615, sharex = ax1)
    ax5.plot(perf.amount, 'black')
    ax5.set_title('Asset amount in portfolio')
    ax5.set_xlabel('Time')
    ax5.set_ylabel('Amount')

    # Plot drawdown
    ax6 = f.add_subplot(616, sharex = ax1)
    ax6.plot(perf.max_drawdown, 'yellow')
    ax6.set_title('Max drawdown')
    ax6.set_xlabel('Time')
    ax6.set_ylabel('Drawdown')

    plt.show()

run_algorithm(
    capital_base = 10,
    data_frequency = 'daily',
    initialize = initialize,
    handle_data = handle_data,
    analyze = analyze,
    exchange_name = 'bitfinex',
    quote_currency = 'btc',
    start = pd.to_datetime('2017-12-1', utc = True),
    end = pd.to_datetime('2018-11-12', utc = True))

Ejemplo n.º 18
0
    return df.symbol.tolist()


# Replace all NA, NAN or infinite values with its nearest value
def fill(series):
    if isinstance(series, pd.Series):
        return series.replace([np.inf, -np.inf], np.nan).ffill().bfill()
    elif isinstance(series, np.ndarray):
        return pd.Series(series).replace(
                     [np.inf, -np.inf], np.nan
                    ).ffill().bfill().values
    else:
        return series


if __name__ == '__main__':
    start_date = pd.to_datetime('2017-11-10', utc=True)
    end_date = pd.to_datetime('2017-11-13', utc=True)

    performance = run_algorithm(start=start_date, end=end_date,
                                capital_base=100.0,  # amount of base_currency
                                initialize=initialize,
                                handle_data=handle_data,
                                analyze=analyze,
                                exchange_name='poloniex',
                                data_frequency='minute',
                                base_currency='btc',
                                live=False,
                                live_graph=False,
                                algo_namespace='simple_universe')
Ejemplo n.º 19
0
def handle_data(context, data):
    price = data.current(context.asset, 'price')
    record(btc=price)

    # Only ordering if it does not have any position to avoid trying some
    # tiny orders with the leftover btc
    pos_amount = context.portfolio.positions[context.asset].amount
    if pos_amount > 0:
        return

    # Adding a limit price to workaround an issue with performance
    # calculations of market orders
    order_target_percent(
        context.asset, 1, limit_price=price * 1.01
    )


if __name__ == '__main__':
    run_algorithm(
        capital_base=0.003,
        initialize=initialize,
        handle_data=handle_data,
        exchange_name='binance',
        live=True,
        algo_namespace=NAMESPACE,
        base_currency='btc',
        live_graph=False,
        simulate_orders=False,
    )
Ejemplo n.º 20
0
    ax4 = plt.subplot(613, sharex=ax1)
    perf.loc[:, 'cash'].plot(ax=ax4,
                             label='Base Currency ({})'.format(base_currency))
    ax4.set_ylabel('Cash ({})'.format(base_currency))

    perf['algorithm'] = perf.loc[:, 'algorithm_period_return']

    ax5 = plt.subplot(614, sharex=ax1)
    perf.loc[:, ['algorithm', 'price_change']].plot(ax=ax5)
    ax5.set_ylabel('Percent Change')

    plt.legend(loc=3)

    # Show the plot.
    plt.gcf().set_size_inches(18, 8)
    plt.show()
    pass


if __name__ == '__main__':
    run_algorithm(capital_base=1,
                  initialize=initialize,
                  handle_data=handle_data,
                  analyze=None,
                  exchange_name='poloniex',
                  live=True,
                  algo_namespace='simple_loop',
                  base_currency='eth',
                  live_graph=False,
                  simulate_orders=True)
Ejemplo n.º 21
0
                      frequency='5T',
                      )
    print(df)
    print(data.current(context.asset1, 'close'))
    print(data.current(context.asset2, 'close'))
    exit(0)


if __name__ == '__main__':
    LIVE = True
    if LIVE:
        run_algorithm(
            capital_base=1,
            initialize=initialize,
            handle_data=handle_data,
            exchange_name='poloniex',
            algo_namespace='test_multi_assets',
            base_currency='usdt',
            live=True,
            simulate_orders=True,
        )
    else:
        run_algorithm(
            capital_base=1,
            data_frequency='minute',
            initialize=initialize,
            handle_data=handle_data,
            exchange_name='poloniex',
            algo_namespace='test_multi_assets',
            base_currency='usdt',
            live=False,
            start=pd.to_datetime('2017-12-1', utc=True),
Ejemplo n.º 22
0

if __name__ == '__main__':
    # Parameters:
    parameters = SimulationParameters()
    start_date = pd.to_datetime(parameters.START_DATE, utc=True)
    end_date = pd.to_datetime(parameters.END_DATE, utc=True)

    if parameters.MODE == 'backtest':
        results = run_algorithm(
            capital_base=parameters.CAPITAL_BASE,
            data_frequency=parameters.DATA_FREQUECY,
            initialize=initialize,
            handle_data=default_handle_data,
            analyze=default_analyze,
            exchange_name=parameters.EXCHANGE_NAME,
            algo_namespace=parameters.ALGO_NAMESPACE,
            base_currency=parameters.BASE_CURRENCY,
            start=start_date,
            end=end_date,
            live=False,
            live_graph=False
        )

        returns_daily = results
        results.to_csv('{}'.format(parameters.ALGO_NAMESPACE_RESULTS_TABLE))

        # returns_daily = returns_minutely.add(1).groupby(pd.TimeGrouper('24H')).prod().add(-1)

        # FIXME: pyfolio integration
        # pf_data = pyfolio.utils.extract_rets_pos_txn_from_zipline(results)
        # pf_data = pyfolio.utils.extract_rets_pos_txn_from_zipline(results[:'2017-01-01'])
    print('the algo stats:\n{}'.format(stats))
    pass


if __name__ == '__main__':
    # The execution mode: backtest or live
    live = False

    if live:
        run_algorithm(
            capital_base=0.1,
            initialize=initialize,
            handle_data=handle_data,
            analyze=analyze,
            exchange_name='poloniex',
            live=True,
            algo_namespace=NAMESPACE,
            base_currency='btc',
            live_graph=False,
            simulate_orders=False,
            stats_output=None,
        )

    else:
        folder = os.path.join(tempfile.gettempdir(), 'catalyst', NAMESPACE)
        ensure_directory(folder)

        timestr = time.strftime('%Y%m%d-%H%M%S')
        out = os.path.join(folder, '{}.p'.format(timestr))
        # catalyst run -f catalyst/examples/mean_reversion_simple.py \
        #    -x bitfinex -s 2017-10-1 -e 2017-11-10 -c usdt -n mean-reversion \
Ejemplo n.º 24
0
    context.asset = symbol('trx_btc')


def handle_data(context, data):
    #order(context.asset, 1)
    context.set_slippage(5)
    #record(btc=data.current(context.asset, 'price'))
    current = data.current(context.asset, ['open', 'close'])
    #history = data.history(context.asset, ['open', 'volume'],
    #                       bar_count=2,
    #                       frequency='1T')

    print('CURRENT:')
    print("{} {}\n".format(data.current_dt, current))
    #print('HISTORY (2 BARS):')
    #print("{}\n".format(history))


if __name__ == '__main__':
    run_algorithm(
        capital_base=10000,
        data_frequency='minute',
        initialize=initialize,
        handle_data=handle_data,
        exchange_name='bitfinex',
        algo_namespace='buy_omg_simple',
        quote_currency='usdt',
        start=pd.to_datetime('2018-01-24', utc=True),
        end=pd.to_datetime('2018-01-26', utc=True),
    )
Ejemplo n.º 25
0
def analyze(context, perf):
    stats = get_pretty_stats(perf)
    print(stats)
    pass


if __name__ == '__main__':
    live = True
    if live:
        run_algorithm(
            capital_base=0.01,
            initialize=initialize,
            handle_data=handle_data,
            exchange_name='poloniex',
            algo_namespace='buy_btc_polo_jh',
            base_currency='btc',
            analyze=analyze,
            live=True,
            simulate_orders=True,
        )
    else:
        run_algorithm(
            capital_base=1000,
            data_frequency='daily',
            initialize=initialize,
            handle_data=handle_data,
            exchange_name='poloniex',
            algo_namespace='buy_btc_polo_jh',
            base_currency='usd',
            analyze=analyze,
Ejemplo n.º 26
0
        scoring='accuracy',  # 'neg_log_loss',
        t1=vertical_barrier.loc[FDFeatures["price"].index],
        cv=8,  # número de divisiones para el Cross-Validation
        cvGen=None,  # Generador de Cross-Validator, si existiera previamente.
        pctEmbargo=0.01)
    print("Puntaje de Cross-Validation para modelo secundario: ", meta_score)

    print("Pickling model...")
    model_name = "ml_model_rf_s" + str(X.shape[0]) + "_p" + str(
        context.bar_period) + ".pkl"
    joblib.dump(context.model, context.model_pickle_directory + "model.pkl")
    joblib.dump(context.meta_model,
                context.model_pickle_directory + "meta_model.pkl")

    context.model_trained = True


if __name__ == '__main__':
    run_algorithm(
        capital_base=1000,
        data_frequency='minute',
        initialize=initialize,
        handle_data=handle_data,
        analyze=analyze,
        exchange_name='poloniex',
        algo_namespace=NAMESPACE,
        quote_currency='usd',
        start=pd.to_datetime('2018-11-1', utc=True),
        end=pd.to_datetime('2018-11-30', utc=True),
    )
Ejemplo n.º 27
0
    return df.symbol.tolist()


# Replace all NA, NAN or infinite values with its nearest value
def fill(series):
    if isinstance(series, pd.Series):
        return series.replace([np.inf, -np.inf], np.nan).ffill().bfill()
    elif isinstance(series, np.ndarray):
        return pd.Series(series).replace([np.inf, -np.inf],
                                         np.nan).ffill().bfill().values
    else:
        return series


if __name__ == '__main__':
    start_date = pd.to_datetime('2017-11-10', utc=True)
    end_date = pd.to_datetime('2017-11-13', utc=True)

    performance = run_algorithm(
        start=start_date,
        end=end_date,
        capital_base=100.0,  # amount of quote_currency
        initialize=initialize,
        handle_data=handle_data,
        analyze=analyze,
        exchange_name='poloniex',
        data_frequency='minute',
        quote_currency='btc',
        live=False,
        live_graph=False,
        algo_namespace='simple_universe')
Ejemplo n.º 28
0
    print('initializing')
    context.asset = symbol('xcp_btc')


def handle_data(context, data):
    print('handling bar: {}'.format(data.current_dt))

    price = data.current(context.asset, 'close')
    print('got price {price}'.format(price=price))

    try:
        prices = data.history(context.asset,
                              fields='close',
                              bar_count=1,
                              frequency='1D')
        print('got {} price entries\n'.format(len(prices), prices))
    except Exception as e:
        print(e)


run_algorithm(capital_base=1,
              start=pd.to_datetime('2015-3-2', utc=True),
              end=pd.to_datetime('2017-8-31', utc=True),
              data_frequency='daily',
              initialize=initialize,
              handle_data=handle_data,
              analyze=None,
              exchange_name='poloniex',
              algo_namespace='issue_55',
              quote_currency='btc')
Ejemplo n.º 29
0
        log.info('no buy or sell opportunity found')


def getLast(arr, name):
    return arr[name][arr[name].index[-1]]


if __name__ == '__main__':
    live = False
    if live:
        run_algorithm(
            capital_base=3000,
            initialize=initialize,
            handle_data=handle_data,
            analyze=analyze,
            exchange_name='bittrex',
            live=True,
            algo_namespace='hedge',
            base_currency='usdt',
            simulate_orders=True,
        )
    else:
        run_algorithm(
            capital_base=10000,
            data_frequency='minute',
            initialize=initialize,
            handle_data=handle_data,
            analyze=analyze,
            exchange_name='poloniex',
            algo_namespace='hedge',
            base_currency='usdt',
Ejemplo n.º 30
0
    pos_percent_change[pos_percent_change <= 0] = np.nan
    neg_percent_change[neg_percent_change > 0] = np.nan

    ax4 = plt.subplot(414, sharex=ax1)
    pos_percent_change.loc[:, ['percent_change_btc']].plot(ax=ax4, color='g')

    neg_percent_change.loc[:, ['percent_change_btc']].plot(ax=ax4, color='r')

    ax4.set_ylabel('% change btc')
    start, end = ax4.get_ylim()
    ax4.yaxis.set_ticks(np.arange(start, end, end / 5))
    ax4.legend_.remove()

    plt.show()


if __name__ == '__main__':
    run_algorithm(
        analyze=analyze,
        capital_base=1000,
        data_frequency='daily',
        initialize=initialize,
        handle_data=handle_data,
        exchange_name='poloniex',
        algo_namespace='momentum',
        base_currency='usd',
        live=False,
        start=pd.to_datetime('2015-10-20', utc=True),
        end=pd.to_datetime('2018-04-23', utc=True),
    )
Ejemplo n.º 31
0
    # Show the plot.
    plt.gcf().set_size_inches(18, 8)
    plt.show()
    pass


if __name__ == '__main__':
    mode = 'backtest'

    if mode == 'backtest':
        run_algorithm(
            capital_base=1,
            initialize=initialize,
            handle_data=handle_data,
            analyze=None,
            exchange_name='poloniex',
            algo_namespace='simple_loop',
            base_currency='eth',
            data_frequency='minute',
            start=pd.to_datetime('2017-9-1', utc=True),
            end=pd.to_datetime('2017-12-1', utc=True),
        )
    else:
        run_algorithm(capital_base=1,
                      initialize=initialize,
                      handle_data=handle_data,
                      analyze=None,
                      exchange_name='binance',
                      live=True,
                      algo_namespace='simple_loop',
                      base_currency='eth',
                      live_graph=False,
Ejemplo n.º 32
0
            label="",
        )

    plt.show()
    print(results)


if __name__ == "__main__":
    live = False
    if live:
        run_algorithm(
            capital_base=1000,
            initialize=initialize,
            handle_data=handle_data,
            analyze=analyze,
            exchange_name="poloniex",
            live=True,
            algo_namespace="hedge",
            base_currency="usdt",
            simulate_orders=True,
        )
    else:
        run_algorithm(
            capital_base=10000,
            data_frequency="minute",
            initialize=initialize,
            handle_data=handle_data,
            analyze=analyze,
            exchange_name="poloniex",
            algo_namespace="ANN",
            base_currency="usdt",
Ejemplo n.º 33
0
    plt.show()
    pass


if __name__ == '__main__':
    # The execution mode: backtest or live
    MODE = 'backtest'

    if MODE == 'backtest':
        run_algorithm(
            capital_base=1,
            data_frequency='minute',
            initialize=initialize,
            handle_data=handle_data,
            analyze=analyze,
            exchange_name='poloniex',
            algo_namespace=algo_namespace,
            base_currency='usdt',
            start=pd.to_datetime('2017-7-1', utc=True),
            # end=pd.to_datetime('2017-9-30', utc=True),
            end=pd.to_datetime('2017-10-31', utc=True),
        )

    elif MODE == 'live':
        run_algorithm(initialize=initialize,
                      handle_data=handle_data,
                      analyze=analyze,
                      exchange_name='poloniex',
                      live=True,
                      algo_namespace=algo_namespace,
                      base_currency='usdt',
Ejemplo n.º 34
0
    trans = results.ix[[t != [] for t in results.transactions]]
    buys = trans.ix[
        [t[0]['amount'] > 0 for t in trans.transactions]
    ]
    ax2.scatter(
        buys.index.to_pydatetime(),
        results.price[buys.index],
        marker='^',
        s=100,
        c='g',
        label=''
    )

    # Show the plot.
    plt.gcf().set_size_inches(18, 8)
    plt.show()

if __name__ == '__main__':
    run_algorithm(
        capital_base=1000,
        data_frequency='minute',
        initialize=initialize,
        handle_data=handle_data,
        analyze=analyze,
        exchange_name='bitfinex',
        algo_namespace='buy_and_hodl',
        quote_currency='usdt',
        start=pd.to_datetime('2018-05-25', utc=True),
        end=pd.to_datetime('2018-06-04', utc=True),
    )
    perf.loc[:, ['algorithm_period_return', 'price_change']].plot(ax=ax3)
    ax3.legend_.remove()
    ax3.set_ylabel('Percent Change')
    start, end = ax3.get_ylim()
    ax3.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    # Fourth chart: Plot our cash
    ax4 = plt.subplot(414, sharex=ax1)
    perf.cash.plot(ax=ax4)
    ax4.set_ylabel('Cash\n({})'.format(quote_currency))
    start, end = ax4.get_ylim()
    ax4.yaxis.set_ticks(np.arange(0, end, end / 5))

    plt.show()


if __name__ == '__main__':

    run_algorithm(
        capital_base=1000,
        data_frequency='minute',
        initialize=initialize,
        handle_data=handle_data,
        analyze=analyze,
        exchange_name='binance',
        live=True,
        algo_namespace=NAMESPACE,
        quote_currency='usd',
        simulate_orders=True,
    )
Ejemplo n.º 36
0
    perf.loc[:, ['btc_price']].plot(ax=ax2, label='PriceB', color='orange')
    ax2.legend_.remove()
    ax2.set_ylabel('BTC USDT')
    start, end = ax2.get_ylim()
    ax2.yaxis.set_ticks(np.arange(0, end, (end - start) / 5))

    transaction_df = extract_transactions(perf)
    if not transaction_df.empty:
        ax2.scatter(transaction_df.index.to_pydatetime(),
                    perf.loc[transaction_df.index, 'btc_price'],
                    marker='x',
                    s=150,
                    c='black',
                    label='')
    plt.show()


if __name__ == '__main__':
    run_algorithm(
        analyze=analyze,
        capital_base=1000,
        initialize=initialize,
        handle_data=handle_data,
        exchange_name='binance',
        algo_namespace='dual_momentum_asdfsadf',
        quote_currency='usd',
        live=True,
        simulate_orders=True,
        # start=pd.to_datetime('2016-01-01', utc=True),
        # end=pd.to_datetime('2018-03-01', utc=True),
    )
Ejemplo n.º 37
0
    ax3 = plt.subplot(413, sharex=ax1)
    perf.loc[:, ['algorithm_period_return', 'price_change']].plot(ax=ax3)
    ax3.legend_.remove()
    ax3.set_ylabel('Percent Change')
    start, end = ax3.get_ylim()
    ax3.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    # Fourth chart: Plot our cash
    ax4 = plt.subplot(414, sharex=ax1)
    perf.cash.plot(ax=ax4)
    ax4.set_ylabel('Cash\n({})'.format(base_currency))
    start, end = ax4.get_ylim()
    ax4.yaxis.set_ticks(np.arange(0, end, end / 5))

    plt.show()


if __name__ == '__main__':
    run_algorithm(
        capital_base=1000,
        data_frequency='minute',
        initialize=initialize,
        handle_data=handle_data,
        analyze=analyze,
        exchange_name='bitfinex',
        algo_namespace=NAMESPACE,
        base_currency='usd',
        start=pd.to_datetime('2017-9-22', utc=True),
        end=pd.to_datetime('2017-9-23', utc=True),
    )
Ejemplo n.º 38
0
    # ax4.yaxis.set_ticks(np.arange(0, end, end / 5))
    #
    # plt.tight_layout()
    # plt.show()


if __name__ == '__main__':
    run_modes = ['backtesting', 'paper trading', 'live']
    run_mode = run_modes[2]

    if run_mode == 'backtesting':
        run_algorithm(capital_base=90,
                      data_frequency='daily',
                      initialize=initialize,
                      handle_data=handle_data,
                      analyze=analyze,
                      exchange_name='binance',
                      algo_namespace=NAMESPACE,
                      quote_currency='usdt',
                      start=pd.to_datetime('2019-01-01', utc=True),
                      end=pd.to_datetime('2019-01-27', utc=True))

    elif run_mode == 'live':
        # 实盘交易
        run_algorithm(live=True,
                      simulate_orders=False,
                      capital_base=100,
                      initialize=initialize,
                      handle_data=handle_data,
                      analyze=analyze,
                      exchange_name='binance',
                      algo_namespace=NAMESPACE,
Ejemplo n.º 39
0
        'treasury',
        'algorithm',
        'benchmark',
    ]].plot(ax=ax5)
    ax5.set_ylabel('Percent\nChange')

    ax6 = plt.subplot(616, sharex=ax1)
    results[['volume']].plot(ax=ax6)
    ax6.set_ylabel('Volume')

    plt.legend(loc=3)

    # Show the plot.
    plt.gcf().set_size_inches(18, 8)
    plt.show()


if __name__ == '__main__':
    run_algorithm(
        capital_base=10000,
        data_frequency='daily',
        initialize=initialize,
        handle_data=handle_data,
        analyze=analyze,
        exchange_name='poloniex',
        algo_namespace='buy_and_hodl',
        base_currency='usdt',
        start=pd.to_datetime('2015-03-01', utc=True),
        end=pd.to_datetime('2017-10-31', utc=True),
    )
Ejemplo n.º 40
0
    context.asset = symbol('trx_btc')


def handle_data(context, data):
    price = data.current(context.asset, 'price')
    record(btc=price)

    # Only ordering if it does not have any position to avoid trying some
    # tiny orders with the leftover btc
    pos_amount = context.portfolio.positions[context.asset].amount
    if pos_amount > 0:
        return

    # Adding a limit price to workaround an issue with performance
    # calculations of market orders
    order_target_percent(context.asset, 1, limit_price=price * 1.01)


if __name__ == '__main__':
    run_algorithm(
        capital_base=0.003,
        initialize=initialize,
        handle_data=handle_data,
        exchange_name='binance',
        live=True,
        algo_namespace=NAMESPACE,
        quote_currency='btc',
        live_graph=False,
        simulate_orders=False,
    )
Ejemplo n.º 41
0
    # Show the plot.
    plt.gcf().set_size_inches(18, 8)
    plt.show()
    pass


if __name__ == '__main__':
    mode = 'backtest'

    if mode == 'backtest':
        run_algorithm(
            capital_base=1,
            initialize=initialize,
            handle_data=handle_data,
            analyze=None,
            exchange_name='poloniex',
            algo_namespace='simple_loop',
            base_currency='eth',
            data_frequency='minute',
            start=pd.to_datetime('2017-9-1', utc=True),
            end=pd.to_datetime('2017-12-1', utc=True),
        )
    else:
        run_algorithm(
            capital_base=1,
            initialize=initialize,
            handle_data=handle_data,
            analyze=None,
            exchange_name='binance',
            live=True,
            algo_namespace='simple_loop',
            base_currency='eth',
Ejemplo n.º 42
0
    log.info('- sma_test:       {}'.format(getLast(analysis, 'sma_test')))
    log.info('- macd_test:      {}'.format(getLast(analysis, 'macd_test')))

    log.info('- stoch_over_bought:   {}'.format(
        getLast(analysis, 'stoch_over_bought')))
    log.info('- stoch_over_sold:   {}'.format(
        getLast(analysis, 'stoch_over_sold')))

    log.info('- rsi_over_bought:       {}'.format(
        getLast(analysis, 'rsi_over_bought')))
    log.info('- rsi_over_sold:       {}'.format(
        getLast(analysis, 'rsi_over_sold')))


def getLast(arr, name):
    return arr[name][arr[name].index[-1]]


if __name__ == '__main__':
    run_algorithm(
        capital_base=10000,
        data_frequency='daily',
        initialize=initialize,
        handle_data=handle_data,
        analyze=analyze,
        exchange_name='poloniex',
        base_currency='usdt',
        start=pd.to_datetime('2016-11-1', utc=True),
        end=pd.to_datetime('2017-11-10', utc=True),
    )
Ejemplo n.º 43
0
def handle_data(context, data):
    print('handling bar: {}'.format(data.current_dt))

    price = data.current(context.asset, 'close')
    print('got price {price}'.format(price=price))

    try:
        prices = data.history(
            context.asset,
            fields='close',
            bar_count=1,
            frequency='1D'
        )
        print('got {} price entries\n'.format(len(prices), prices))
    except Exception as e:
        print(e)


run_algorithm(
    capital_base=1,
    start=pd.to_datetime('2015-3-2', utc=True),
    end=pd.to_datetime('2017-8-31', utc=True),
    data_frequency='daily',
    initialize=initialize,
    handle_data=handle_data,
    analyze=None,
    exchange_name='poloniex',
    algo_namespace='issue_55',
    base_currency='btc'
)
Ejemplo n.º 44
0
import pandas as pd
import MA_crossover_strategy
from catalyst import run_algorithm

if __name__ == "__main__":
    run_algorithm(capital_base=1000,
                  data_frequency="minute",
                  initialize=MA_crossover_strategy.initialize,
                  handle_data=MA_crossover_strategy.handle_data,
                  analyze=MA_crossover_strategy.analyze,
                  exchange_name="bitfinex",
                  algo_namespace=MA_crossover_strategy.NAMESPACE,
                  base_currency="usd",
                  start=pd.to_datetime("2018-4-25", utc=True),
                  end=pd.to_datetime("2018-4-26", utc=True))