Esempio n. 1
0
    def _render_price(self, current_step, net_worth, step_range, dates):
        self.price_ax.clear()

        # Format data for OHCL candlestick graph
        candlesticks = zip(dates, self.df['Open'].values[step_range],
                           self.df['Close'].values[step_range],
                           self.df['High'].values[step_range],
                           self.df['Low'].values[step_range])

        # Plot price using candlestick graph from mpl_finance
        candlestick(self.price_ax, candlesticks, width=2)

        last_date = self.df['Timestamp'].values[current_step]
        last_close = self.df['Close'].values[current_step]
        last_high = self.df['High'].values[current_step]

        # Print the current price to the price axis
        self.price_ax.annotate('{0:.2f}'.format(last_close),
                               (last_date, last_close),
                               xytext=(last_date, last_high),
                               bbox=dict(boxstyle='round',
                                         fc='w',
                                         ec='k',
                                         lw=1),
                               color="black",
                               fontsize="small")

        # Shift price axis up to give volume chart space
        ylim = self.price_ax.get_ylim()
        self.price_ax.set_ylim(
            ylim[0] - (ylim[1] - ylim[0]) * VOLUME_CHART_HEIGHT, ylim[1])
Esempio n. 2
0
    def _render_price(self, current_step, net_worth, dates, step_range):
        self.price_ax.clear()

        candlesticks = zip(dates, self.df['Open'].values[step_range],
                           self.df['Close'].values[step_range],
                           self.df['High'].values[step_range],
                           self.df['Low'].values[step_range])
        candlestick(self.price_ax,
                    candlesticks,
                    width=1,
                    colorup=UP_COLOR,
                    colordown=DOWN_COLOR)

        last_date = date2num(self.df['Date'].values[current_step])
        last_close = self.df['Close'].values[current_step]
        last_high = self.df['High'].values[current_step]

        self.price_ax.annotate('{0:.2f}'.format(last_close),
                               (last_date, last_close),
                               xytext=(last_date, last_high),
                               bbox=dict(boxstyle='round',
                                         fc='w',
                                         ec='k',
                                         lw=1),
                               color='black',
                               fontsize='small')

        ylim = self.price_ax.get_ylim()
        self.price_ax.set_ylim(
            ylim[0] - (ylim[1] - ylim[0]) * VOLUME_CHART_HEIGHT, ylim[1])
Esempio n. 3
0
    def _render_price(self, current_step, step_range):
        self.price_ax.clear()

        candlesticks = zip(step_range, self.df['Open'].values[step_range],
                           self.df['Close'].values[step_range],
                           self.df['High'].values[step_range],
                           self.df['Low'].values[step_range])
        candlestick(self.price_ax,
                    candlesticks,
                    width=1,
                    colorup=UP_COLOR,
                    colordown=DOWN_COLOR)

        last_close = self.df['Close'].values[current_step]
        last_high = self.df['High'].values[current_step]

        self.price_ax.annotate('{0:.2f}'.format(last_close),
                               (current_step, last_close),
                               xytext=(current_step, last_high),
                               bbox=dict(boxstyle='round',
                                         fc='w',
                                         ec='k',
                                         lw=1),
                               color='black',
                               fontsize='small')
Esempio n. 4
0
 def _render_price(self, current_step, net_worth, dates, step_range):
     candlesticks = {}
     last_dates = {}
     last_closes = {}
     last_highs = {}
     y_limit = {}
     for index, asset in enumerate(self.assets):
         if index == 0:
             self.price_axs[asset].set_title(
                 'Candlesticks')  # ? this can go out?
         self.price_axs[asset].clear()
         candlesticks[asset] = zip(dates,
                                   self.df_features[asset]['open'].values[step_range],
                                   self.df_features[asset]['close'].values[step_range],
                                   self.df_features[asset]['high'].values[step_range],
                                   self.df_features[asset]['low'].values[step_range])
         candlestick(self.price_axs[asset],
                     candlesticks[asset],
                     width=self.candlestick_width,
                     colorup=UP_COLOR,
                     colordown=DOWN_COLOR)
         last_dates[asset] = date2num(
             self.df_complete[asset]['Date'].values[current_step])
         last_closes[asset] = self.df_features[asset]['close'].values[current_step]
         last_highs[asset] = self.df_features[asset]['high'].values[current_step]
         self.price_axs[asset].annotate(s="{0:.4f}".format(last_closes[asset]), xy=(
             last_dates[asset], last_closes[asset]), xytext=(last_dates[asset], last_highs[asset]), bbox=dict(boxstyle='round', fc='w', ec='k', lw=1), color='black', fontsize='small')
         y_limit[asset] = self.price_axs[asset].get_ylim()
         self.price_axs[asset].set_ylim(y_limit[asset][0] - (
             y_limit[asset][1] - y_limit[asset][0]) * VOLUME_CHART_HEIGHT, y_limit[asset][1])
         self.price_axs[asset].set_ylabel(
             '{}/{}'.format(asset, self.currency))
