Beispiel #1
0
def analyze(context, results):
    ax1 = plt.subplot(611)
    results[["portfolio_value"]].plot(ax=ax1)
    ax1.set_ylabel("Portfolio\nValue\n(USD)")

    ax2 = plt.subplot(412, sharex=ax1)
    results.loc[:, ["price"]].plot(ax=ax2, label="Price")
    ax2.legend_.remove()
    start, end = ax2.get_ylim()
    ax2.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    transaction_df = extract_transactions(results)
    if not transaction_df.empty:
        buy_df = transaction_df[transaction_df["amount"] > 0]
        sell_df = transaction_df[transaction_df["amount"] < 0]
        ax2.scatter(
            buy_df.index.to_pydatetime(),
            results.loc[buy_df.index, "price"],
            marker="^",
            s=100,
            c="green",
            label="",
        )
        ax2.scatter(
            sell_df.index.to_pydatetime(),
            results.loc[sell_df.index, "price"],
            marker="v",
            s=100,
            c="red",
            label="",
        )

    plt.show()
    print(results)
Beispiel #2
0
def plot_single(perf, filepath=None):
    plt.figure(figsize=(20, 10))
    ax1 = plt.subplot(411)
    perf.loc[:, ['cmx_pnl']].plot(ax=ax1)
    ax1.legend_.remove()
    ax1.set_ylabel('pnl\n(quote)')
    ymin, ymax = ax1.get_ylim()
    ax1.yaxis.set_ticks(np.arange(ymin, ymax, (ymax - ymin) / 5))

    # Second chart: Plot asset price, moving averages and buys/sells
    ax2 = plt.subplot(412, sharex=ax1)
    perf.loc[:, [
        'price', 'fair_price', 'invent_long_entry', 'invent_short_entry'
    ]].plot(ax=ax2, label='Price')
    ax2.legend_.remove()
    ax2.set_ylabel('price')
    ymin, ymax = ax2.get_ylim()
    ax2.yaxis.set_ticks(np.arange(ymin, ymax, (ymax - ymin) / 5))

    transaction_df = extract_transactions(perf)
    if transaction_df is not None and not transaction_df.empty:
        buy_df = transaction_df[transaction_df['amount'] > 0]
        sell_df = transaction_df[transaction_df['amount'] < 0]
        ax2.scatter(buy_df.index.to_pydatetime(),
                    perf.loc[buy_df.index, 'price'],
                    marker='^',
                    s=100,
                    c='green',
                    label='')
        ax2.scatter(sell_df.index.to_pydatetime(),
                    perf.loc[sell_df.index, 'price'],
                    marker='v',
                    s=100,
                    c='red',
                    label='')

    # Third chart: Plot our position
    position_series = perf['positions'].map(lambda x: x[0]['amount']
                                            if len(x) > 0 else 0)
    # position_series -= self.context.risk_init_position
    ax3 = plt.subplot(413, sharex=ax1)
    position_series.plot(ax=ax3)
    ax3.set_ylabel('position\n(base)')
    ymin, ymax = ax3.get_ylim()
    ax3.yaxis.set_ticks(np.arange(ymin, ymax, (ymax - ymin) / 5))

    # Fourth chart: Compare percentage change between our portfolio
    # and the price of the asset
    ax4 = plt.subplot(414, sharex=ax1)
    perf.loc[:, ['algorithm_period_return', 'price_change']].plot(ax=ax4)
    ax4.legend_.remove()
    ax4.set_ylabel('pct change')
    ymin, ymax = ax4.get_ylim()
    ax4.yaxis.set_ticks(np.arange(ymin, ymax, (ymax - ymin) / 5))

    if filepath is not None:
        folder = os.path.dirname(os.path.abspath(filepath))
        if not os.path.exists(folder):
            os.makedirs(folder)
        plt.savefig(filepath, dpi=300)
Beispiel #3
0
def plot_buy_sells(results, pos, y_val=None):
    # Plot the price increase or decrease over time.

    if y_val is None:
        y_val = "price"
        ax = plot_column(results, "price", pos, y_label="Buy/Sells")

    else:  # dont plot price if using other y_val
        ax = plt.subplot(pos)

    transaction_df = extract_transactions(results)
    if not transaction_df.empty:
        buy_df = transaction_df[transaction_df["amount"] > 0]
        sell_df = transaction_df[transaction_df["amount"] < 0]
        ax.scatter(
            buy_df.index.to_pydatetime(),
            results.loc[buy_df.index, y_val],
            marker="^",
            s=100,
            c="green",
            label="",
        )
        ax.scatter(
            sell_df.index.to_pydatetime(),
            results.loc[sell_df.index, y_val],
            marker="v",
            s=100,
            c="red",
            label="",
        )
Beispiel #4
0
def analyze(context, perf):
    stats = get_pretty_stats(perf)
    print('the algo stats:\n{}'.format(stats))
    # Get the base_currency that was passed as a parameter to the simulation
    exchange = list(context.exchanges.values())[0]
    base_currency = exchange.quote_currency.upper()

    # First chart: Plot portfolio value using base_currency
    ax1 = plt.subplot(411)
    perf.loc[:, ['portfolio_value']].plot(ax=ax1)
    ax1.legend_.remove()
    ax1.set_ylabel('Portfolio Value\n({})'.format(base_currency))
    start, end = ax1.get_ylim()
    ax1.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    ax2 = plt.subplot(412, sharex=ax1)
    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()
Beispiel #5
0
def analyze(context, results):
    ax1 = plt.subplot(611)
    results.loc[:, ['portfolio_value']].plot(ax=ax1)

    ax2 = plt.subplot(612, sharex=ax1)
    results.loc[:, ['sLRI']].plot(ax=ax2)
    results.loc[:, ['lLRI']].plot(ax=ax2)

    ax3 = plt.subplot(613, sharex=ax1)
    results.loc[:, ['price']].plot(ax=ax3, label='Price')
    ax3.legend_.remove()
    start, end = ax3.get_ylim()
    ax3.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    transaction_df = extract_transactions(results)
    if not transaction_df.empty:
        buy_df = transaction_df[transaction_df['amount'] > 0]
        sell_df = transaction_df[transaction_df['amount'] < 0]
        ax3.scatter(buy_df.index.to_pydatetime(),
                    results.loc[buy_df.index, 'price'],
                    marker='^',
                    s=100,
                    c='green',
                    label='')
        ax3.scatter(sell_df.index.to_pydatetime(),
                    results.loc[sell_df.index, 'price'],
                    marker='v',
                    s=100,
                    c='red',
                    label='')

    plt.show()
    print(results)
Beispiel #6
0
def analyze(context, perf):
    import matplotlib.pyplot as plt
    log.info('the stats: {}'.format(get_pretty_stats(perf)))

    # The base currency of the algo exchange
    base_currency = list(context.exchanges.values())[0].base_currency.upper()

    # Plot the portfolio value over time.
    ax1 = plt.subplot(611)
    perf.loc[:, 'portfolio_value'].plot(ax=ax1)
    ax1.set_ylabel('Portfolio Value ({})'.format(base_currency))

    # Plot the price increase or decrease over time.
    ax2 = plt.subplot(612, sharex=ax1)
    perf.loc[:, 'price'].plot(ax=ax2, label='Price')

    ax2.set_ylabel('{asset} ({base})'.format(
        asset=context.asset.symbol, base=base_currency
    ))

    transaction_df = extract_transactions(perf)
    if not transaction_df.empty:
        buy_df = transaction_df[transaction_df['amount'] > 0]
        sell_df = transaction_df[transaction_df['amount'] < 0]
        ax2.scatter(
            buy_df.index.to_pydatetime(),
            perf.loc[buy_df.index, 'price'],
            marker='^',
            s=100,
            c='green',
            label=''
        )
        ax2.scatter(
            sell_df.index.to_pydatetime(),
            perf.loc[sell_df.index, 'price'],
            marker='v',
            s=100,
            c='red',
            label=''
        )

    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
Beispiel #7
0
def analyze(context, perf):
    # Get the base_currency that was passed as a parameter to the simulation
    exchange = list(context.exchanges.values())[0]
    base_currency = exchange.base_currency.upper()

    # First chart: Plot portfolio value using base_currency
    ax1 = plt.subplot(411)
    perf.loc[:, ['portfolio_value']].plot(ax=ax1)
    ax1.legend_.remove()
    ax1.set_ylabel('Portfolio Value\n({})'.format(base_currency))
    start, end = ax1.get_ylim()
    ax1.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    # Second chart: Plot asset price, moving averages and buys/sells
    ax2 = plt.subplot(412, sharex=ax1)
    perf.loc[:, [
        'price', 'fastL', 'fastLC', 'fastS', 'fastSC', 'slowL', 'slowLC',
        'slowS', 'slowSC'
    ]].plot(ax=ax2, label='Price')
    ax2.legend_.remove()
    ax2.set_ylabel('{asset}\n({base})'.format(asset=context.coin.symbol,
                                              base=base_currency))
    start, end = ax2.get_ylim()
    ax2.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    transaction_df = extract_transactions(perf)
    if not transaction_df.empty:
        buy_df = transaction_df[transaction_df['amount'] > 0]
        sell_df = transaction_df[transaction_df['amount'] < 0]
        ax2.scatter(buy_df.index.to_pydatetime(),
                    perf.loc[buy_df.index, 'price'],
                    marker='^',
                    s=100,
                    c='green',
                    label='')
        ax2.scatter(sell_df.index.to_pydatetime(),
                    perf.loc[sell_df.index, 'price'],
                    marker='v',
                    s=100,
                    c='red',
                    label='')

    # Third chart: Compare percentage change between our portfolio
    # and the price of the asset
    ax3 = plt.subplot(413, sharex=ax1)
    perf.loc[:, ['algorithm_period_return']].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()
