Esempio n. 1
0
def example_1(data, signals):
    # Example 1)
    # In this example we create a fig and an axis and
    # plot the candlestick chart plus some indicators
    # and the rsi on a seperate axis:

    # Create fig
    fig, _ = plt.subplots(facecolor=mfe.background_color)

    # Create first axis
    ax0 = plt.subplot2grid((8, 4), (0, 0),
                           rowspan=4,
                           colspan=4,
                           facecolor=mfe.background_color)

    # Add content to the first axis.
    # 1) Candlestick chart
    #    Alternative you can use plot_candlestick()
    #    instead of plot_filled_ohlc().
    #    The functionality is the same
    # 2) Bollinger Bands 20
    # 3) Moving Average 36
    # 4) Exponential Moving Average 8
    _, _ = mfe.plot_candlestick(
        fig=fig,
        axis=ax0,
        data=data,
        name='BTC_XRP_5min',
        signals=signals,
        plot_columns=['bband_upper_20', 'bband_lower_20', 'MA_36', 'EMA_8'],
        draw_verticals=False,
        signal_evaluation=True,
        signal_evaluation_form='rectangle',  # 'arrow_1'
        disable_x_ticks=True,
    )

    # Create second axis
    ax1 = plt.subplot2grid((8, 4), (4, 0),
                           rowspan=4,
                           colspan=4,
                           sharex=ax0,
                           facecolor=mfe.background_color)

    # Add content to the second axis.
    # 1) RSI 14
    mfe.plot(data=data,
             name='Chart 2',
             plot_columns=['RSI_14'],
             axis=ax1,
             fig=fig,
             xhline_red=0.8,
             xhline_green=0.2,
             gradient_fill=True)

    plt.show()
Esempio n. 2
0
def test_3():
    # Read and prepare data
    df = pd.read_csv('stocks.csv', index_col=False).tail(1000)
    date = df['Date']
    df = df.drop(['Date'], axis=1)

    # List of vlines:
    # [index_1, index_2, ...] or
    # [{'index':..., 'color':..., 'linewidth':..., 'alpha':..., 'linestyle':...,}, ...]
    vlines = [50, 150]

    # List of hlines:
    # [index_1, index_2, ...] or
    # [{'index':..., 'color':..., 'linewidth':..., 'alpha':..., 'linestyle':...,}, ...]
    hlines = [{
        'index': 3.5,
        'color': 'red',
        'linewidth': 0.8,
        'alpha': 0.8,
        'linestyle': ':'
    }, {
        'index': 4,
        'color': 'red',
        'linewidth': 0.8,
        'alpha': 0.8,
        'linestyle': ':'
    }]

    # List of lines
    # [{'start': [x, y], 'stop': [x, y], 'color':..., 'linewidth':..., 'alpha':..., 'linestyle':...,}, ...]
    lines = [{
        'start': [50, 3.5],
        'stop': [150, 4]
    }, {
        'start': [50, 4],
        'stop': [150, 3.5]
    }]

    mfe.plot(
        df / df.iloc[0],
        columns=['AMZN', 'AMD', 'GOOGL'],
        xticks=date,
        gradient_fill=True,
        xlabel='Date',
        ylabel='Price',
        title='Stocks',
        vspans=[[50, 150]],  # List of vspans: [[start index, end index], ...]
        hspans=[[3.5, 4]],  # List of hspans: [[start index, end index], ...]
        vlines=vlines,
        hlines=hlines,
        lines=lines)