Esempio n. 5
0
    def candlestick(self,
                    index,
                    open,
                    high,
                    low,
                    close,
                    width=0.3,
                    secondary_y=False,
                    *args,
                    **kwargs):
        """
            Takes a df and plots a candlestick. 
            Will auto search for proper columns
        """
        data = {}
        data['open'] = open
        data['high'] = high
        data['low'] = low
        data['close'] = close
        df = pd.DataFrame(data, index=index)

        if self.index is None:
            self.index = index

        # grab merged data
        xax = np.arange(len(self.index))
        quotes = izip(xax, df['open'], df['close'], df['high'], df['low'])

        ax = self.find_ax(secondary_y, kwargs)

        self.setup_datetime(index)
        candlestick(ax, quotes, width=width, colorup='g')
Esempio n. 6
0
def generate_plot(name,hours):
    dates = []
    btc = []
    eth = []
    n = 0
    history_file = open('./history.txt','r')
    lines  = history_file.readlines()
    history_file.close()
    date = datetime.now()
    while (datetime.now() - date).total_seconds() < hours * 3600:
        n = n + 1
        line = lines[-n].split(",")
        date = datetime.strptime(line[0], "%Y-%m-%d %H:%M:%S.%f")
        btc_price = float(line[1])
        eth_price = float(line[2])
        dates.append(date)
        btc.append(btc_price)
        eth.append(eth_price)
    if name == 'BTC':
        fig, ax = plt.subplots()
        ax.plot(dates,btc)
        ax.set_title("Evolution of the price in the last "+str(hours)+" h")
        plt.xlabel("Date")
        plt.ylabel("BTC price")
        fig.autofmt_xdate()
        ax.fmt_xdata = mdates.DateFormatter('%H:%M') 
        plt.grid()
        plt.savefig("./btc.png")
        plt.clf()
        fig, ax = plt.subplots()
        opens, closes, highs, lows , d = get_candlesticks(btc,dates,2*hours)
        candlestick(ax, opens, closes, highs, lows, width = 0.6)
        print("Candlesticks for BTC plotted")
        ax.set_title("Evolution of the price in the last "+str(hours)+" h")
        plt.xlabel("Step = "str(2*hours)+" points")
        plt.ylabel("BTC price")
        plt.grid()
        plt.savefig("./btc_candlestick.png")
        plt.clf()
    if name == 'ETH':
        fig, ax = plt.subplots()
        ax.plot(dates,eth)
        ax.set_title("Evolution of the price in the last "+str(hours)+" h")
        plt.xlabel("Step")
        plt.ylabel("ETH price")
        fig.autofmt_xdate()
        ax.fmt_xdata = mdates.DateFormatter('%H:%M') 
        plt.grid()
        plt.savefig("./eth.png")
        plt.clf()
        fig, ax = plt.subplots()
        opens, closes, highs, lows, d = get_candlesticks(eth,dates,2*hours)
        candlestick(ax, opens, closes, highs , lows, width = 0.6) 
        ax.set_title("Evolution of the price in the last "+str(hours)+" h")
        plt.xlabel("Step = "str(2*hours)+" points")
        plt.ylabel("ETH price")
        plt.grid()
        plt.savefig("./eth_candlestick.png")
        plt.clf()