Beispiel #8
0
def analyze(context, perf):
    import matplotlib.pyplot as plt
    log.info('the stats: {}'.format(get_pretty_stats(perf)))

    # The quote currency of the algo exchange
    quote_currency = list(context.exchanges.values())[0].quote_currency.upper()

    # Plot the portfolio value over time.
    ax1 = plt.subplot(611)
    perf.loc[:, 'portfolio_value'].plot(ax=ax1)
    ax1.set_ylabel('Portfolio Value ({})'.format(quote_currency))

    # Plot the price increase or decrease over time.
    ax2 = plt.subplot(612, sharex=ax1)
    perf.loc[:, 'price'].plot(ax=ax2, label='Price')

    ax2.set_ylabel('{asset} ({quote})'.format(
        asset=context.asset.symbol, quote=quote_currency
    ))

    transaction_df = extract_transactions(perf)
    if not transaction_df.empty:
        buy_df = transaction_df[transaction_df['amount'] > 0]
        sell_df = transaction_df[transaction_df['amount'] < 0]
        ax2.scatter(
            buy_df.index.to_pydatetime(),
            perf.loc[buy_df.index, 'price'],
            marker='^',
            s=100,
            c='green',
            label=''
        )
        ax2.scatter(
            sell_df.index.to_pydatetime(),
            perf.loc[sell_df.index, 'price'],
            marker='v',
            s=100,
            c='red',
            label=''
        )

    ax4 = plt.subplot(613, sharex=ax1)
    perf.loc[:, 'cash'].plot(
        ax=ax4, label='Quote Currency ({})'.format(quote_currency)
    )
    ax4.set_ylabel('Cash ({})'.format(quote_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
def analyze(context, perf):
    # get the quote_currency that was passed as a parameter to the simulation
    exchange = list(context.exchanges.values())[0]
    quote_currency = exchange.base_currency.upper()

    # first chart: portfolio value
    ax1 = plt.subplot(411)
    perf.loc[:, ['portfolio_value']].plot(ax=ax1)
    ax1.legend_.remove()
    ax1.set_ylabel('Portfolio Value\n({})'.format(quote_currency))
    start, end = ax1.get_ylim()
    ax1.yaxis.set_ticks(np.arange(start, end, 30))

    # second chart: asset price, buys & sells
    ax2 = plt.subplot(412, sharex=ax1)
    perf.loc[:, ['price']].plot(ax=ax2, label='Price')
    ax2.legend_.remove()
    ax2.set_ylabel('{asset}\n({quote})'.format(asset=context.asset.symbol,
                                               quote=quote_currency))
    start, end = ax2.get_ylim()
    ax2.yaxis.set_ticks(np.arange(start, end, 300))

    transaction_df = extract_transactions(perf)
    if not transaction_df.empty:
        buy_df = transaction_df[transaction_df['amount'] > 0]
        sell_df = transaction_df[transaction_df['amount'] < 0]
        ax2.scatter(buy_df.index.to_pydatetime(),
                    perf.loc[buy_df.index, 'price'],
                    marker='^',
                    s=50,
                    c='green',
                    label='')
        ax2.scatter(sell_df.index.to_pydatetime(),
                    perf.loc[sell_df.index, 'price'],
                    marker='v',
                    s=50,
                    c='red',
                    label='')

    # third chart: relative strength index
    ax3 = plt.subplot(413, sharex=ax1)
    perf.loc[:, ['RSI']].plot(ax=ax3)
    plt.axhline(y=30, linestyle='dotted', color='grey')
    plt.axhline(y=70, linestyle='dotted', color='grey')
    ax3.legend_.remove()
    ax3.set_ylabel('RSI')
    start, end = ax3.get_ylim()
    ax3.yaxis.set_ticks(np.arange(0, 100, 10))

    # fourth chart: percentage return of the algorithm vs holding
    ax4 = plt.subplot(414, sharex=ax1)
    perf.loc[:, ['algorithm_period_return', 'price_change']].plot(ax=ax4)
    ax4.legend_.remove()
    ax4.set_ylabel('Percent Change')
    start, end = ax4.get_ylim()
    ax4.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    plt.show()
Beispiel #10
0
def analyze(context, perf):
    stats = get_pretty_stats(perf)
    print('the algo stats:\n{}'.format(stats))
    # Get the base_currency that was passed as a parameter to the simulation
    exchange = list(context.exchanges.values())[0]
    quote_currency = exchange.quote_currency.upper()

    # First chart: Plot portfolio value using base_currency
    ax1 = plt.subplot(411)
    perf.loc[:, ['portfolio_value']].plot(ax=ax1)
    ax1.legend_.remove()
    ax1.set_ylabel('Portfolio Value\n({})'.format(quote_currency))
    start, end = ax1.get_ylim()
    ax1.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    ax2 = plt.subplot(412, sharex=ax1)
    perf.loc[:, ['price']].plot(ax=ax2, label='Price')
    ax2.legend_.remove()
    ax2.set_ylabel('{asset}\n({base})'.format(asset=context.asset.symbol,
                                              base=quote_currency))
    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, 'price'],
                    marker='x',
                    s=150,
                    c='black',
                    label='')

    # Plot our cash
    ax3 = plt.subplot(413, 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))

    # Plot % change in look back period
    percent_change_data = perf.loc[:, ['percent_change']]
    pos_percent_change = percent_change_data.copy()
    neg_percent_change = percent_change_data.copy()

    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']].plot(ax=ax4, color='g')

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

    ax4.set_ylabel('% change 28 d\n({})'.format(quote_currency))
    start, end = ax4.get_ylim()
    ax4.yaxis.set_ticks(np.arange(start, end, end / 5))
    ax4.legend_.remove()

    plt.show()
Beispiel #11
0
def analyze(context, perf):
    # 保存交易记录
    perf.to_csv('./shuanjunxian.csv')

    # 获取交易所的计价货币
    exchange = list(context.exchanges.values())[0]
    quote_currency = exchange.quote_currency.upper()

    # 可视化资产值
    ax1 = plt.subplot(411)
    perf['portfolio_value'].plot(ax=ax1)
    ax1.set_ylabel('portfolio value]\n({})'.format(quote_currency))
    start, end = ax1.get_ylim()
    ax1.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    # 可视化货币价格,均线,买入卖出点
    ax2 = plt.subplot(412, sharex=ax1)
    perf[['price', 'short_mavg', 'long_mavg']].plot(ax=ax2)
    ax2.set_ylabel('{asset}\n({quote})'.format(asset=context.asset.symbol,
                                               quote=quote_currency))
    start, end = ax2.get_ylim()
    ax2.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))
    # 提取交易时间点
    transaction_df = extract_transactions(perf)
    if not transaction_df.empty:
        buy_df = transaction_df[transaction_df['amount'] > 0]
        sell_df = transaction_df[transaction_df['amount'] < 0]
        ax2.scatter(buy_df.index.to_pydatetime(),
                    perf.loc[buy_df.index, 'price'],
                    marker='^',
                    s=100,
                    c='green',
                    label='')
        ax2.scatter(sell_df.index.to_pydatetime(),
                    perf.loc[sell_df.index, 'price'],
                    marker='v',
                    s=100,
                    c='red',
                    label='')

    # 绘制价格变化率和资产变化率
    ax3 = plt.subplot(413, sharex=ax1)
    perf[['algorithm_period_return', 'price_change']].plot(ax=ax3)
    ax3.set_ylabel('percent change')
    start, end = ax3.get_ylim()
    ax3.yaxis.set_ticks(np.arange(0, end, end / 5))

    # 可视化资产数量
    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.tight_layout()
    plt.show()
Beispiel #12
0
    def analyze(context, perf):
        set_print_settings()

        transaction_df = extract_transactions(perf)
        print('the transactions:\n{}'.format(transaction_df))

        orders_df = extract_orders(perf)
        print('the orders:\n{}'.format(orders_df))

        stats = get_pretty_stats(perf, show_tail=False, num_rows=5)
        print('the stats:\n{}'.format(stats))
        pass
Beispiel #13
0
    def analyze(context, perf):
        set_print_settings()

        transaction_df = extract_transactions(perf)
        print('the transactions:\n{}'.format(transaction_df))

        orders_df = extract_orders(perf)
        print('the orders:\n{}'.format(orders_df))

        stats = get_pretty_stats(perf, show_tail=False, num_rows=5)
        print('the stats:\n{}'.format(stats))
        pass