def main():

    # 1) Arrange data -------------------------------------------------
    # Load dataset (max 120000 datapoints)
    data = pd.read_csv('BTC_XRP_5min.csv', index_col=0).tail(5000)
    data = data.drop(['date', 'quoteVolume', 'volume', 'weightedAverage'], 1)

    # Calculate indicators
    data = relative_strength_index(df=data, n=14)
    data = bollinger_bands(df=data, n=20, std=4, add_ave=False)
    data = exponential_moving_average(df=data, n=10)
    data = moving_average(df=data, n=12)
    data = macd(df=data, n_fast=12, n_slow=26)

    # Cut DataFrame
    data = data.iloc[40::]
    # Reset index
    data = data.reset_index()
    # Delete old index
    data = data.drop('index', 1)

    # Normalize data
    data_n = (data - data.mean()) / (data.max() - data.min())

    # 2) RNN ----------------------------------------------------------
    # Parameters
    batch_size = 3
    test_dataset_size = 0.05
    num_units = 12
    learning_rate = 0.001
    epochs = 8

    # Which names are avaiable? print(list(data_n))
    features = ['MA_12', 'MACD_12_26']

    dataset_train_length = len(data_n.index) -\
        int(len(data_n.index) * test_dataset_size)

    training_data = data_n.iloc[:dataset_train_length]

    # Train and test the RNN
    predicted_data = network(data_n, features, batch_size,
                             dataset_train_length, num_units, learning_rate,
                             epochs)

    # Append test close data and the predicted data
    test_close = pd.DataFrame(data_n['close'][dataset_train_length::])
    df = pd.concat([training_data, predicted_data, test_close])

    # 3) Plot ---------------------------------------------------------
    fig, _ = plt.subplots(facecolor=mfe.background_color)
    ax0 = plt.subplot2grid((10, 8), (0, 0),
                           rowspan=6,
                           colspan=8,
                           facecolor=mfe.background_color)

    mfe.plot_candlestick(
        fig=fig,
        axis=ax0,
        data=df,
        plot_columns=[
            'bband_upper_20', 'bband_lower_20', 'MA_12', 'predicted', 'close'
        ],
        vline=dataset_train_length - 1,
        vspan=[dataset_train_length - 1,
               len(data_n.index)],
    )

    tracking_error = np.std(predicted_data['predicted'] -
                            data_n['close'][dataset_train_length::]) * 100
    print('Tracking_error: ' + str(tracking_error))

    # Plot RSI
    ax1 = plt.subplot2grid((10, 8), (6, 0),
                           rowspan=2,
                           colspan=8,
                           sharex=ax0,
                           facecolor=mfe.background_color)

    mfe.plot(data=data_n,
             name='RSI_14',
             plot_columns=['RSI_14'],
             axis=ax1,
             fig=fig,
             xhline_red=0.8,
             xhline_green=0.2,
             vline=dataset_train_length - 1,
             vspan=[dataset_train_length - 1,
                    len(data_n.index)])

    # Plot MACD
    ax1 = plt.subplot2grid((10, 8), (8, 0),
                           rowspan=2,
                           colspan=8,
                           sharex=ax0,
                           facecolor=mfe.background_color)

    mfe.plot(data=data_n,
             name='MACD',
             plot_columns=['MACD_12_26', 'MACDsign_12_26', 'MACDdiff_12_26'],
             axis=ax1,
             fig=fig,
             xhline_dashed1=0,
             vline=dataset_train_length - 1,
             vspan=[dataset_train_length - 1,
                    len(data_n.index)])
    plt.subplots_adjust(left=.07,
                        bottom=.05,
                        right=.94,
                        top=.96,
                        hspace=0.2,
                        wspace=0.03)
    plt.show()
Esempio n. 4
0
def example_5():
    df = pd.read_csv('stocks.csv', index_col=0).tail(1000)
    mfe.plot(df / df.iloc[0], gradient_fill=True)
Esempio n. 5
0
def test_1(df):
    # Example 1)
    # In this example we plot the candlestick chart plus
    # some indicators and rsi on a seperate axis:

    # Structure: [(signal, index, price), ... ].
    # Signal can be 'BUY' or 'SELL'
    signals = [
        ('BUY', 12, 0.69),
        ('SELL', 27, 0.7028),
        ('BUY', 56, 0.6563),
        ('SELL', 81, 0.6854),
        ('BUY', 106, 0.665),
        ('SELL', 165, 0.640),
        ('BUY', 183, 0.66),
        ('SELL', 202, 0.7063),
    ]

    # Create fig
    fig, _ = plt.subplots(facecolor=mfe.cb)

    # Create first axis
    ax0 = plt.subplot2grid((8, 4), (0, 0),
                           rowspan=4,
                           colspan=4,
                           facecolor=mfe.cb)

    # Add content to the first axis.
    mfe.plot_candlestick(
        fig=fig,
        axis=ax0,
        data=df,
        title='BTC_XRP_5min',
        signals=signals,
        columns=['bband_upper_20', 'bband_Lower_20', 'MA_36', 'EMA_8'],
        disable_xticks=False,
    )

    # Just to show what is possible
    # mfe.plot_volume(
    #     twin_axis=ax0,
    #     fig=fig,
    #     data=df
    # )

    # Create second axis
    ax1 = plt.subplot2grid((8, 4), (4, 0),
                           rowspan=4,
                           colspan=4,
                           sharex=ax0,
                           facecolor=mfe.cb)

    # Add content to the second axis.
    # 1) RSI 14
    mfe.plot(axis=ax1,
             fig=fig,
             data=df,
             name='RSI 2',
             columns=['RSI_14'],
             hlines=[{
                 'index': 0.8,
                 'color': 'red'
             }, {
                 'index': 0.2,
                 'color': 'green'
             }])

    plt.show()