Esempio n. 7
0
def plot_candlestick_and_volume(data_df: pd.DataFrame):
    """ Plot a candlestick chart of open/high/low/close with the
        volume overlayed at the bottom

    :param data_df: pandas.DataFrame that requires columns: date, open, close,
        max, min, volume
    """

    candlesticks = zip(date2num(data_df['date']), data_df['open'],
                       data_df['close'], data_df['max'], data_df['min'],
                       data_df['volume'])

    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)

    ax.set_ylabel('Quote ($)', size=20)
    candlestick(ax, candlesticks, width=1, colorup='g', colordown='r')

    # shift y-limits of the candlestick plot so that there is space at the bottom for the volume bar chart
    pad = 0.25
    yl = ax.get_ylim()
    ax.set_ylim(yl[0] - (yl[1] - yl[0]) * pad, yl[1])

    # create the second axis for the volume bar-plot
    ax2 = ax.twinx()

    # set the position of ax2 so that it is short (y2=0.32)
    # but otherwise the same size as ax
    ax2.set_position(matplotlib.transforms.Bbox([[0.125, 0.1], [0.9, 0.32]]))

    # get data from candlesticks for a bar plot
    dates = [x[0] for x in candlesticks]
    dates = np.asarray(dates)
    volume = [x[5] for x in candlesticks]
    volume = np.asarray(volume)

    # make bar plots and color differently depending on up/down for the day
    pos = (data_df['open'] - data_df['close']) < 0
    neg = (data_df['open'] - data_df['close']) > 0
    ax2.bar(dates[pos], volume[pos], color='green', width=1, align='center')
    ax2.bar(dates[neg], volume[neg], color='red', width=1, align='center')

    # scale the x-axis tight
    ax2.set_xlim(min(dates), max(dates))
    # the y-ticks for the bar were too dense, keep only every third one
    yticks = ax2.get_yticks()
    ax2.set_yticks(yticks[::3])

    ax2.yaxis.set_label_position("right")
    ax2.set_ylabel('Volume', size=20)

    # format the x-ticks with a human-readable date.
    xt = ax.get_xticks()
    new_xticks = [datetime.date.isoformat(num2date(d)) for d in xt]
    ax.set_xticklabels(new_xticks, rotation=45, horizontalalignment='right')

    # plt.ion()
    # plt.show()
    return fig, ax
 def _render_price(self, current_step, net_worth, step_range, dates):
     self.price_ax.clear()
     candlesticks = zip(dates, self.df['Open'].values[step_range],
                        self.df['Close'].values[step_range],
                        self.df['High'].values[step_range],
                        self.df['Low'].values[step_range])
     candlestick(self.price_ax, candlesticks, width=20)
     last_date = self.df['Timestamp'].values[current_step]
     last_close = self.df['Close'].values[current_step]
     last_high = self.df['High'].values[current_step]
Esempio n. 9
0
def plot_k_line(data):

    candlesticks = zip(date2num(data['time'].values), data['open'], data['close'], data['high'], data['low'], data['vol'])

    scale = abs(candlesticks[1][0] - candlesticks[0][0])

    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)

    ax.set_ylabel('Quote ($)', size=20)
    candlestick(ax, candlesticks, width=scale, colorup='g', colordown='r')

    # shift y-limits of the candlestick plot so that there is space at the bottom for the volume bar chart
    pad = 0.25
    yl = ax.get_ylim()
    ax.set_ylim(yl[0]-(yl[1]-yl[0])*pad,yl[1])

    # create the second axis for the volume bar-plot
    ax2 = ax.twinx()

    # set the position of ax2 so that it is short (y2=0.32) but otherwise the same size as ax
    ax2.set_position(matplotlib.transforms.Bbox([[0.125, 0.1], [0.9, 0.32]]))

    # get data from candlesticks for a bar plot
    dates = [x[0] for x in candlesticks]
    dates = np.asarray(dates)
    volume = [x[5] for x in candlesticks]
    volume = np.asarray(volume)

    # make bar plots and color differently depending on up/down for the day
    pos = data['open'] - data['close'] < 0
    neg = data['open'] - data['close'] > 0
    ax2.bar(dates[pos], volume[pos], color='green', width=scale, align='center')
    ax2.bar(dates[neg], volume[neg], color='red', width=scale, align='center')

    #scale the x-axis tight
    ax2.set_xlim(min(dates),max(dates))
    # the y-ticks for the bar were too dense, keep only every third one
    yticks = ax2.get_yticks()
    ax2.set_yticks(yticks[::3])

    ax2.yaxis.set_label_position("right")
    ax2.set_ylabel('Volume', size=20)

    # format the x-ticks with a human-readable date.
    xt = ax.get_xticks()
    new_xticks = [num2date(d).strftime('%Y%m%d%H%M') for d in xt]
    #new_xticks = [datetime.date.isoformat(num2date(d)) for d in xt]
    ax.set_xticklabels(new_xticks,rotation=45, horizontalalignment='right')

    #plt.ion()
    plt.show()