Beispiel #14
0
def analyze(context, perf):

    # Get the base_currency that was passed as a parameter to the simulation
    exchange = list(context.exchanges.values())[0]
    base_currency = exchange.base_currency.upper()

    # First chart: Plot portfolio value using base_currency
    ax1 = plt.subplot(411)
    perf.loc[:, ["portfolio_value"]].plot(ax=ax1)
    ax1.legend_.remove()
    ax1.set_ylabel("Portfolio Value\n({})".format(base_currency))
    start, end = ax1.get_ylim()
    ax1.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    # Second chart: Plot asset price, moving averages and buys/sells
    ax2 = plt.subplot(412, sharex=ax1)
    perf.loc[:, ["price"]].plot(ax=ax2, label="Price")
    ax2.legend_.remove()
    ax2.set_ylabel(
        "{asset}\n({base})".format(asset=context.asset.symbol, base=base_currency)
    )
    start, end = ax2.get_ylim()
    ax2.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    transaction_df = extract_transactions(perf)
    if not transaction_df.empty:
        buy_df = transaction_df[transaction_df["amount"] > 0]
        sell_df = transaction_df[transaction_df["amount"] < 0]
        ax2.scatter(
            buy_df.index.to_pydatetime(),
            perf.loc[buy_df.index, "price"],
            marker="^",
            s=100,
            c="green",
            label="",
        )
        ax2.scatter(
            sell_df.index.to_pydatetime(),
            perf.loc[sell_df.index, "price"],
            marker="v",
            s=100,
            c="red",
            label="",
        )

    plt.show()