Esempio n. 10
0
    def animate(self, i):
        #logger.info("[plotThread][animate] self.update_flag " + str(self.update_flag))

        if self.update_flag:
            sec_id = singleton_data.getInstance().getOHLC_data()

            sec_id_ochl = np.array(pd.DataFrame({'0':date2num(sec_id.index),
                                                 '1':sec_id.open,
                                                 '2':sec_id.close,
                                                 '3':sec_id.high,
                                                 '4':sec_id.low}))

            #logger.info("[plotThread][animate] sec_id_ochl " + str(sec_id_ochl))

            self.analysis = pd.DataFrame(index = sec_id.index)

            self.analysis['sma_f'] = sec_id.close.rolling(self.SMA_FAST).mean()
            self.analysis['sma_s'] = sec_id.close.rolling(self.SMA_SLOW).mean()
            self.analysis['rsi'] = ta.RSI(sec_id.close.to_numpy(), self.RSI_PERIOD)
            self.analysis['sma_r'] = self.analysis.rsi.rolling(self.RSI_PERIOD).mean()
            self.analysis['macd'], self.analysis['macdSignal'], self.analysis['macdHist'] = ta.MACD(sec_id.close.to_numpy(), fastperiod=self.MACD_FAST, slowperiod=self.MACD_SLOW, signalperiod=self.MACD_SIGNAL)
            self.analysis['stoch_k'], self.analysis['stoch_d'] = ta.STOCH(sec_id.high.to_numpy(), sec_id.low.to_numpy(), sec_id.close.to_numpy(), fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0)#slowk_period=self.STOCH_K, slowd_period=self.STOCH_D)

            self.analysis['sma'] = np.where(self.analysis.sma_f > self.analysis.sma_s, 1, 0)

            # Plot candles width=.6/(24*60)
            candlestick(self.ax1, sec_id_ochl, width=.6/(24*60), colorup='g', colordown='r', alpha=1)

            # Draw Moving Averages
            self.analysis['sma_f'] = sec_id.close.rolling(self.SMA_FAST).mean()
            self.analysis['sma_s'] = sec_id.close.rolling(self.SMA_SLOW).mean()

            self.analysis.sma_f.plot(ax=self.ax1, c='r', linewidth=self.LINE_WIDTH)
            self.analysis.sma_s.plot(ax=self.ax1, c='g', linewidth=self.LINE_WIDTH)

            self.analysis.rsi.plot(ax = self.ax2, c='g', label = 'Period: ' + str(self.RSI_PERIOD), linewidth=self.LINE_WIDTH)
            self.analysis.sma_r.plot(ax = self.ax2, c='r', label = 'MA: ' + str(self.RSI_AVG_PERIOD), linewidth=self.LINE_WIDTH)

            self.analysis.macd.plot(ax=self.ax3, color='b', label='Macd', linewidth=self.LINE_WIDTH)
            self.analysis.macdSignal.plot(ax=self.ax3, color='g', label='Signal', linewidth=self.LINE_WIDTH)
            self.analysis.macdHist.plot(ax=self.ax3, color='r', label='Hist', linewidth=self.LINE_WIDTH)

            self.analysis.stoch_k.plot(ax=self.ax4, label='stoch_k:'+ str(self.STOCH_K), color='r', linewidth=self.LINE_WIDTH)
            self.analysis.stoch_d.plot(ax=self.ax4, label='stoch_d:'+ str(self.STOCH_D), color='g', linewidth=self.LINE_WIDTH)

            self.update_flag = False
Esempio n. 11
0
def analyze(context, data, analysis):
    ticker = context.CURRENCY
    date_from = '2018-08-01'
    
    # Data for matplotlib finance plot
    data = data[data.index > date_from]
    data['Date'] = data.index.map(mdates.date2num)
    ohlc = data[['Date','OPEN_PRC','HIGH_PRC','LOW_PRC','CLS_PRC']]

    analysis = analysis[analysis.index > date_from]
    analysis.index = date2num(analysis.index.to_pydatetime())

    # Prepare figure and plots
    fig, (ax1, ax2, ax3) = plt.subplots(3, 1, gridspec_kw={'height_ratios':[6,2,2]}, sharex=True)
    fig.set_size_inches(15,30)

    # Set ax1
    ax1.set_ylabel(ticker, size=20)
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
    ax1.grid(True)

    # Draw Candlestick
    candlestick(ax1, ohlc.values, width=0.1, colorup='g', colordown='r', alpha=1)

    # Plot ZigZag
    ax1.plot(analysis.ix[analysis.ZIGZAG != 0].index, analysis.price[analysis.ZIGZAG != 0], 'k-')
    ax1.scatter(analysis.ix[analysis.ZIGZAG == 1].index, analysis.price[analysis.ZIGZAG == 1], color='g')
    ax1.scatter(analysis.ix[analysis.ZIGZAG == -1].index, analysis.price[analysis.ZIGZAG == -1], color='r')

    # Draw Moving Averages
    analysis.sma_f.plot(ax=ax1, c='r', label='SMA'+str(SMA_FAST))
    analysis.sma_s.plot(ax=ax1, c='g', label='SMA'+str(SMA_SLOW))
    #ax1.plot(analysis.ix[analysis.sma == 1].index, analysis.sma_f[analysis.sma == 1], '^')

    # Draw 3Inside
    ax1.plot(analysis.ix[analysis.CDL3INSIDE < 0].index, analysis.price[analysis.CDL3INSIDE < 0], 'v')
    ax1.plot(analysis.ix[analysis.CDL3INSIDE > 0].index, analysis.price[analysis.CDL3INSIDE > 0], '^')

    # Draw Support and Resistance Line
    support, resistance = indic.findsnp(data['CLS_PRC'], 10)
    for value in support+resistance:
        ax1.hlines(y=value, xmin=analysis.index.min(), xmax=analysis.index.max(), linewidth=1, color='r', linestyles='--') 

    # Draw Peak and Valley
    # indices = peakutils.indexes(analysis['price'], valley=False, thres=0.3, min_dist=1, thres_abs=False)
    # peak1 = analysis.iloc[indices]

    # peak_indices = indic.detect_peaks(analysis['price'], edge='rising', valley=False, threshold=0.3)
    # valley_indices = indic.detect_peaks(analysis['price'], edge='falling', valley=True, threshold=0.3)
    # peaks = analysis.iloc[peak_indices]
    # valleys = analysis.iloc[valley_indices]
    # peaknvalley_indices = peak_indices.tolist()+valley_indices.tolist()
    # peaknvalley_indices.sort()
    # peaknvalley = analysis.iloc[peaknvalley_indices]

    # ax1.plot(peaknvalley.index, peaknvalley.price, 'k-')    
    # ax1.scatter(peaks.index, peaks.price, color='y')
    # ax1.scatter(valleys.index, valleys.price, color='r')
    # ax1.scatter(peak1.index, peak1.price, color='b', marker='^')
    
    #RSI
    ax2.set_ylabel('RSI', size=Y_AXIS_SIZE)
    analysis.rsi.plot(ax=ax2, c='g', label = 'Period: ' + str(RSI_PERIOD))
    analysis.sma_r.plot(ax=ax2, c='r', label = 'MA: ' + str(RSI_AVG_PERIOD))
    ax2.axhline(y=30, c='b')
    ax2.axhline(y=50, c='black')
    ax2.axhline(y=70, c='b')
    ax2.set_ylim([0,100])
    ax2.legend(loc='upper left')

    '''# Volume
    ax2.bar(analysis.index, analysis.volume, 0.2, align='center', color='b', label='Volume')
    ax2.legend(loc='upper left')
    ax2.grid(True)'''

    '''# Volume Change Rate
    ax3.set_ylabel('VOL_CHG', size=Y_AXIS_SIZE)
    analysis.VOL_CHG.plot(ax=ax3, c='g', label = 'VOL_CHG')
    handles, labels = ax3.get_legend_handles_labels()
    ax3.legend(handles, labels) 
    ax3.grid()'''

    '''
    # Draw MACD computed with Talib
    ax3.set_ylabel('MACD: '+ str(MACD_FAST) + ', ' + str(MACD_SLOW) + ', ' + str(MACD_SIGNAL), size=Y_AXIS_SIZE)
    analysis.macd.plot(ax=ax3, color='b', label='Macd')
    analysis.macdSignal.plot(ax=ax3, color='g', label='Signal')
    analysis.macdHist.plot(ax=ax3, color='r', label='Hist')
    ax3.axhline(0, lw=2, color='0')
    handles, labels = ax3.get_legend_handles_labels()
    ax3.legend(handles, labels)
    ax3.grid()'''

    # Stochastic plot
    # ax2.set_ylabel('Stoch1', size=Y_AXIS_SIZE)
    # analysis.STO_K.plot(ax=ax2, label='STO_K', color='b')
    # analysis.STO_D.plot(ax=ax2, label='STO_D', color='r')
    # ax2.legend(loc='upper left')
    # ax2.axhline(y=20, c='m')
    # ax2.axhline(y=80, c='m')
    # ax2.grid()

    # Stochastic plot
    ax3.set_ylabel('Stoch', size=Y_AXIS_SIZE)
    analysis.stoch_k.plot(ax=ax3, label='stoch_k', color='b')
    analysis.stoch_d.plot(ax=ax3, label='stoch_d', color='r')
    ax3.legend(loc='upper left')
    ax3.axhline(y=20, c='m')
    ax3.axhline(y=80, c='m')
    ax3.grid()

    # Plot Peak and Valley for Stochastic
    peak_indices = indic.detect_peaks(analysis['stoch_k'], edge='rising', valley=False, threshold=0.3)
    valley_indices = indic.detect_peaks(analysis['stoch_k'], edge='falling', valley=True, threshold=0.3)
    peaks = analysis.iloc[peak_indices]
    valleys = analysis.iloc[valley_indices]
    ax3.scatter(peaks.index, peaks.stoch_k, color='y')
    ax3.scatter(valleys.index, valleys.stoch_k, color='r')

    plt.show()
    def _render_price(self, current_step, net_worth, dates, step_range):
        self.price_ax1.clear()
        self.price_ax2.clear()
        self.price_ax3.clear()

        candlesticks1 = zip(dates,
                           self.df1['open'].values[step_range], self.df1['close'].values[step_range],
                           self.df1['high'].values[step_range], self.df1['low'].values[step_range])
        candlesticks2 = zip(dates,
                           self.df2['open'].values[step_range], self.df2['close'].values[step_range],
                           self.df2['high'].values[step_range], self.df2['low'].values[step_range])
        candlesticks3 = zip(dates,
                           self.df3['open'].values[step_range], self.df3['close'].values[step_range],
                           self.df3['high'].values[step_range], self.df3['low'].values[step_range])

        # Plot price using candlestick graph from mpl_finance
        candlestick(self.price_ax1, candlesticks1, width=.04,
                    colorup=UP_COLOR, colordown=DOWN_COLOR)
        candlestick(self.price_ax2, candlesticks2, width=.04,
                    colorup=UP_COLOR, colordown=DOWN_COLOR)
        candlestick(self.price_ax3, candlesticks3, width=.04,
                    colorup=UP_COLOR, colordown=DOWN_COLOR)

        last_date = date2num(self.df1['Date'].values[current_step])
        last_close1 = self.df1['close'].values[current_step]
        last_high1 = self.df1['high'].values[current_step]
        last_close2 = self.df2['close'].values[current_step]
        last_high2 = self.df2['high'].values[current_step]
        last_close3 = self.df3['close'].values[current_step]
        last_high3 = self.df3['high'].values[current_step]

        # Print the current price to the price axis
        self.price_ax1.annotate('{0:.4f}'.format(last_close1), (last_date, last_close1),
                               xytext=(last_date, last_high1),
                               bbox=dict(boxstyle='round',
                                         fc='w', ec='k', lw=1),
                               color="black",
                               fontsize="small")
        self.price_ax2.annotate('{0:.4f}'.format(last_close2), (last_date, last_close2),
                               xytext=(last_date, last_high2),
                               bbox=dict(boxstyle='round',
                                         fc='w', ec='k', lw=1),
                               color="black",
                               fontsize="small")
        self.price_ax3.annotate('{0:.4f}'.format(last_close3), (last_date, last_close3),
                               xytext=(last_date, last_high3),
                               bbox=dict(boxstyle='round',
                                         fc='w', ec='k', lw=1),
                               color="black",
                               fontsize="small")

        # Shift price axis up to give volume chart space
        ylim1 = self.price_ax1.get_ylim()
        ylim2 = self.price_ax2.get_ylim()
        ylim3 = self.price_ax3.get_ylim()

        self.price_ax1.set_ylim(ylim1[0] - (ylim1[1] - ylim1[0])
                               * VOLUME_CHART_HEIGHT, ylim1[1])
        self.price_ax1.set_ylabel('BTC')
        self.price_ax2.set_ylim(ylim2[0] - (ylim2[1] - ylim2[0])
                               * VOLUME_CHART_HEIGHT, ylim2[1])
        self.price_ax2.set_ylabel('ETH')
        self.price_ax3.set_ylim(ylim3[0] - (ylim3[1] - ylim3[0])
                               * VOLUME_CHART_HEIGHT, ylim3[1])
        self.price_ax3.set_ylabel('LTC')