def analyze(context, perf):
    # Get the base_currency that was passed as a parameter to the simulation
    exchange = list(context.exchanges.values())[0]
    base_currency = exchange.base_currency.upper()

    # First chart: Plot portfolio value using base_currency
    ax1 = plt.subplot(311)
    perf.loc[:, ['portfolio_value']].plot(ax=ax1)
    ax1.legend_.remove()
    ax1.set_ylabel('Portfolio Value\n({})'.format(base_currency))
    start, end = ax1.get_ylim()
    ax1.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    ax2 = plt.subplot(312, sharex=ax1)
    perf.loc[:, ['price']].plot(
        ax=ax2,
        label='Price')
    ax2.legend_.remove()
    ax2.set_ylabel('{asset}\n({base})'.format(
        asset=context.asset.symbol,
        base=base_currency
    ))
    start, end = ax2.get_ylim()
    ax2.yaxis.set_ticks(np.arange(start, 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, '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(base_currency))
    start, end = ax3.get_ylim()
    ax3.yaxis.set_ticks(np.arange(0, end, end / 5))

    plt.show()
Beispiel #16
0
def analyze(context, perf):
    # Get the quote_currency that was passed as a parameter to the simulation
    exchange = list(context.exchanges.values())[0]
    quote_currency = exchange.quote_currency.upper()

    # First chart: Plot portfolio value using quote_currency
    ax1 = plt.subplot(211)
    perf.loc[:, ['portfolio_value']].plot(ax=ax1)
    ax1.legend_.remove()
    ax1.set_ylabel('Portfolio Value\n({})'.format(quote_currency))
    start, end = ax1.get_ylim()
    ax1.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    # Second chart: Plot asset price, moving averages and buys/sells
    ax2 = plt.subplot(212, sharex=ax1)
    perf.loc[:, ['price', 'short_mavg', 'long_mavg']].plot(ax=ax2,
                                                           label='Price')
    ax2.legend_.remove()
    ax2.set_ylabel('{asset}\n({quote})'.format(asset=context.asset.symbol,
                                               quote=quote_currency))
    start, end = ax2.get_ylim()
    ax2.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    transaction_df = extract_transactions(perf)
    if not transaction_df.empty:
        buy_df = transaction_df[transaction_df['amount'] > 0]
        sell_df = transaction_df[transaction_df['amount'] < 0]
        ax2.scatter(buy_df.index.to_pydatetime(),
                    perf.loc[buy_df.index, 'price'],
                    marker='^',
                    s=100,
                    c='green',
                    label='')
        ax2.scatter(sell_df.index.to_pydatetime(),
                    perf.loc[sell_df.index, 'price'],
                    marker='v',
                    s=100,
                    c='red',
                    label='')
    plt.show()
Beispiel #17
0
    def mark_purchases(self, ax):
        """
        Marks the purchases made

        Args:
                ax (matplotlib.pyplot.subplot) Subplot
        """

        transaction_df = extract_transactions(self.perf)
        if not transaction_df.empty:
            buy_df = transaction_df[transaction_df['amount'] > 0]
            sell_df = transaction_df[transaction_df['amount'] < 0]
            ax.scatter(buy_df.index.to_pydatetime(),
                       self.perf.loc[buy_df.index, 'price'],
                       marker='^',
                       s=20,
                       c='green',
                       label='')
            ax.scatter(sell_df.index.to_pydatetime(),
                       self.perf.loc[sell_df.index, 'price'],
                       marker='v',
                       s=20,
                       c='red',
                       label='')
def analyze(context, perf):
    exchange = list(context.exchanges.values())[0]
    quote_currency = exchange.quote_currency.upper()

    #  print(perf)

    #  1st graph
    ax1 = plt.subplot(411)
    perf.loc[:, ['portfolio_value']].plot(ax=ax1)
    ax1.legend_.remove()
    ax1.set_title("Portfolio Value ({})".format(quote_currency), rotation=0)
    start, end = ax1.get_ylim()

    ax1.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    # Second graph
    ax2 = plt.subplot(412, sharex=ax1)
    perf.loc[:, ['poloniex_price']].plot(ax=ax2, label='Price')
    ax2.legend_.remove()
    ax2.set_title('Price ({asset} / {quote})'.format(
        asset=context.asset.symbol, quote=quote_currency),
                  rotation=0)
    start, end = ax2.get_ylim()
    #  ax2.yaxis.set_ticks(np.arange(floor(start), ceil(end), 300))
    ax2.yaxis.set_ticks(np.arange(start, end, (start - end) / 5))
    ax2.set_title('Poloniex Price', rotation=0)

    transaction_df = extract_transactions(perf)
    if not transaction_df.empty:
        buy_df = transaction_df[transaction_df['amount'] > 0]
        sell_df = transaction_df[transaction_df['amount'] < 0]
        ax2.scatter(buy_df.index.to_pydatetime(),
                    perf.loc[buy_df.index, 'poloniex_price'],
                    marker='^',
                    s=50,
                    c='green',
                    label='')
        ax2.scatter(sell_df.index.to_pydatetime(),
                    perf.loc[sell_df.index, 'poloniex_price'],
                    marker='v',
                    s=50,
                    c='red',
                    label='')

    ax3 = plt.subplot(413, sharex=ax1)
    perf.loc[:, ['binance_price']].plot(ax=ax3, label='Price')
    ax3.legend_.remove()
    ax3.set_title('Price ({asset} / {quote})'.format(
        asset=context.asset.symbol, quote=quote_currency),
                  rotation=0)
    start, end = ax3.get_ylim()
    #  ax2.yaxis.set_ticks(np.arange(floor(start), ceil(end), 300))
    ax3.yaxis.set_ticks(np.arange(start, end, (start - end) / 5))
    ax3.set_title('Binance Price', rotation=0)

    transaction_df = extract_transactions(perf)
    if not transaction_df.empty:
        buy_df = transaction_df[transaction_df['amount'] > 0]
        sell_df = transaction_df[transaction_df['amount'] < 0]
        ax3.scatter(buy_df.index.to_pydatetime(),
                    perf.loc[buy_df.index, 'binance_price'],
                    marker='^',
                    s=50,
                    c='green',
                    label='')
        ax3.scatter(sell_df.index.to_pydatetime(),
                    perf.loc[sell_df.index, 'binance_price'],
                    marker='v',
                    s=50,
                    c='red',
                    label='')

    # Third graph (cash)
    #  ax3 = plt.subplot(513, sharex=ax1)
    #  perf.cash.plot(ax=ax3)
    #  ax3.set_title('Cash ({})'.format(quote_currency), rotation=0)

    ax4 = plt.subplot(414, sharex=ax1)
    perf.max_drawdown.plot(ax=ax4, kind='area', color='coral', alpha=0.7)
    ax4.set_title('Max drawdown', rotation=0)
    ax4.set_ylim(-1.0, 0)

    #  perf[[
    #  'treasury',
    #  'algorithm',
    #  'benchmark',
    #  ]] = perf[[
    #  'treasury_period_return',
    #  'algorithm_period_return',
    #  'benchmark_period_return',
    #  ]]
    #
    #  ax5 = plt.subplot(515, sharex=ax1)
    #  perf[[
    #  'treasury',
    #  'algorithm',
    #  'benchmark',
    #  ]].plot(ax=ax5)
    #  ax5.set_ylabel('Percent Change')

    plt.savefig("arbitrage.png")

    #  fig = plt.figure()
    #  ax1 = plt.subplot(311)
    #  perf.portfolio_value.plot(ax=ax1)
    #
    #  ax2 = plt.subplot(312, sharex=ax1)
    #  perf.benchmark_period_return.plot(ax=ax2)

    #  print(perf.columns)

    #  ax3 = plt.subplot(313, sharex=ax1)
    #  perf.alpha.plot(ax=ax3)

    plt.show()

    print("Starting Cash: $", perf.starting_cash.iloc[0])
    print("Ending portfolio value: $", perf.portfolio_value.iloc[-1])
    print("Cash: $", perf.cash.iloc[-1])
    print("Ending cash: $", perf.ending_cash.iloc[-1])
    print("Max Drawdown: ", perf.max_drawdown.min() * 100, "%")
    print("Algorithm Period Return: ",
          perf.algorithm_period_return.iloc[-1] * 100, "%")
    print("Pnl $", perf.pnl.sum())

    print(get_pretty_stats(perf))
def analyze(context, perf):
    # Get the base_currency that was passed as a parameter to the simulation
    exchange = list(context.exchanges.values())[0]
    base_currency = exchange.base_currency.upper()

    # First chart: Plot portfolio value using base_currency
    ax1 = plt.subplot(411)
    perf.loc[:, ['portfolio_value']].plot(ax=ax1)
    ax1.legend_.remove()
    ax1.set_ylabel('Portfolio Value\n({})'.format(base_currency))
    start, end = ax1.get_ylim()
    ax1.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    # Second chart: Plot asset price, moving averages and buys/sells
    ax2 = plt.subplot(412, sharex=ax1)
    perf.loc[:, ['price', 'short_mavg', 'long_mavg']].plot(
        ax=ax2,
        label='Price')
    ax2.legend_.remove()
    ax2.set_ylabel('{asset}\n({base})'.format(
        asset=context.asset.symbol,
        base=base_currency
    ))
    start, end = ax2.get_ylim()
    ax2.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    transaction_df = extract_transactions(perf)
    if not transaction_df.empty:
        buy_df = transaction_df[transaction_df['amount'] > 0]
        sell_df = transaction_df[transaction_df['amount'] < 0]
        ax2.scatter(
            buy_df.index.to_pydatetime(),
            perf.loc[buy_df.index, 'price'],
            marker='^',
            s=100,
            c='green',
            label=''
        )
        ax2.scatter(
            sell_df.index.to_pydatetime(),
            perf.loc[sell_df.index, 'price'],
            marker='v',
            s=100,
            c='red',
            label=''
        )

    # Third chart: Compare percentage change between our portfolio
    # and the price of the asset
    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()
Beispiel #20
0
def analyze(context, perf):
    # Get the base_currency that was passed as a parameter to the simulation
    exchange = list(context.exchanges.values())[0]
    base_currency = exchange.base_currency.upper()

    # First chart: Plot portfolio value using base_currency
    ax1 = plt.subplot(611)
    perf.loc[:, ["portfolio_value"]].plot(ax=ax1)
    ax1.legend_.remove()
    ax1.set_ylabel("Portfolio Value\n({})".format(base_currency))
    start, end = ax1.get_ylim()
    ax1.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    # Second chart: Plot asset price, moving averages and buys/sells
    ax2 = plt.subplot(612, sharex=ax1)
    perf.loc[:, ["price", "short_mavg", "long_mavg"]].plot(ax=ax2,
                                                           label="Price")
    ax2.legend_.remove()
    ax2.set_ylabel("{asset}\n({base})".format(asset=context.asset.symbol,
                                              base=base_currency))
    start, end = ax2.get_ylim()
    ax2.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    transaction_df = extract_transactions(perf)
    if not transaction_df.empty:

        buy_df = transaction_df.loc[transaction_df["amount"] > 0]
        sell_df = transaction_df.loc[transaction_df["amount"] < 0]

        log.info("Buy DF: \n {} ".format(buy_df))

        log.info("Sell  DF: \n {} ".format(sell_df))
        ax2.scatter(
            buy_df.index.to_pydatetime(),
            perf.loc[buy_df.index, "price"],
            marker="^",
            s=100,
            c="green",
            label="",
        )
        ax2.scatter(
            sell_df.index.to_pydatetime(),
            perf.loc[sell_df.index, "price"],
            marker="v",
            s=100,
            c="red",
            label="",
        )

    # Third chart: Compare percentage change between our portfolio
    # and the price of the asset
    ax3 = plt.subplot(613, 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(614, 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))

    ax6 = plt.subplot(615, sharex=ax1)
    perf.loc[:, "rsi"].plot(ax=ax6, label="RSI")
    ax6.set_ylabel("RSI")
    start, end = ax6.get_ylim()
    ax6.yaxis.set_ticks(np.arange(0, end, end / 5))

    plt.show()
def analyze(context, perf):
    #print("perf.max_drawdown=", perf.max_drawdown)
    empyrical_max_drawdown = max_drawdown(perf.algorithm_period_return)
    print("empyrical_max_drawdown = ", empyrical_max_drawdown)

    empyrical_tail_ratio = tail_ratio(perf.algorithm_period_return)
    print("empyrical_tail_ratio = ", empyrical_tail_ratio)

    empyrical_sharpe_ratio = sharpe_ratio(perf.algorithm_period_return)
    print("empyrical_sharpe_ratio = ", empyrical_sharpe_ratio)

    empyrical_alpha_beta = alpha_beta(perf.algorithm_period_return,
                                      perf.benchmark_period_return)
    print("empyrical_alpha_beta = ", empyrical_alpha_beta)

    #cum_returns(perf)
    # Save results in CSV file
    filename = "csvoutput"
    perf.to_csv(filename + '.csv')

    filename_orders = "orders_output"

    perf0 = perf[['orders']]
    perf1 = perf0[perf0['orders'].apply(len) > 0]

    perf2 = pd.DataFrame(perf1['orders'])
    #perf2 = pd.DataFrame([x for x in perf1['orders']])
    #print(perf1[['orders',-1]].head(n=5))
    #convert list of dictionaries to dictionary
    perf2["ordersd"] = pd.Series(perf2["orders"].str[0])
    print(perf2["ordersd"].head(70))

    #extracting orders dictionary to multiple columns
    perf2 = pd.DataFrame([x for x in perf2['ordersd']])

    #unpack(perf2, 'ordersd')
    perf2.to_csv(filename_orders + '.csv')

    exchange = list(context.exchanges.values())[0]
    base_currency = exchange.base_currency.upper()

    axl = plt.subplot(411)
    perf.loc[:, ['portfolio_value']].plot(ax=axl)
    axl.legend_.remove()
    axl.set_ylabel('Portfolio Value\n({})'.format(base_currency))
    start, end = axl.get_ylim()
    axl.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    ax2 = plt.subplot(412, sharex=axl)
    perf.loc[:, ['price', 'short_ema', 'long_ema']].plot(ax=ax2, label='Price')
    ax2.legend_.remove()
    ax2.set_ylabel('{asset}\n({base})'.format(asset=context.asset.symbol,
                                              base=base_currency))
    start, end = ax2.get_ylim()
    ax2.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    transaction_df = extract_transactions(perf)
    if not transaction_df.empty:
        buy_df = transaction_df[transaction_df['amount'] > 0]
        sell_df = transaction_df[transaction_df['amount'] < 0]
        ax2.scatter(buy_df.index.to_pydatetime(),
                    perf.loc[buy_df.index, 'price'],
                    marker='^',
                    s=100,
                    c='green',
                    label='')
        ax2.scatter(sell_df.index.to_pydatetime(),
                    perf.loc[sell_df.index, 'price'],
                    marker='v',
                    s=100,
                    c='red',
                    label='')

    ax3 = plt.subplot(413, sharex=axl)
    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(0, end, (end - start) / 5))

    ax4 = plt.subplot(414, sharex=axl)
    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()
Beispiel #22
0
def analyze(context=None, results=None):
    from plotly.offline import plot
    import plotly.graph_objs as go

    # Сохраним результаты в csv формате
    results.to_csv('catalyst_portfolio.csv')

    trans = extract_transactions(results)
    buys = trans[trans['amount'] > 0]
    sells = trans[trans['amount'] < 0]

    trans.to_csv('transaction.csv')
    buys.to_csv('buys.csv')
    sells.to_csv('sells.csv')
    # Построение графика курсов акцивов
    trace = go.Candlestick(
        x=results.index,
        open=results.open,
        high=results.high,
        low=results.low,
        close=results.close,
        increasing=dict(line=dict(width=1, color='#17BECF')),
        decreasing=dict(line=dict(width=1, color='#7F7F7F')),
        name='Курсы {}'.format(context.asset.asset_name),
        yaxis='y2')

    # График короткой скользящей средней
    short_window = go.Scatter(x=results.short_mavg.index,
                              y=results.short_mavg,
                              line=dict(width=1,
                                        color='rgba(60, 190, 60, 1.0)'),
                              name='40-дневная SMA',
                              yaxis='y2')

    # График длинной скользящей средней
    long_window = go.Scatter(x=results.long_mavg.index,
                             y=results.long_mavg,
                             line=dict(width=1,
                                       color='rgba(180, 60, 170, 1.0)'),
                             name='100-дневная SMA',
                             yaxis='y2')

    # График покупок акцивов
    buy = go.Scatter(
        x=results.short_mavg[buys.index].index,
        y=results.short_mavg[buys.index],
        mode='markers',
        marker=dict(
            symbol="triangle-up",
            size=8,
            #         color='rgba(250, 128, 114, .9)',
            color='red',
            line=dict(width=1, color='rgba(0, 0, 0, 1.0)')),
        name='Покупка акцивов',
        yaxis='y2')

    # ПГрафик продажи акцивов
    sell = go.Scatter(x=results.short_mavg[sells.index].index,
                      y=results.short_mavg[sells.index],
                      mode='markers',
                      marker=dict(symbol="triangle-down",
                                  size=8,
                                  color='blue',
                                  line=dict(width=1, color='black')),
                      name='Продажа акцивов',
                      yaxis='y2')

    # График общего капитала при торгах
    capital_total = go.Scatter(x=results.portfolio_value.index,
                               y=results.portfolio_value,
                               line=dict(width=1, color='blue'),
                               name='Значение Portfolio в $',
                               yaxis='y1')

    # График позиций - покупок на фоне общего капитала
    capital_buy = go.Scatter(x=results.portfolio_value[buys.index].index,
                             y=results.portfolio_value[buys.index],
                             mode='markers',
                             marker=dict(symbol="triangle-up",
                                         size=8,
                                         color='red',
                                         line=dict(
                                             width=1,
                                             color='rgba(0, 0, 0, 1.0)')),
                             name='Покупка акцивов',
                             yaxis='y1')

    # График позиций - продаж на фоне общего капитала
    capital_sell = go.Scatter(x=results.portfolio_value[sells.index].index,
                              y=results.portfolio_value[sells.index],
                              mode='markers',
                              marker=dict(symbol="triangle-down",
                                          size=8,
                                          color='black',
                                          line=dict(width=1, color='blue')),
                              name='Продажа акцивов',
                              yaxis='y1')

    # Создадим список наших постоенных графиков
    data = [
        trace, short_window, long_window, buy, sell, capital_total,
        capital_buy, capital_sell
    ]

    # Настройки общего графика
    layout = go.Layout(
        paper_bgcolor='rgb(234, 233, 241)',
        plot_bgcolor='rgb(201, 187, 172)',
        title=
        'График бэк-теста стратегии Moving Average Crossover на данных биржи BitMex',
        titlefont=dict(family='Arial, sans-serif', size=26, color='black'),
        xaxis=dict(title='Дата',
                   titlefont=dict(family='Arial, sans-serif',
                                  size=18,
                                  color='black'),
                   rangeslider=dict(visible=True),
                   range=['2018-06-01 00:00:00', '2018-06-05 00:00:00'],
                   type='date'),
        yaxis=dict(title='Капитал $',
                   titlefont=dict(family='Arial, sans-serif',
                                  size=18,
                                  color='black'),
                   domain=[0, 0.47]),
        yaxis2=dict(title='Kурсы {} $'.format(context.asset.asset_name),
                    titlefont=dict(family='Arial, sans-serif',
                                   size=18,
                                   color='black'),
                    domain=[0.53, 1]))

    # В итоге сторим наш общийграфик (создаем html файл)
    figure = go.Figure(data=data, layout=layout)
    plot(figure, filename='pandas_analyze')
Beispiel #23
0
def analyze(context, perf):
    if not LIVE:
        # Get the base_currency that was passed as a parameter to the simulation
        exchange = list(context.exchanges.values())[0]

        log.info(
            "Total Profit: \n {} ".format(perf.loc[:, ["portfolio_value"]].iloc[-1])
        )

        base_currency = exchange.quote_currency.upper()
        fig = plt.figure(figsize=(18, 16), dpi=80, facecolor="w", edgecolor="k")

        # First chart: Plot portfolio value using base_currency
        ax1 = plt.subplot(611)
        perf.loc[:, ["portfolio_value"]].plot(ax=ax1)
        ax1.legend_.remove()
        ax1.set_ylabel("Portfolio Value\n({})".format(base_currency))
        start, end = ax1.get_ylim()
        ax1.xaxis.set_ticks(np.arange(start, end, (end - start) / 5))

        # Second chart: Plot asset price, value and buys/sells

        try:
            ax2 = plt.subplot(612, sharex=ax1)
            perf.loc[:, ["price_0", "vstop_0"]].plot(ax=ax2, label="Price + Vstop")
            ax2.legend_.remove()
            ax2.set_ylabel("Asset: \n({})".format(context.trading_pairs[0]))

            start, end = ax2.get_ylim()
            ax2.yaxis.set_ticks(np.arange(start, end, (end - start) / 10))

            # Second chart: Plot asset price, value and buys/sells
            ax3 = plt.subplot(613, sharex=ax1)
            perf.loc[:, ["price_1", "vstop_1"]].plot(ax=ax3, label="Price + Vstop")
            ax3.legend_.remove()
            ax3.set_ylabel("Asset: \n({})".format(context.trading_pairs[1]))

            start, end = ax3.get_ylim()
            ax3.yaxis.set_ticks(np.arange(start, end, (end - start) / 10))

            ax4 = plt.subplot(614, sharex=ax1)
            perf.loc[:, ["price_2", "vstop_2"]].plot(ax=ax4, label="Price + Vstop")
            ax4.legend_.remove()
            ax4.set_ylabel("Asset: \n({})".format(context.trading_pairs[2]))

            start, end = ax4.get_ylim()
            ax4.yaxis.set_ticks(np.arange(start, end, (end - start) / 10))
        except KeyError:
            log.info(f"SID: \n {KeyError} ")

        transaction_df = extract_transactions(perf)
        if not transaction_df.empty:
            try:
                transactions_0 = transaction_df["sid"] == context.assets[0].symbol
                transactions_0 = transaction_df.loc[transactions_0]
                transactions_1 = transaction_df["sid"] == context.assets[1].symbol
                transactions_1 = transaction_df.loc[transactions_1]
                transactions_2 = transaction_df["sid"] == context.assets[2].symbol
                transactions_2 = transaction_df.loc[transactions_2]
            except IndexError:
                log.info(f"SID: \n {IndexError} ")
            try:
                buy_df = transactions_0.loc[transactions_0["amount"] > 0]
                sell_df = transactions_0.loc[transactions_0["amount"] < 0]

                # temp hardcoded plotting should be based on # of assets
                ax2.scatter(
                    buy_df.index.to_pydatetime(),
                    perf.loc[buy_df.index, "price_0"],
                    marker="^",
                    s=100,
                    c="green",
                    label="",
                )
                ax2.scatter(
                    sell_df.index.to_pydatetime(),
                    perf.loc[sell_df.index, "price_0"],
                    marker="v",
                    s=100,
                    c="red",
                    label="",
                )

                buy_df = transactions_1.loc[transactions_1["amount"] > 0]
                sell_df = transactions_1.loc[transactions_1["amount"] < 0]
                ax3.scatter(
                    buy_df.index.to_pydatetime(),
                    perf.loc[buy_df.index, "price_1"],
                    marker="^",
                    s=100,
                    c="green",
                    label="",
                )
                ax3.scatter(
                    sell_df.index.to_pydatetime(),
                    perf.loc[sell_df.index, "price_1"],
                    marker="v",
                    s=100,
                    c="red",
                    label="",
                )

                buy_df = transactions_2.loc[transactions_2["amount"] > 0]
                sell_df = transactions_2.loc[transactions_2["amount"] < 0]
                ax4.scatter(
                    buy_df.index.to_pydatetime(),
                    perf.loc[buy_df.index, "price_2"],
                    marker="^",
                    s=100,
                    c="green",
                    label="",
                )
                ax4.scatter(
                    sell_df.index.to_pydatetime(),
                    perf.loc[sell_df.index, "price_2"],
                    marker="v",
                    s=100,
                    c="red",
                    label="",
                )
            except (KeyError, UnboundLocalError) as e:
                log.info(f"SID: \n {e} ")

        ax5 = plt.subplot(615, sharex=ax1)
        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()
Beispiel #24
0
	def plot(self, perf):
		if not self.context.plot_fig:
			return False
		plt.figure(figsize=(20,10))
		ax1 = plt.subplot(411)
		perf.loc[:, ['cmx_pnl']].plot(ax=ax1)
		ax1.legend_.remove()
		ax1.set_ylabel('pnl\n({})'.format(self.context.quote_currency))
		ymin, ymax = ax1.get_ylim()
		ax1.yaxis.set_ticks(np.arange(ymin, ymax, (ymax - ymin) / 4))

		# Second chart: Plot asset price, moving averages and buys/sells
		ax2 = plt.subplot(412, sharex=ax1)
		perf.loc[:, ['price', 'fair_price', 'invent_long_entry', 'invent_short_entry']].plot(
		    ax=ax2,
		    label='Price')
		ax2.legend_.remove()
		ax2.set_ylabel('price\n({})'.format(self.context.symbol_str))
		ymin, ymax = ax2.get_ylim()
		ax2.yaxis.set_ticks(np.arange(ymin, ymax, (ymax - ymin) / 4))

		transaction_df = extract_transactions(perf)
		try:
			if not transaction_df.empty:
				buy_df = transaction_df[transaction_df['amount'] > 0]
				sell_df = transaction_df[transaction_df['amount'] < 0]
				ax2.scatter(
							buy_df.index.to_pydatetime(),
							perf.loc[buy_df.index, 'price'],
							marker='^',
							s=100,
							c='green',
							label=''
							)
				ax2.scatter(
							sell_df.index.to_pydatetime(),
							perf.loc[sell_df.index, 'price'],
							marker='v',
							s=100,
							c='red',
							label=''
							)
		except Exception as e:
			self.context.cmx_logger.log_error(e)


		# Third chart: Compare percentage change between our portfolio
		# and the price of the asset
		ax3 = plt.subplot(413, sharex=ax1)
		perf.loc[:, ['algorithm_period_return', 'price_change']].plot(ax=ax3)
		ax3.legend_.remove()
		ax3.set_ylabel('pct change')
		ymin, ymax = ax3.get_ylim()
		ax3.yaxis.set_ticks(np.arange(ymin, ymax, (ymax - ymin) / 4))

		# Fourth chart: Plot our cash
		position_series = perf['positions'].map(lambda x: x[0]['amount'] if len(x) > 0 else 0)
		position_series -= self.context.risk_init_position if self.context.risk_init_position is not None else 0
		ax4 = plt.subplot(414, sharex=ax1)
		position_series.plot(ax = ax4)
		ax4.set_ylabel('position\n({})'.format(self.context.base_currency))
		ymin, ymax = ax4.get_ylim()
		ax4.yaxis.set_ticks(np.arange(ymin, ymax, (ymax - ymin) / 4))

		plt.savefig(self.context.plot_file, dpi = 300)
		self.context.cmx_logger.log_plot_info()
Beispiel #25
0
def analyze(context, perf):
    if not LIVE:
        # Get the base_currency that was passed as a parameter to the simulation
        exchange = list(context.exchanges.values())[0]

        print("Total return: " + str(perf.algorithm_period_return[-1] * 100))
        print("Sortino coef: " + str(perf.sortino[-1]))
        print("Max drawdown: " + str(np.min(perf.max_drawdown)))
        print("Alpha: " + str(perf.alpha[-1]))
        print("Beta: " + str(perf.beta[-1]))
        perf.to_csv("perf_" + str(context.assets[0].pair) + ".csv")

        base_currency = exchange.quote_currency.upper()
        fig = plt.figure(figsize=(18, 16),
                         dpi=80,
                         facecolor="w",
                         edgecolor="k")

        # First chart: Plot portfolio value using base_currency
        ax1 = plt.subplot(611)
        perf.loc[:, ["portfolio_value"]].plot(ax=ax1)
        ax1.legend_.remove()
        ax1.set_ylabel("Portfolio Value\n({})".format(base_currency))
        start, end = ax1.get_ylim()
        ax1.xaxis.set_ticks(np.arange(start, end, (end - start) / 5))

        # Second chart: Plot asset price, value and buys/sells

        try:
            ax2 = plt.subplot(612, sharex=ax1)
            perf.loc[:, ["price_0", "vstop_0"]].plot(ax=ax2,
                                                     label="Price + Vstop")
            ax2.legend_.remove()
            ax2.set_ylabel("Asset: \n({})".format(context.assets[0].pair))

            start, end = ax2.get_ylim()
            ax2.yaxis.set_ticks(np.arange(start, end, (end - start) / 10))

        except KeyError:
            log.info(f"SID: \n {KeyError} ")

        transaction_df = extract_transactions(perf)
        if not transaction_df.empty:
            try:
                transactions_0 = transaction_df["sid"] == context.assets[
                    0].symbol
                transactions_0 = transaction_df.loc[transactions_0]
            except IndexError:
                log.info(f"SID: \n {IndexError} ")
            try:
                buy_df = transactions_0.loc[transactions_0["amount"] > 0]
                sell_df = transactions_0.loc[transactions_0["amount"] < 0]

                # temp hardcoded plotting should be based on # of assets
                ax2.scatter(
                    buy_df.index.to_pydatetime(),
                    perf.loc[buy_df.index, "price_0"],
                    marker="^",
                    s=100,
                    c="green",
                    label="",
                )
                ax2.scatter(
                    sell_df.index.to_pydatetime(),
                    perf.loc[sell_df.index, "price_0"],
                    marker="v",
                    s=100,
                    c="red",
                    label="",
                )
            except (KeyError, UnboundLocalError) as e:
                log.info(f"SID: \n {e} ")

        plt.show()
Beispiel #26
0
def analyze(context, perf):
    # Summary output

    print("Total return: " + str(perf.algorithm_period_return[-1] * 100))
    print("Sortino coef: " + str(perf.sortino[-1]))
    print("Max drawdown: " + str(np.min(perf.max_drawdown)))
    print("Alpha: " + str(perf.alpha[-1]))
    print("Beta: " + str(perf.beta[-1]))
    perf.to_csv("perf_" + str(context.asset) + ".csv")

    f = plt.figure(figsize=(7.2, 7.2))

    # Plot performance
    ax1 = f.add_subplot(611)
    ax1.plot(perf.algorithm_period_return, "blue")
    ax1.plot(perf.benchmark_period_return, "red")
    ax1.set_title("Performance")
    ax1.set_xlabel("Time")
    ax1.set_ylabel("Return")

    # Plot price and renko price
    ax2 = f.add_subplot(612, sharex=ax1)
    ax2.plot(perf.price, "grey")
    ax2.plot(perf.renko_price, "yellow")
    ax2.set_title(context.asset)
    ax2.set_xlabel("Time")
    ax2.set_ylabel("Price")

    transaction_df = extract_transactions(perf)
    if not transaction_df.empty:
        try:
            transactions = transaction_df["sid"] == context.asset
            transactions = transaction_df.loc[transactions]
        except IndexError:
            log.info(f"SID: \n {IndexError} ")
        try:
            buy_df = transactions.loc[transactions["amount"] > 0]
            sell_df = transactions.loc[transactions["amount"] < 0]

            # temp hardcoded plotting should be based on # of assets
            ax2.scatter(
                buy_df.index.to_pydatetime(),
                perf.loc[buy_df.index, "price"],
                marker="^",
                s=100,
                c="green",
                label="",
            )
            ax2.scatter(
                sell_df.index.to_pydatetime(),
                perf.loc[sell_df.index, "price"],
                marker="v",
                s=100,
                c="red",
                label="",
            )
        except (KeyError, UnboundLocalError) as e:
            log.info(f"SID: \n {e} ")

    # Plot brick size
    ax3 = f.add_subplot(613, sharex=ax1)
    ax3.plot(perf.brick_size, "blue")
    xcoords = perf.index[perf.rebuilding_status == 1]
    for xc in xcoords:
        ax3.axvline(x=xc, color="red")
    ax3.set_title("Brick size and rebuilding status")
    ax3.set_xlabel("Time")
    ax3.set_ylabel("Size and Status")

    # Plot renko_price
    ax4 = f.add_subplot(614, sharex=ax1)
    ax4.plot(perf.num_created_bars, "green")
    ax4.set_title("Number of created Renko bars")
    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()
Beispiel #27
0
def tutorial_plt1(context, perf):
    # Get the quote_currency that was passed as a parameter to the simulation
    exchange = list(context.exchanges.values())[0]
    quote_currency = exchange.quote_currency.upper()
    rows = 1
    cols = 1

    # Second chart: Plot asset price, moving averages and buys/sells
    ax2 = plt.subplot(rows, cols, 1)
    perf.loc[:, ['price', 'short_mavg', 'long_mavg']].plot(ax=ax2,
                                                           label='Price')
    ax2.legend_.remove()
    ax2.set_ylabel('{asset}\n({quote})'.format(asset=context.asset.symbol,
                                               quote=quote_currency))
    start, end = ax2.get_ylim()
    ax2.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    transaction_df = extract_transactions(perf)
    if not transaction_df.empty:
        buy_df = transaction_df[transaction_df['amount'] > 0]
        sell_df = transaction_df[transaction_df['amount'] < 0]
        ax2.scatter(buy_df.index.to_pydatetime(),
                    perf.loc[buy_df.index, 'price'],
                    marker='^',
                    s=100,
                    c='green',
                    label='')
        ax2.scatter(sell_df.index.to_pydatetime(),
                    perf.loc[sell_df.index, 'price'],
                    marker='v',
                    s=100,
                    c='red',
                    label='')

    # First chart: Plot portfolio value using quote_currency
    # ax2 = plt.subplot(rows, cols, 1, sharex=ax1)
    # perf.loc[:, ['portfolio_value']].plot(ax=ax1)
    # ax1.legend_.remove()
    # ax1.set_ylabel('Portfolio Value\n({})'.format(quote_currency))
    # start, end = ax1.get_ylim()
    # ax1.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    # # Third chart: Compare percentage change between our portfolio
    # # and the price of the asset
    # ax3 = plt.subplot(rows, cols, 3, 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(rows, cols, 4, sharex=ax1)
    # perf.ending_cash.plot(ax=ax4)
    # ax4.set_ylabel('ending_cash\n({})'.format(quote_currency))
    # start, end = ax4.get_ylim()
    # ax4.yaxis.set_ticks(np.arange(0, end, end / 5))

    # plt.show()
    plt.gcf().set_size_inches(PLT_SIZE)
    plt.savefig("figures/tut1.png", bbox_inches='tight')
Beispiel #28
0
def plot_double(perf_a, perf_b, titles=['live', 'sim'], filepath=None):
    pnl_df = _concat(perf_a, perf_b, 'cmx_pnl')
    price_df = _concat(perf_a, perf_b, 'price')
    fair_df = _concat(perf_a, perf_b, 'fair_price')
    sig_long_df = _concat(perf_a, perf_b, 'invent_long_entry')
    sig_short_df = _concat(perf_a, perf_b, 'invent_short_entry')

    pos_a = perf_a['positions'].map(lambda x: x[0]['amount']
                                    if len(x) > 0 else 0)
    pos_b = perf_b['positions'].map(lambda x: x[0]['amount']
                                    if len(x) > 0 else 0)
    pos_df = _concat(pos_a, pos_b)

    return_df = _concat(perf_a, perf_b, 'algorithm_period_return')
    prc_chg_df = _concat(perf_a, perf_b, 'price_change')
    ###################################################################
    plt.figure(figsize=(20, 10))
    ax1 = plt.subplot(421)
    pnl_df['a'].plot(ax=ax1)
    ax1.set_ylabel('pnl\n(quote)')
    ymin = pnl_df.min().min()
    ymax = pnl_df.max().max()
    ax1.yaxis.set_ticks(np.arange(ymin, ymax, (ymax - ymin) / 5))
    ax1.set_title(titles[0])

    ax5 = plt.subplot(422, sharex=ax1)
    pnl_df['b'].plot(ax=ax5)
    ax5.set_ylabel('pnl\n(quote)')
    ax5.yaxis.set_ticks(np.arange(ymin, ymax, (ymax - ymin) / 5))
    ax5.set_title(titles[1])

    # Second chart: Plot asset price, moving averages and buys/sells
    ax2 = plt.subplot(423, sharex=ax1)
    df = pd.concat(
        [price_df['a'], fair_df['a'], sig_long_df['a'], sig_short_df['a']],
        axis=1)
    df.columns = [
        'price', 'fair_price', 'invent_long_entry', 'invent_short_entry'
    ]
    df.plot(ax=ax2, label='Price')
    ax2.legend_.remove()
    ax2.set_ylabel('price')
    ymin = df.min().min()
    ymax = df.max().max()
    ax2.yaxis.set_ticks(np.arange(ymin, ymax, (ymax - ymin) / 5))

    transaction_df = extract_transactions(perf_a)
    if transaction_df is not None and not transaction_df.empty:
        buy_df = transaction_df[transaction_df['amount'] > 0]
        sell_df = transaction_df[transaction_df['amount'] < 0]
        ax2.scatter(buy_df.index.to_pydatetime(),
                    perf_a.loc[buy_df.index, 'price'],
                    marker='^',
                    s=100,
                    c='green',
                    label='')
        ax2.scatter(sell_df.index.to_pydatetime(),
                    perf_a.loc[sell_df.index, 'price'],
                    marker='v',
                    s=100,
                    c='red',
                    label='')

    ax6 = plt.subplot(424, sharex=ax1)
    df = pd.concat(
        [price_df['b'], fair_df['b'], sig_long_df['b'], sig_short_df['b']],
        axis=1)
    df.columns = [
        'price', 'fair_price', 'invent_long_entry', 'invent_short_entry'
    ]
    df.plot(ax=ax6, label='Price')
    ax6.legend_.remove()
    ax6.set_ylabel('price')
    ax6.yaxis.set_ticks(np.arange(ymin, ymax, (ymax - ymin) / 5))

    transaction_df = extract_transactions(perf_b)
    if transaction_df is not None and not transaction_df.empty:
        buy_df = transaction_df[transaction_df['amount'] > 0]
        sell_df = transaction_df[transaction_df['amount'] < 0]
        ax6.scatter(buy_df.index.to_pydatetime(),
                    perf_b.loc[buy_df.index, 'price'],
                    marker='^',
                    s=100,
                    c='green',
                    label='')
        ax6.scatter(sell_df.index.to_pydatetime(),
                    perf_b.loc[sell_df.index, 'price'],
                    marker='v',
                    s=100,
                    c='red',
                    label='')

    # Third chart: Plot our position
    ax3 = plt.subplot(425, sharex=ax1)
    pos_df['a'].plot(ax=ax3)
    ax3.set_ylabel('position\n(base)')
    ymin = pos_df.min().min()
    ymax = pos_df.max().max()
    ax3.yaxis.set_ticks(np.arange(ymin, ymax, (ymax - ymin) / 5))

    ax7 = plt.subplot(426, sharex=ax1)
    pos_df['b'].plot(ax=ax7)
    ax7.set_ylabel('position\n(base)')
    ax7.yaxis.set_ticks(np.arange(ymin, ymax, (ymax - ymin) / 5))

    # Fourth chart: Compare percentage change between our portfolio
    # and the price of the asset
    ax4 = plt.subplot(427, sharex=ax1)
    df = pd.concat([return_df['a'], prc_chg_df['a']], axis=1)
    df.columns = ['algorithm_period_return', 'price_change']
    df.plot(ax=ax4)
    ax4.legend_.remove()
    ax4.set_ylabel('returns')
    ymin = df.min().min()
    ymax = df.max().max()
    ax4.yaxis.set_ticks(np.arange(ymin, ymax, (ymax - ymin) / 5))

    ax8 = plt.subplot(428, sharex=ax1)
    df = pd.concat([return_df['b'], prc_chg_df['b']], axis=1)
    df.columns = ['algorithm_period_return', 'price_change']
    df.plot(ax=ax8)
    ax8.legend_.remove()
    ax8.set_ylabel('returns')
    ax8.yaxis.set_ticks(np.arange(ymin, ymax, (ymax - ymin) / 5))

    if filepath is not None:
        folder = os.path.dirname(os.path.abspath(filepath))
        if not os.path.exists(folder):
            os.makedirs(folder)
        plt.savefig(filepath, dpi=300)


# perf_a = pd.read_pickle(r'C:\comics_data\xmreth-sim\record\xmreth-sim_local_backtest_1533773974.pickle')
# perf_b = pd.read_pickle(r'C:\comics_data\xmreth-sim\record\xmreth-sim_local_backtest_1533771766.pickle')
# plot_double(perf_a, perf_b, titles = ['a', 'b'], filepath = 'tmp.png')
def analyze(context=None, perf=None):
    end = time.time()
    log.info('elapsed time: {}'.format(end - context.start_time))

    import matplotlib.pyplot as plt
    # The base currency of the algo exchange
    base_currency = list(context.exchanges.values())[0].base_currency.upper()

    # Plot the portfolio value over time.
    ax1 = plt.subplot(611)
    perf.loc[:, 'portfolio_value'].plot(ax=ax1)
    ax1.set_ylabel('Portfolio\nValue\n({})'.format(base_currency))

    # Plot the price increase or decrease over time.
    ax2 = plt.subplot(612, sharex=ax1)
    perf.loc[:, 'price'].plot(ax=ax2, label='Price')

    ax2.set_ylabel('{asset}\n({base})'.format(
        asset=context.market.symbol, base=base_currency
    ))

    transaction_df = extract_transactions(perf)
    if not transaction_df.empty:
        buy_df = transaction_df[transaction_df['amount'] > 0]
        sell_df = transaction_df[transaction_df['amount'] < 0]
        ax2.scatter(
            buy_df.index.to_pydatetime(),
            perf.loc[buy_df.index.floor('1 min'), 'price'],
            marker='^',
            s=100,
            c='green',
            label=''
        )
        ax2.scatter(
            sell_df.index.to_pydatetime(),
            perf.loc[sell_df.index.floor('1 min'), 'price'],
            marker='v',
            s=100,
            c='red',
            label=''
        )

    ax4 = plt.subplot(613, sharex=ax1)
    perf.loc[:, 'cash'].plot(
        ax=ax4, label='Base Currency ({})'.format(base_currency)
    )
    ax4.set_ylabel('Cash\n({})'.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\nChange')

    ax6 = plt.subplot(615, sharex=ax1)
    perf.loc[:, 'rsi'].plot(ax=ax6, label='RSI')
    ax6.set_ylabel('RSI')
    ax6.axhline(context.RSI_OVERBOUGHT, color='darkgoldenrod')
    ax6.axhline(context.RSI_OVERSOLD, color='darkgoldenrod')

    if not transaction_df.empty:
        ax6.scatter(
            buy_df.index.to_pydatetime(),
            perf.loc[buy_df.index.floor('1 min'), 'rsi'],
            marker='^',
            s=100,
            c='green',
            label=''
        )
        ax6.scatter(
            sell_df.index.to_pydatetime(),
            perf.loc[sell_df.index.floor('1 min'), 'rsi'],
            marker='v',
            s=100,
            c='red',
            label=''
        )
    plt.legend(loc=3)
    start, end = ax6.get_ylim()
    ax6.yaxis.set_ticks(np.arange(0, end, end / 5))

    # Show the plot.
    plt.gcf().set_size_inches(18, 8)
    plt.show()
    pass
Beispiel #30
0
def analyze(context, perf): 
    #print("perf.max_drawdown=", perf.max_drawdown)
    empyrical_max_drawdown = max_drawdown(perf.algorithm_period_return)
    print("empyrical_max_drawdown = ", empyrical_max_drawdown)
    
    empyrical_tail_ratio = tail_ratio(perf.algorithm_period_return)
    print("empyrical_tail_ratio = ", empyrical_tail_ratio)
    
    empyrical_sharpe_ratio = sharpe_ratio(perf.algorithm_period_return)
    print("empyrical_sharpe_ratio = ", empyrical_sharpe_ratio)
    
    empyrical_alpha_beta = alpha_beta(perf.algorithm_period_return, perf.benchmark_period_return)
    print("empyrical_alpha_beta = ", empyrical_alpha_beta)    
    
    
    
    #cum_returns(perf)
    # Save results in CSV file
    filename = "csvoutput"
    perf.to_csv(filename + '.csv')      
    
    exchange = list(context.exchanges.values())[0]
    base_currency = exchange.base_currency.upper()
    
    axl = plt.subplot(411)
    perf.loc[:, ['portfolio_value']].plot(ax = axl)
    axl.legend_.remove()
    axl.set_ylabel('Portfolio Value\n({})'.format(base_currency))
    start, end = axl.get_ylim()
    axl.yaxis.set_ticks(np.arange(start, end, (end-start) / 5))
    
    ax2 = plt.subplot(412, sharex = axl)
    perf.loc[:,['price','short_ema','long_ema']].plot(ax = ax2, label = 'Price')
    ax2.legend_.remove()
    ax2.set_ylabel('{asset}\n({base})'.format(asset = context.asset.symbol, base = base_currency))
    start, end = ax2.get_ylim()
    ax2.yaxis.set_ticks(np.arange(start, end, (end-start) / 5))
    
    transaction_df = extract_transactions(perf)
    if not transaction_df.empty:
        buy_df = transaction_df[transaction_df['amount'] > 0]
        sell_df = transaction_df[transaction_df['amount'] < 0]
        ax2.scatter(buy_df.index.to_pydatetime(), perf.loc[buy_df.index, 'price'], marker = '^', s = 100, c = 'green', label = '')
        ax2.scatter(sell_df.index.to_pydatetime(), perf.loc[sell_df.index, 'price'], marker = 'v', s = 100, c = 'red', label = '')    
    
    
    ax3 = plt.subplot(413, sharex = axl)
    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(0, end, (end-start) / 5))
    
    
    
    
    ax4 = plt.subplot(414, sharex = axl)
    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()
Beispiel #31
0
def analyze(context=None, perf=None):
    end = time.time()
    log.info('elapsed time: {}'.format(end - context.start_time))

    import matplotlib.pyplot as plt
    # The quote currency of the algo exchange
    quote_currency = list(context.exchanges.values())[0].quote_currency.upper()

    # Plot the portfolio value over time.
    ax1 = plt.subplot(611)
    perf.loc[:, 'portfolio_value'].plot(ax=ax1)
    ax1.set_ylabel('Portfolio\nValue\n({})'.format(quote_currency))

    # Plot the price increase or decrease over time.
    ax2 = plt.subplot(612, sharex=ax1)
    perf.loc[:, 'price'].plot(ax=ax2, label='Price')

    ax2.set_ylabel('{asset}\n({quote})'.format(asset=context.market.symbol,
                                               quote=quote_currency))

    transaction_df = extract_transactions(perf)
    if not transaction_df.empty:
        buy_df = transaction_df[transaction_df['amount'] > 0]
        sell_df = transaction_df[transaction_df['amount'] < 0]
        ax2.scatter(buy_df.index.to_pydatetime(),
                    perf.loc[buy_df.index.floor('1 min'), 'price'],
                    marker='^',
                    s=100,
                    c='green',
                    label='')
        ax2.scatter(sell_df.index.to_pydatetime(),
                    perf.loc[sell_df.index.floor('1 min'), 'price'],
                    marker='v',
                    s=100,
                    c='red',
                    label='')

    ax4 = plt.subplot(613, sharex=ax1)
    perf.loc[:,
             'cash'].plot(ax=ax4,
                          label='Quote Currency ({})'.format(quote_currency))
    ax4.set_ylabel('Cash\n({})'.format(quote_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\nChange')

    ax6 = plt.subplot(615, sharex=ax1)
    perf.loc[:, 'rsi'].plot(ax=ax6, label='RSI')
    ax6.set_ylabel('RSI')
    ax6.axhline(context.RSI_OVERBOUGHT, color='darkgoldenrod')
    ax6.axhline(context.RSI_OVERSOLD, color='darkgoldenrod')

    if not transaction_df.empty:
        ax6.scatter(buy_df.index.to_pydatetime(),
                    perf.loc[buy_df.index.floor('1 min'), 'rsi'],
                    marker='^',
                    s=100,
                    c='green',
                    label='')
        ax6.scatter(sell_df.index.to_pydatetime(),
                    perf.loc[sell_df.index.floor('1 min'), 'rsi'],
                    marker='v',
                    s=100,
                    c='red',
                    label='')
    plt.legend(loc=3)
    start, end = ax6.get_ylim()
    ax6.yaxis.set_ticks(np.arange(0, end, end / 5))

    # Show the plot.
    plt.gcf().set_size_inches(18, 8)
    plt.show()
    pass
Beispiel #32
0
def analyze(context, perf):
    # Get the base_currency that was passed as a parameter to the simulation
    exchange = list(context.exchanges.values())[0]
    base_currency = exchange.base_currency.upper()

    # First chart: Plot portfolio value using base_currency
    ax1 = plt.subplot(611)
    perf.loc[:, ['adx', 'pdi', 'mdi']].plot(ax=ax1,
                                            label=['ADX', 'PDI', 'MDI'])
    ax1.set_ylabel('ADX\n({})'.format(base_currency))
    ax1.axhline(30, color='g')
    start, end = ax1.get_ylim()
    ax1.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    # Second chart: Plot asset price, moving averages and buys/sells
    ax2 = plt.subplot(612, sharex=ax1)
    perf.loc[:, ['price', 'ema_long']].plot(ax=ax2, label=['Price', 'EMA20'])

    ax2.set_ylabel('{asset}\n({base})'.format(asset=context.asset.symbol,
                                              base=base_currency))
    start, end = ax2.get_ylim()
    ax2.yaxis.set_ticks(np.arange(start, end, (end - start) / 5))

    transaction_df = extract_transactions(perf)
    if not transaction_df.empty:
        buy_df = transaction_df[transaction_df['amount'] > 0]
        sell_df = transaction_df[transaction_df['amount'] < 0]
        ax2.scatter(buy_df.index.to_pydatetime(),
                    perf.loc[buy_df.index, 'price'],
                    marker='^',
                    s=100,
                    c='green',
                    label='')
        ax2.scatter(sell_df.index.to_pydatetime(),
                    perf.loc[sell_df.index, 'price'],
                    marker='v',
                    s=100,
                    c='red',
                    label='')

    # Third chart: Compare percentage change between our portfolio
    # and the price of the asset
    ax3 = plt.subplot(613, sharex=ax1)
    perf.loc[:, ['algorithm_period_return', 'price_change']].plot(
        ax=ax3, label=['Algo Return', 'HODL Return'])
    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 indicator
    ax4 = plt.subplot(614, sharex=ax1)
    perf.loc[:, ['macd', 'signal']].plot(ax=ax4)
    ax4.set_ylabel('macd\n({})'.format(base_currency))
    start, end = ax4.get_ylim()
    ax4.yaxis.set_ticks(np.arange(0, end, end / 5))

    # Fourth chart: Plot our indicator
    ax5 = plt.subplot(615, sharex=ax1)
    perf.loc[:, ['mfi']].plot(ax=ax5)
    ax5.set_ylabel('Money Flow Index\n({})'.format(base_currency))
    start, end = ax5.get_ylim()
    ax5.yaxis.set_ticks(np.arange(0, end, end / 5))
    ax5.axhline(25, color='r')
    ax5.axhline(80, color='g')

    # Fourth chart: Plot our indicator
    ax6 = plt.subplot(616, sharex=ax1)
    perf.loc[:, ['hist']].plot(ax=ax6)
    ax6.set_ylabel('Hist Pct\n({})'.format(base_currency))
    start, end = ax6.get_ylim()
    ax6.yaxis.set_ticks(np.arange(0, end, end / 5))
    # ax6.axhline(25, color='r')
    # ax6.axhline(80, color='g')

    plt.show()
    perf.to_csv(DATA_PATH + "macd_test.csv")