Esempio n. 13
0
def show_tech_thru_code(code, days=100):
    '''
    展示蜡烛图
    展示RSI
    展示MACD
    https://wiki.fintechki.com/index.php?title=How_to_draw_MACD_Charts
    '''
    ticker = code
    df = ts.get_hist_data(code)
    sec_id = df.sort_index(ascending=True)
    sec_id.index = pd.to_datetime(sec_id.index)
    part_sec_id = sec_id.sort_index(ascending=False).iloc[0:days]
    # Data for matplotlib finance plot
    sec_id_ochl = np.array(
        pd.DataFrame({
            '0': date2num(part_sec_id.index),
            '1': part_sec_id.open,
            '2': part_sec_id.close,
            '3': part_sec_id.high,
            '4': part_sec_id.low
        }))

    analysis = pd.DataFrame(index=sec_id.index)

    analysis['sma_f'] = pd.Series.rolling(sec_id.close, SMA_FAST).mean()
    analysis['sma_s'] = pd.Series.rolling(sec_id.close, SMA_SLOW).mean()
    analysis['rsi'] = ta.RSI(sec_id.close.values, RSI_PERIOD)

    analysis['sma_r'] = pd.Series.rolling(analysis.rsi, RSI_AVG_PERIOD).mean()
    analysis['macd'], analysis['macdSignal'], analysis['macdHist'] = ta.MACD(
        sec_id.close.values,
        fastperiod=MACD_FAST,
        slowperiod=MACD_SLOW,
        signalperiod=MACD_SIGNAL)
    analysis['stoch_k'], analysis['stoch_d'] = ta.STOCH(sec_id.high.values,
                                                        sec_id.low.values,
                                                        sec_id.close.values,
                                                        slowk_period=STOCH_K,
                                                        slowd_period=STOCH_D)

    analysis['sma'] = np.where(analysis.sma_f > analysis.sma_s, 1, 0)
    analysis['macd_test'] = np.where((analysis.macd > analysis.macdSignal), 1,
                                     0)
    analysis['stoch_k_test'] = np.where(
        (analysis.stoch_k < 50) &
        (analysis.stoch_k > analysis.stoch_k.shift(1)), 1, 0)
    analysis['rsi_test'] = np.where(
        (analysis.rsi < 50) & (analysis.rsi > analysis.rsi.shift(1)), 1, 0)

    analysis = analysis.sort_index(ascending=False)
    analysis = analysis.iloc[:100]

    # Prepare plot
    fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1, sharex=True)
    ax1.set_ylabel(ticker, size=20)

    #size plot
    fig.set_size_inches(15, 30)

    # Plot candles
    candlestick(ax1,
                sec_id_ochl,
                width=0.5,
                colorup='g',
                colordown='r',
                alpha=1)

    # Draw Moving Averages
    analysis.sma_f.plot(ax=ax1, c='r')
    analysis.sma_s.plot(ax=ax1, c='g')

    #RSI
    ax2.set_ylabel('RSI', size=Y_AXIS_SIZE)
    analysis.rsi.plot(ax=ax2, c='g', label='Period: ' + str(RSI_PERIOD))
    analysis.sma_r.plot(ax=ax2, c='r', label='MA: ' + str(RSI_AVG_PERIOD))
    ax2.axhline(y=30, c='b')
    ax2.axhline(y=50, c='black')
    ax2.axhline(y=70, c='b')
    ax2.set_ylim([0, 100])
    handles, labels = ax2.get_legend_handles_labels()
    ax2.legend(handles, labels)

    # Draw MACD computed with Talib
    ax3.set_ylabel('MACD: ' + str(MACD_FAST) + ', ' + str(MACD_SLOW) + ', ' +
                   str(MACD_SIGNAL),
                   size=Y_AXIS_SIZE)
    analysis.macd.plot(ax=ax3, color='b', label='Macd')
    analysis.macdSignal.plot(ax=ax3, color='g', label='Signal')
    ax3.fill_between(analysis.index,
                     analysis['macdHist'],
                     color='gray',
                     alpha=0.5,
                     label='Histogram')
    ax3.axhline(0, lw=2, color='0')
    handles, labels = ax3.get_legend_handles_labels()
    ax3.legend(handles, labels)

    # Stochastic plot
    ax4.set_ylabel('Stoch (k,d)', size=Y_AXIS_SIZE)
    analysis.stoch_k.plot(ax=ax4, label='stoch_k:' + str(STOCH_K), color='r')
    analysis.stoch_d.plot(ax=ax4, label='stoch_d:' + str(STOCH_D), color='g')
    handles, labels = ax4.get_legend_handles_labels()
    ax4.legend(handles, labels)
    ax4.axhline(y=20, c='b')
    ax4.axhline(y=50, c='black')
    ax4.axhline(y=80, c='b')

    plt.show()

    return None
Esempio n. 14
0
analysis['stoch_k_test'] = np.where(
    (analysis.stoch_k < 50) & (analysis.stoch_k > analysis.stoch_k.shift(1)),
    1, 0)
analysis['rsi_test'] = np.where(
    (analysis.rsi < 50) & (analysis.rsi > analysis.rsi.shift(1)), 1, 0)

# Prepare plot
#fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1, sharex=True)
fig, (ax1, ax3) = plt.subplots(2, 1, sharex=True)
ax1.set_ylabel(ticker, size=20)

#size plot
fig.set_size_inches(15, 30)

# Plot candles
candlestick(ax1, sec_id_ohlc, width=0.5, colorup='g', colordown='r', alpha=1)

# Draw Moving Averages
analysis.sma_f.plot(ax=ax1, c='r')
analysis.sma_s.plot(ax=ax1, c='g')

#RSI
#ax2.set_ylabel('RSI', size=Y_AXIS_SIZE)
#analysis.rsi.plot(ax = ax2, c='g', label = 'Period: ' + str(RSI_PERIOD))
#analysis.sma_r.plot(ax = ax2, c='r', label = 'MA: ' + str(RSI_AVG_PERIOD))
#ax2.axhline(y=30, c='b')
#ax2.axhline(y=50, c='black')
#ax2.axhline(y=70, c='b')
#ax2.set_ylim([0,100])
#handles, labels = ax2.get_legend_handles_labels()
#ax2.legend(handles, labels)
    def run(self):
        logger.info("[bitmex_plot][run]")

        sec_id = singleton_data.instance().getOHLC_data()

        self.sec_id_ochl = np.array(
            pd.DataFrame({
                '0': date2num(sec_id.index),  #.to_pydatetime()),
                '1': sec_id.open,
                '2': sec_id.close,
                '3': sec_id.high,
                '4': sec_id.low
            }))

        #self.analysis.Date.dt.tz_localize('UTC')
        self.analysis = analysis.get_analysis(False)

        # Prepare plot
        self.fig, (self.ax1, self.ax2, self.ax3,
                   self.ax4) = plt.subplots(4, 1, sharex=True)
        self.ax1.set_ylabel(ticker, size=20)

        self.ax1.xaxis.set_major_formatter(
            matplotlib.dates.DateFormatter('%H:%M:%S'))

        #size plot
        self.fig.set_size_inches(15, 30)

        # Plot candles width=.6/(24*60)
        candlestick(self.ax1,
                    self.sec_id_ochl,
                    width=.6 / (24 * 60),
                    colorup='g',
                    colordown='r',
                    alpha=1)

        # Draw Moving Averages
        self.analysis.sma_f.plot(ax=self.ax1, c='r', linewidth=self.LINE_WIDTH)
        self.analysis.sma_s.plot(ax=self.ax1, c='g', linewidth=self.LINE_WIDTH)
        handles, labels = self.ax1.get_legend_handles_labels()
        self.ax1.legend(handles, labels)

        #RSI
        self.ax2.set_ylabel('RSI', size=self.Y_AXIS_SIZE)
        self.analysis.rsi.plot(ax=self.ax2,
                               c='g',
                               label='Period: ' + str(self.RSI_PERIOD),
                               linewidth=self.LINE_WIDTH)
        self.analysis.sma_r.plot(ax=self.ax2,
                                 c='r',
                                 label='MA: ' + str(self.RSI_AVG_PERIOD),
                                 linewidth=self.LINE_WIDTH)
        self.ax2.axhline(y=30, c='b', linewidth=self.LINE_WIDTH)
        #self.ax2.axhline(y=50, c='black', linewidth=self.LINE_WIDTH)
        self.ax2.axhline(y=70, c='b', linewidth=self.LINE_WIDTH)
        self.ax2.set_ylim([0, 100])
        handles, labels = self.ax2.get_legend_handles_labels()
        self.ax2.legend(handles, labels)

        # Draw MACD computed with Talib
        self.ax3.set_ylabel('MACD: ' + str(self.MACD_FAST) + ', ' +
                            str(self.MACD_SLOW) + ', ' + str(self.MACD_SIGNAL),
                            size=self.Y_AXIS_SIZE)
        self.analysis.macd.plot(ax=self.ax3,
                                color='b',
                                label='Macd',
                                linewidth=self.LINE_WIDTH)
        self.analysis.macdSignal.plot(ax=self.ax3,
                                      color='g',
                                      label='Signal',
                                      linewidth=self.LINE_WIDTH)
        self.analysis.macdHist.plot(ax=self.ax3,
                                    color='r',
                                    label='Hist',
                                    linewidth=self.LINE_WIDTH)
        self.ax3.axhline(0, lw=2, color='0', linewidth=self.LINE_WIDTH)
        handles, labels = self.ax3.get_legend_handles_labels()
        self.ax3.legend(handles, labels)

        # Stochastic plot
        self.ax4.set_ylabel('Stoch (k,d)', size=self.Y_AXIS_SIZE)
        self.analysis.stoch_k.plot(ax=self.ax4,
                                   label='stoch_k:' + str(self.STOCH_K),
                                   color='r',
                                   linewidth=self.LINE_WIDTH)
        self.analysis.stoch_d.plot(ax=self.ax4,
                                   label='stoch_d:' + str(self.STOCH_D),
                                   color='g',
                                   linewidth=self.LINE_WIDTH)
        handles, labels = self.ax4.get_legend_handles_labels()
        self.ax4.legend(handles, labels)
        self.ax4.axhline(y=20, c='b', linewidth=self.LINE_WIDTH)
        self.ax4.axhline(y=50, c='black', linewidth=self.LINE_WIDTH)
        self.ax4.axhline(y=80, c='b', linewidth=self.LINE_WIDTH)

        self.ani = animation.FuncAnimation(self.fig,
                                           self.animate,
                                           interval=5000)

        plt.show()
Esempio n. 16
0
# creation of new data by replacing the time array with equally spaced values.
# this will allow to remove the gap between the days, when plotting the data
data2 = np.hstack([np.arange(data[:, 0].size)[:, np.newaxis], data[:, 1:]])

# plot the data
fig = plt.figure(figsize=(10, 5))
ax = fig.add_axes([0.1, 0.2, 0.85, 0.7])
# customization of the axis
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.tick_params(axis='both',
               direction='out',
               width=2,
               length=8,
               labelsize=12,
               pad=8)
ax.spines['left'].set_linewidth(2)
ax.spines['bottom'].set_linewidth(2)
# set the ticks of the x axis only when starting a new day
ax.set_xticks(data2[ndays[1], 0])
ax.set_xticklabels(xdays, rotation=45, horizontalalignment='right')

ax.set_ylabel('Quote ($)', size=20)
ax.set_ylim([177, 196])

candlestick(ax, data2, width=0.5, colorup='g', colordown='r')

plt.show()