Esempio n. 1
0
def plot_stock_line(code,start):
    fig = plt.figure(figsize=(10,15))
    # fig,(ax,ax2)=plt.subplots(2,1,sharex=True,figsize=(16,10))
    ax=fig.add_axes([0,0.2,1,0.5])
    ax2=fig.add_axes([0,0,1,0.2])
    df = ts.bar(code,conn=api,start_date=start)
    # df=df.sort_values(by='datetime')
    df = df.sort_index()
    df =df.reset_index()
    # df = ts.get_k_data('300141',start='2018-03-01')
    # df['date']=df['date'].dt.strftime('%Y-%m-%d')
    df['datetime']=df['datetime'].dt.strftime('%Y-%m-%d')
    sma5=talib.SMA(df['close'].values,5)
    sma20=talib.SMA(df['close'].values,20)
    # ax.set_xticks(range(0,len(df),20))
    # # ax.set_xticklabels(df['date'][::5])
    # ax.set_xticklabels(df['datetime'][::20])
    candlestick2_ochl(ax,df['open'],df['close'],df['high'],df['low'],width=0.5,colorup='r',colordown='g',alpha=0.6)
    # ax.set_title(code)
    ax.plot(sma5)
    ax.plot(sma20)


    # df['vol'].plot(kind='bar')
    volume_overlay(ax2,df['open'],df['close'],df['vol'],width=0.5,alpha=0.8,colordown='g',colorup='r')
    ax2.set_xticks(range(0,len(df),20))
    # ax.set_xticklabels(df['date'][::5])
    ax2.set_xticklabels(df['datetime'][::20])
    # ax2.grid(True)

    # plt.setp(ax.get_xticklabels(), rotation=30, horizontalalignment='right')
    # plt.grid(True)
    # plt.subplots_adjust(hspace=0)
    plt.show()
Esempio n. 2
0
def drawCandlestick(index, path):
    fig = plt.figure(figsize=(2, 2))
    ax = fig.add_axes([0, 0.3, 1, 0.7])  # [left, bottom, width, height]
    ax2 = fig.add_axes([0, 0, 1, 0.3])
    # 画蜡烛图
    mpf.candlestick2_ochl(ax,
                          data['open'][index - 20:index],
                          data['close'][index - 20:index],
                          data['high'][index - 20:index],
                          data['low'][index - 20:index],
                          width=0.5,
                          colorup='r',
                          colordown='g',
                          alpha=1)
    # 画交易量
    mpf.volume_overlay(ax2,
                       data['open'][index - 20:index],
                       data['close'][index - 20:index],
                       data['volume'][index - 20:index],
                       colorup='r',
                       colordown='g',
                       width=0.5,
                       alpha=0.8)
    # 去掉坐标轴刻度
    ax.set_xticks([])
    ax.set_yticks([])
    ax2.set_xticks([])
    ax2.set_yticks([])

    plt.savefig(path + str(int(index)) + ".jpg")
Esempio n. 3
0
def plot_k(data, code, attachs, d_channel = False):
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    import matplotlib.finance as mpf
    from matplotlib import gridspec
    import os



    fig = plt.figure(figsize = (10,6))
    gs = gridspec.GridSpec(2,1,height_ratios=[2, 0.8])
    ax = plt.subplot(gs[0]) 
    ax2 = plt.subplot(gs[1]) 
    mpf.candlestick2_ochl(ax, data['open'], data['close'], data['high'], data['low'],
                     width=0.6, colorup='red', colordown='green', alpha=1)

    # 绘制唐奇安通道
    if d_channel:
        ax.plot(data['date'], data['d_up'], color='r', label='Donchian Channel Up: {} days'.format(D_Channel['up']))
        ax.plot(data['date'], data['d_down'], color='b',
                label='Donchian Channel Down: {} days'.format(D_Channel['down']))
    ax.legend()
    ax.set_title(code)
    ax.grid(True)

    mpf.volume_overlay(ax2, data['open'], data['close'], data['volume'], colorup='r', colordown='g', width=0.2, alpha=1)
    ax2.set_xticks(range(0, len(data['date']),2))
    ax2.set_xticklabels(data['date'][::2], rotation=45)
    ax2.grid(True)
    plt.subplots_adjust(hspace = 0)
    figPath = os.getcwd()+ '/{}.png'.format(code)
    fig.savefig(figPath,dpi = 100)
    # plt.show()
    attachs.append(figPath)
Esempio n. 4
0
 def __plt_volume(self, ax):
     ax2 = ax.twinx()
     ax2.set_ylim([0, max(self.ohcl["volume"]) * 4])
     ax2.set_ylabel("volume")
     finance.volume_overlay(ax2,
                            self.ohcl["open"],
                            self.ohcl["close"],
                            self.ohcl["volume"],
                            colorup='r',
                            colordown='g',
                            width=0.5,
                            alpha=0.5)
Esempio n. 5
0
def plot_stock_line(code, start):
    fig = plt.figure(figsize=(10, 15))
    # fig,(ax,ax2)=plt.subplots(2,1,sharex=True,figsize=(16,10))
    ax = fig.add_axes([0, 0.2, 1, 0.5])
    ax2 = fig.add_axes([0, 0, 1, 0.2])
    df = ts.bar(code, conn=api, start_date=start)
    # df=df.sort_values(by='datetime')
    df = df.sort_index()
    df = df.reset_index()
    # df = ts.get_k_data('300141',start='2018-03-01')
    # df['date']=df['date'].dt.strftime('%Y-%m-%d')
    df['datetime'] = df['datetime'].dt.strftime('%Y-%m-%d')
    sma5 = talib.SMA(df['close'].values, 5)
    sma20 = talib.SMA(df['close'].values, 20)
    # ax.set_xticks(range(0,len(df),20))
    # # ax.set_xticklabels(df['date'][::5])
    # ax.set_xticklabels(df['datetime'][::20])
    candlestick2_ochl(ax,
                      df['open'],
                      df['close'],
                      df['high'],
                      df['low'],
                      width=0.5,
                      colorup='r',
                      colordown='g',
                      alpha=0.6)
    # ax.set_title(code)
    ax.plot(sma5)
    ax.plot(sma20)

    # df['vol'].plot(kind='bar')
    volume_overlay(ax2,
                   df['open'],
                   df['close'],
                   df['vol'],
                   width=0.5,
                   alpha=0.8,
                   colordown='g',
                   colorup='r')
    ax2.set_xticks(range(0, len(df), 20))
    # ax.set_xticklabels(df['date'][::5])
    ax2.set_xticklabels(df['datetime'][::20])
    # ax2.grid(True)

    # plt.setp(ax.get_xticklabels(), rotation=30, horizontalalignment='right')
    # plt.grid(True)
    # plt.subplots_adjust(hspace=0)
    plt.show()
Esempio n. 6
0
def plot_volume_overlay(ax,_dfquotes,begin,_locatormulti=40):
    """
    plot volume bar with m5,10 line
    Args:
        _dfquotes (dataframe): the seurity dataframe which include'openPrice''closePrice''turnoverVol''tradeDate'
        ax : matplotlib ax object
        begin : the index of first volume bar, _dfquotes[begin:] will be plot
        _locatormulti (int): adjust the axis's ticker display interval
    Returns:
        lineandbars : return volume_overlay's lineandbars objects

    Examples:
        >> 
    """
    global _tickerstart
    global dfquotes
    dfquotes = _dfquotes
    _tickerstart = begin
    lineandbars = maf.volume_overlay(ax,dfquotes[u'openPrice'][_tickerstart:].values,\
                          dfquotes[u'closePrice'][_tickerstart:].values,\
                          dfquotes[u'turnoverVol'][_tickerstart:].values,\
                          colorup='r',colordown='g',width=0.5,alpha=1.0)
    lineandbars.set_edgecolor(lineandbars.get_facecolor())
    _multilocator = int((len(dfquotes)-_tickerstart)/_locatormulti)#超过40个交易日,日期刻度单位加一天
    ax.xaxis.set_major_locator(MultipleLocator(1+_multilocator))
    ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
    plt.gcf().autofmt_xdate()
    _doublelist = [float(x) for x in dfquotes[u'turnoverVol'].values]
    _doublenparray = np.array(_doublelist)
    plotEMA([5,10],_doublenparray,_tickerstart)
    for label in ax.xaxis.get_ticklabels():
        label.set_rotation(90)
    return lineandbars
Esempio n. 7
0
def candlestick_vol(quotes):
    SCALE = 5
    COLORUP = 'red'
    COLORDOWN = 'green'

    fig, (ax, ax2) = plt.subplots(2, 1, sharex=True, figsize=(17, 10))

    candlestick2_ochl(ax,
                      quotes['open'],
                      quotes['close'],
                      quotes['high'],
                      quotes['low'],
                      width=0.5,
                      colorup=COLORUP,
                      colordown=COLORDOWN,
                      alpha=0.6)
    ax.set_xticks(range(0, len(quotes.index), SCALE))
    ax.set_ylabel('Quote')
    ax.grid(True)

    bc = volume_overlay(ax2,
                        quotes['open'],
                        quotes['close'],
                        quotes['volume'],
                        colorup=COLORUP,
                        colordown=COLORDOWN,
                        width=0.5,
                        alpha=0.6)
    ax2.add_collection(bc)
    ax2.set_xticks(range(0, len(quotes.index), SCALE))
    ax2.set_xticklabels(quotes.index[::SCALE], rotation=30)
    ax2.grid(True)
    plt.subplots_adjust(hspace=0.01)
    plt.show()
Esempio n. 8
0
    def plot_ohlcv(self, df):

        fig, ax = plt.subplots()

        # Plot the candlestick
        candlestick2_ohlc(ax,
                          df['open'],
                          df['high'],
                          df['low'],
                          df['close'],
                          width=1,
                          colorup='g',
                          colordown='r',
                          alpha=0.5)

        # 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])

        # Add a seconds axis for the volume overlay
        ax2 = ax.twinx()

        ax2.set_position(
            matplotlib.transforms.Bbox([[0.125, 0.1], [0.9, 0.26]]))

        # Plot the volume overlay
        bc = volume_overlay(ax2,
                            df['open'],
                            df['close'],
                            df['volume'],
                            colorup='g',
                            alpha=0.5,
                            width=1)

        ax.xaxis.set_major_locator(ticker.MaxNLocator(6))

        def mydate(x, pos):
            try:
                return df.index[int(x)]
            except IndexError:
                return ''

        ax.xaxis.set_major_formatter(ticker.FuncFormatter(mydate))
        plt.margins(0)
        plt.show()
Esempio n. 9
0
def plot_with_price(quotes, save_to_file=None, min_max=[]):

    # fig = plt.figure()

    fig, ax = plt.subplots(figsize=(30, 15))

    # ax.set_xlim([1,2])

    # ax.set_ylim(min_max)

    candlestick2_ohlc(ax,
                      quotes['open'],
                      quotes['high'],
                      quotes['low'],
                      quotes['close'],
                      width=0.6)

    xdate = [i for i in quotes.index]

    ax.xaxis.set_major_locator(ticker.MaxNLocator(6))

    def mydate(x, pos):
        try:
            return xdate[int(x)]
        except IndexError:
            return ''

    ax.xaxis.set_major_formatter(ticker.FuncFormatter(mydate))

    ax2 = ax.twinx()
    # ax2.set_ylim([0,5000])
    # Plot the volume overlay
    bc = volume_overlay(ax2,
                        quotes['open'],
                        quotes['close'],
                        quotes['volume'],
                        colorup='g',
                        alpha=0.1,
                        width=1)
    ax2.add_collection(bc)

    fig.autofmt_xdate()
    fig.tight_layout()

    # plt.show()
    if (save_to_file is not None):
        plt.savefig(save_to_file)
Esempio n. 10
0
def chart(symbol):
	data = df[df['<Ticker>'] == symbol][['<DTYYYYMMDD>','<Open>','<High>','<Low>','<Close>','<Volume>']]
	fig = plt.figure()
	ax = plt.subplot2grid((4,4), (0,0), rowspan=3, colspan=4)
	data['<DTYYYYMMDD>'] = data['<DTYYYYMMDD>'].apply(lambda x: datetime.strptime(str(x), '%Y%m%d'))
	data['<DTYYYYMMDD>'] = data['<DTYYYYMMDD>'].map(dt.date2num)

	candlestick_ohlc(ax, data.values, width=0.5, colorup='#53c156', colordown='#ff1717')
	ax.set_title(symbol)
	ax.set_ylabel('Price')
	ax.set_xlabel('Date')
	ax.axes.get_xaxis().set_visible(False)

	ax2 = plt.subplot2grid((4,4), (3,0), rowspan=1, colspan=4)
	bc = volume_overlay(ax2, data['<Open>'][::-1], data['<Close>'][::-1], data['<Volume>'][::-1], colorup='g', alpha=0.5, width=1)
	ax2.add_collection(bc)
	# ax2.xaxis_date()
	# ax2.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
	# fig.autofmt_xdate()
	# ax2.grid(True)
	plt.show()
	return data
Esempio n. 11
0
 def plot(self, widget):
     self.widget = widget
     finance.volume_overlay(widget, self.open, self.close, self.volume,
                            self.colorup, self.colordown, self.width)
Esempio n. 12
0
                       transform=axMiddle.transAxes)


    # now do the moviing average.  I'll use a convolution to simulate a
    # real moving average
    ma5  = movavg(vopens, 5)
    ma20 = movavg(vopens, 20)
    axMiddle.plot(vind[5-1:], ma5,   'b', linewidth=1)
    axMiddle.plot(vind[20-1:], ma20, 'r', linewidth=1)
    
    axMiddle.set_ylim((20, 32))
    axMiddle.set_yticks((25,30))

    # Now do the volume overlay

    bars = volume_overlay(axMiddleVol, opens, closes, volumes, alpha=0.5)
    axMiddleVol.set_ylim((0, 3*max(vvolumes)))  # use only a third of the viewlim


if 1:  ############### Lower axes #################

    # make up two signals; I don't know what the signals are in real life
    # so I'll just illustrate the plotting stuff
    s1 = random_signal(len(vind), 10)
    s2 = random_signal(len(vind), 20)

    axLower.plot(vind, s1, color=purple)
    axLower.plot(vind, s2, color='k', linewidth=1.0)
    s3 = s2-s1
    axLower.plot(vind, s3, color='#cccc99')  # wheat
    bars = index_bar(axLower, s3, width=2, alpha=0.5,
Esempio n. 13
0
                       fontsize=textsize,
                       transform=axMiddle.transAxes)

    # now do the moviing average.  I'll use a convolution to simulate a
    # real moving average
    ma5 = movavg(vopens, 5)
    ma20 = movavg(vopens, 20)
    axMiddle.plot(vind[5 - 1:], ma5, 'b', linewidth=1)
    axMiddle.plot(vind[20 - 1:], ma20, 'r', linewidth=1)

    axMiddle.set_ylim((20, 32))
    axMiddle.set_yticks((25, 30))

    # Now do the volume overlay

    bars = volume_overlay(axMiddleVol, opens, closes, volumes, alpha=0.5)
    axMiddleVol.set_ylim(
        (0, 3 * max(vvolumes)))  # use only a third of the viewlim

if 1:  ############### Lower axes #################

    # make up two signals; I don't know what the signals are in real life
    # so I'll just illustrate the plotting stuff
    s1 = random_signal(len(vind), 10)
    s2 = random_signal(len(vind), 20)

    axLower.plot(vind, s1, color=purple)
    axLower.plot(vind, s2, color='k', linewidth=1.0)
    s3 = s2 - s1
    axLower.plot(vind, s3, color='#cccc99')  # wheat
    bars = index_bar(axLower,
Esempio n. 14
0
#new_xticks = [datetime.date.isoformat(num2date(d)) for d in xt]
#ax1.set_xticklabels(new_xticks, rotation=45, horizontalalignment='right')

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

xl = ax1.get_xlim()
ax1.set_xlim(xl[0], 3 * xl[1])

ax2 = ax1.twinx()
bc = volume_overlay(ax2,
                    input_df.open,
                    input_df.close,
                    input_df.volume,
                    colorup='#0d8cec',
                    colordown='#ff82c7',
                    alpha=0.1,
                    width=1)
ax2.add_collection(bc)
'''
ax3 = plt.subplot(212, sharex=ax1)
ax3.grid()
ax3.plot(input_df.close, color="black")
ax3.plot(log_bband_middle, color="red")
ax3.fill_between(log_bband_middle.index, log_bband_upper.values.flatten(), log_bband_lower.values.flatten(),
                 facecolor="dodgerblue", alpha=0.5)
ax3.legend(["Close", "Middle", "Bollinger (2-SD)"], loc="upper left", fontsize=10)
ax3.set_ylabel("Log price")
ax3.set_xlabel("Time")
                     BB20[:, 0],
                     BB20[:, 2],
                     facecolor='#cccccc',
                     alpha=0.5)

    ax0.set_xticks(tickindex)
    ax0.set_xticklabels(ticknames)
    ax0.format_coord = format_coord1
    ax0.legend(loc='best', shadow=True, fancybox=True)
    ax0.set_ylabel('Price($)', fontsize=16)
    ax0.set_title(ticker, fontsize=24, fontweight='bold')
    ax0.grid(True)

    ax1 = plt.subplot(gs[1], sharex=ax0)

    vc = volume_overlay(ax1, r.open, r.close, r.volume, colorup='g', width=1)

    ax1.set_xticks(tickindex)
    ax1.set_xticklabels(ticknames)
    ax1.format_coord = format_coord2

    ax1.tick_params(axis='x', direction='out', length=5)
    ax1.yaxis.set_major_formatter(millionformatter)
    ax1.yaxis.tick_right()
    ax1.yaxis.set_label_position("right")
    ax1.set_ylabel('Volume', fontsize=16)
    ax1.grid(True)

    plt.setp(ax0.get_xticklabels(), visible=False)

    plt.show()
Esempio n. 16
0
    def __plot(self, stock, figsize, qfq, index, index_overlay=False):
        stock_data = stock.qfq_data if qfq else stock.hist_data
        stock_data = stock_data.sort_index(ascending=True, inplace=False)
        index_data = index.hist_data.sort_index(ascending=True)
        data_err_found = False

        fp = FontProperties(fname='simsun.ttc')
        fig = plt.figure(figsize=figsize, dpi=100)
        fig.subplots_adjust(left=.10, bottom=.09, right=.93, top=.95, wspace=.20, hspace=0)
        gs = gridspec.GridSpec(3, 1, height_ratios=[4, 1, 1])

        # draw hist price diagram
        ax_price = plt.subplot(gs[0])
        candlestick2_ochl(ax_price, stock_data.open, stock_data.high, stock_data.low, stock_data.close,
                          width=.75, colorup='g', colordown='r', alpha=0.75)

        for i, factor in enumerate(stock_data.factor):
            if i != 0 and round(factor, 2) != round(stock_data.factor[i-1], 2):
                ax_price.annotate('Q(f=%.3f)' % factor,
                    xy=(i, stock_data.open[i]), xycoords='data',
                    xytext=(0, stock_data.high.max()/10), textcoords='offset points', ha='center', va='bottom',
                    bbox=dict(boxstyle='round,pad=0.2', fc='blue', alpha=0.3),
                    arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"),
                    fontsize=10, color='c')

        for i, date in enumerate(stock_data.index):
            if i == stock_data.index.size -1:
                break

            next_date = stock_data.index[i + 1]
            if date not in index_data.index or next_date not in index_data.index:
                logging.warning('%s: data date %s or %s is not in index %s, probably additional wrong data'
                                % (stock, date, next_date, index.name))
                data_err_found = True
                break

            index_loc = index_data.index.get_loc(date)
            if index_data.index[index_loc+1] != stock_data.index[i+1]:
                suspended_days = index_data.index.get_loc(next_date) - index_loc
                ax_price.annotate('suspend %ddays [%s - %s]' % (suspended_days, date, stock_data.index[i+1]),
                                  xy=(i, stock_data.open[i]), xycoords='data',
                                  xytext=(0, stock_data.high.max()/10), textcoords='offset points', ha='center', va='bottom',
                                  bbox=dict(boxstyle='round,pad=0.2', fc='yellow', alpha=0.3),
                                  arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"),
                                  fontsize=10, color='y')

        left, height, top = 0.025, 0.03, 0.9
        t1 = ax_price.text(left, top, '%s-%s,%s,%s' % (stock.code, stock.name, stock.area, stock.industry),
                           fontproperties=fp, fontsize=8, transform=ax_price.transAxes)
        ax_price.text(left, top - height, 'pe=%.2f' % (stock.pe if stock.pe else 0.0), fontsize=8, transform=ax_price.transAxes)
        ax_price.text(left, top - 2*height, 'nmc=%.2f亿' % (stock.nmc/10000 if stock.nmc else 0.0), fontproperties=fp, fontsize=8, transform=ax_price.transAxes)
        ax_price.text(left, top - 3*height, 'mktcap=%.2f亿' % (stock.mktcap/10000 if stock.mktcap else 0.0), fontproperties=fp, fontsize=8, transform=ax_price.transAxes)

        if not qfq:
            ax_price.text(left, top - 4*height, 'EMA(5)', color='b', fontsize=8, transform=ax_price.transAxes)
            ax_price.text(left, top - 5*height, 'EMA(10)', color='y', fontsize=8, transform=ax_price.transAxes)
            ax_price.text(left, top - 6*height, 'EMA(20)', color='g', fontsize=8, transform=ax_price.transAxes)
            ax_price.text(left, top - 7*height, 'EMA(30)', color='r', fontsize=8, transform=ax_price.transAxes)
            ax_price.plot(stock_data.ma5.values, color='b', lw=1)
            ax_price.plot(stock_data.ma10.values, color='y', lw=1)
            ax_price.plot(stock_data.ma20.values, color='g', lw=1)
            ax_price.plot(stock.ma30.sort_index(ascending=True).close.values, color='r', lw=1)
            #ax_price.plot(stock.ma60.sort_index(ascending=True).close.values, color='r', lw=1)
            #ax_price.plot(stock.ma120.sort_index(ascending=True).close.values, color='r', lw=1)


        s = '%s O:%1.2f H:%1.2f L:%1.2f C:%1.2f, V:%1.1fM Chg:%+1.2f' % (
            stock_data.index[-1],
            stock_data.open[-1], stock_data.high[-1], stock_data.low[-1], stock_data.close[-1],
            stock_data.volume[-1] * 1e-6,
            stock_data.close[-1] - stock_data.open[-1])
        ax_price.text(0.5, top, s, fontsize=8, transform=ax_price.transAxes)

        plt.ylabel('Price')
        plt.ylim(ymin=stock_data.low.min()-stock_data.low.min()/30, ymax=stock_data.high.max()+stock_data.high.max()/30)
        ax_price.grid(True)

        if qfq:
            plt.title('Forward Adjusted History Price')
        else:
            plt.title('History Price')

        xrange = range(0, stock_data.index.size, max(int(stock_data.index.size / 5), 5))
        plt.xticks(xrange, [stock_data.index[loc] for loc in xrange])
        plt.setp(ax_price.get_xticklabels(), visible=False)

        # draw index overlay
        if index_overlay:
            common_index = index_data.index.intersection(stock_data.index)
            common_data = index_data.join(DataFrame(index=common_index), how='inner')
            common_data.sort_index(ascending=True, inplace=True)
            ax_index = ax_price.twinx()
            candlestick2_ochl(ax_index, common_data.open, common_data.high, common_data.low, common_data.close,
                              width=.75, colorup='g', colordown='r', alpha=0.35)
            ax_index.set_ylabel('Index(%s)' % index.name, fontproperties=fp)
            ax_index.set_ylim(ymin=common_data.low.min(), ymax=common_data.high.max())

        # draw hist volume diagram
        ax_volume = plt.subplot(gs[1], sharex=ax_price)
        volume_overlay(ax_volume, stock_data.open, stock_data.close, stock_data.volume,
                       width=.75, colorup='g', colordown='r', alpha=0.75)
        ax_volume.yaxis.set_major_formatter(FuncFormatter(lambda x, pos: '%1.1fM' % (x*1e-6)
                       if stock_data.volume.max()>1e6 else '%1.1fK' % (x*1e-3)))

        if not qfq:
            ax_volume.plot(stock_data.v_ma5.values, color='b', lw=1)
            ax_volume.plot(stock_data.v_ma10.values, color='y', lw=1)
            ax_volume.plot(stock_data.v_ma20.values, color='r', lw=1)
        plt.setp(ax_volume.get_xticklabels(), visible=False)
        ax_volume.yaxis.set_ticks_position('both')
        ax_volume.set_ylabel('Volume')
        ax_volume.grid(True)

        # draw hist turnover diagram
        ax_turnover = plt.subplot(gs[2], sharex=ax_price)
        volume_overlay(ax_turnover, stock_data.open, stock_data.close, stock_data.turnover,
                       width=.75, colorup='g', colordown='r', alpha=0.75)
        ax_turnover.xaxis.set_major_formatter(FuncFormatter(lambda x, pos: '%s' % (stock_data.index[x])))
        ax_turnover.yaxis.set_major_formatter(FuncFormatter(lambda x, pos: '%.2f%%' % (x)))
        for label in ax_turnover.xaxis.get_ticklabels():
            label.set_rotation(0)
        ax_turnover.set_xlabel('Date')
        ax_turnover.yaxis.set_ticks_position('both')
        ax_turnover.set_ylabel('Turnover')
        ax_turnover.grid(True)
        # plt.legend(prop=fp)

        # show error warning
        if data_err_found:
            ax_price.text(1.01, 0.02, '(>_<) ', color='r', fontsize=10, transform=ax_price.transAxes)

        self._ax_price = ax_price
        self._ax_volume = ax_volume
        self._ax_turnover = ax_turnover
    ax0.legend(loc='best')
    ax0.set_ylabel(u'株価', fontproperties=fp, fontsize=16)

    #ax0.xaxis_date()
    #ax0.autoscale_view()

    ax1 = plt.subplot(gs[1], sharex=ax0)

    #vc = volume_overlay3(ax1, quotes, colorup='k', colordown='r', width=4, alpha=1.0)
    #volume_overlay(ax1, opens, closes, volumes, colorup='g', alpha=0.5, width=1)
    #ax1.set_xticks(ds)

    vc = volume_overlay(ax1,
                        opens,
                        closes,
                        volumes,
                        colorup='g',
                        alpha=0.5,
                        width=1)
    ax1.add_collection(vc)

    ax1.xaxis.set_major_locator(get_locator())
    ax1.xaxis.set_major_formatter(formatter)
    ax1.yaxis.set_major_formatter(millionformatter)
    ax1.yaxis.tick_right()
    ax1.set_ylabel(u'出来高', fontproperties=fp, fontsize=16)

    plt.setp(ax0.get_xticklabels(), visible=False)
    plt.setp(ax1.get_xticklabels(), rotation=30, horizontalalignment='left')
    plt.legend(prop=fp)
Esempio n. 18
0
def Ohlc(Open,High,Low,Close,Volume,MACD):
    # 出来高,MACDのy軸ラベルとチャート,出来高のx軸のラベルを非表示
    ax.tick_params(labelbottom="off")
    ax2.tick_params(labelbottom="off",labelleft='off')
    mpf.candlestick2_ohlc(ax,Open,High,Low,Close,width=0.8,colorup='#008800',colordown='#ff0000',alpha=0.75)
    mpf.volume_overlay(ax2,Open,Close,Volume,width=1,colorup='#008800',colordown='#ff0000')
Esempio n. 19
0
                   rotation=90)  # 2017.12.31
ax.set_xlim([0, df.shape[0]])  # 横軸の範囲はデータの個数(df.shape[0]個)までに変更しておく
ax.set_ylabel("Price")

plt.grid(color='y', linestyle='-')

# ローソク足を上側75%に収める
bottom, top = ax.get_ylim()
ax.set_ylim(bottom - (top - bottom) / 4, top)

# 出来高のチャートをプロット
ax2 = ax.twinx()
volume_overlay(ax2,
               df["Open"],
               df["Adj Close"],
               df["Volume"],
               width=1,
               colorup="g",
               colordown="g")
ax2.set_xlim([0, df.shape[0]])

# 出来高チャートは下側25%に収める
ax2.set_ylim([0, df["Volume"].max() * 4])
ax2.set_ylabel("Volume")
formatter = EngFormatter()
ax2.yaxis.set_major_formatter(formatter)
plt.show()
""" Plot Adj Close Graph"""
# 5days, 25days移動平均の計算
MA5 = stock_name['Adj Close'].rolling(window=5).mean()
MA25 = stock_name['Adj Close'].rolling(window=25).mean()
Esempio n. 20
0
    ax0.plot(range(len(r.date)), BB20[:,0], color='black', lw=2, ls='--', label='BBU (20)')
    ax0.plot(range(len(r.date)), BB20[:,1], color='black', lw=2, ls='--', label='BBM (20)')
    ax0.plot(range(len(r.date)), BB20[:,2], color='black', lw=2, ls='--', label='BBD (20)')
    ax0.fill_between(range(len(r.date)), BB20[:,0],BB20[:,2], facecolor='#cccccc', alpha=0.5)

    ax0.set_xticks(tickindex)
    ax0.set_xticklabels(ticknames)
    ax0.format_coord=format_coord1
    ax0.legend(loc='best', shadow=True, fancybox=True)
    ax0.set_ylabel('Price($)', fontsize=16)
    ax0.set_title(ticker, fontsize=24, fontweight='bold')
    ax0.grid(True)

    ax1 = plt.subplot(gs[1], sharex=ax0)

    vc = volume_overlay(ax1, r.open, r.close, r.volume, colorup='g', width=1)

    ax1.set_xticks(tickindex)
    ax1.set_xticklabels(ticknames)
    ax1.format_coord=format_coord2

    ax1.tick_params(axis='x',direction='out',length=5)
    ax1.yaxis.set_major_formatter(millionformatter)
    ax1.yaxis.tick_right()
    ax1.yaxis.set_label_position("right")
    ax1.set_ylabel('Volume', fontsize=16)
    ax1.grid(True)

    plt.setp(ax0.get_xticklabels(), visible=False)

    plt.show()
Esempio n. 21
0
 def plot(self, widget):
     import matplotlib.finance as finance
     self.widget = widget
     finance.volume_overlay(widget, self.open, self.close, self.volume,
                            self.colorup, self.colordown, self.width)
Esempio n. 22
0
def kplot(df: pd.DataFrame, picturePath: str):
    """根据给的120day的交易日数据画出K线图
    :param df: 传进的DataFrame是120天的交易日日数据
    :param picturePath: 图片保存路径
    """
    df['ii'] = range(len(df))
    ohlc = df['ii'].map(lambda x: tuple(df.iloc[
        x][['时间', '开盘价(元)', '最高价(元)', '最低价(元)', '收盘价(元)']])).tolist()

    # 生成了120个(i,time,open,high,low,close)的tuple 这里注意这里处理了nan
    weekday_ohlc = [
        tuple([i] +
              list([0 if str(x) == 'nan' else float(x) for x in item[1:]]))
        for i, item in enumerate(ohlc)
    ]
    week_line = [
        0 if str(x) == 'nan' else float(x) for x in df['周線'].tolist()
    ]  # 一列的list
    month_line = [
        0 if str(x) == 'nan' else float(x) for x in df['月線'].tolist()
    ]
    quarter_line = [
        0 if str(x) == 'nan' else float(x) for x in df['季線'].tolist()
    ]
    half_line = [
        0 if str(x) == 'nan' else float(x) for x in df['半年線'].tolist()
    ]
    year_line = [0 if str(x) == 'nan' else float(x) for x in df['年線'].tolist()]
    open = [0 if str(x) == 'nan' else float(x) for x in df['开盘价(元)'].tolist()]
    close = [0 if str(x) == 'nan' else float(x) for x in df['收盘价(元)'].tolist()]
    volume = [
        0 if str(x) == 'nan' else float(x) for x in df['成交量(股)'].tolist()
    ]
    kdj_k = [0 if str(x) == 'nan' else float(x) for x in df['KDJ-K'].tolist()]
    kdj_d = [0 if str(x) == 'nan' else float(x) for x in df['KDJ-D'].tolist()]
    kdj_j = [0 if str(x) == 'nan' else float(x) for x in df['KDJ-J'].tolist()]

    fig = plt.figure(figsize=(18, 10))  # 设置形状的宽度和高度
    p1 = fig.add_axes([0, 0.6, 1, 0.6])
    p1.axes.get_xaxis().set_visible(False)
    plt.xlim(0, len(weekday_ohlc) - 1)  # 设置一下x轴的范围
    candlestick_ohlc(p1, weekday_ohlc, width=0.6, colorup='r', colordown='g')

    # 年线
    plt.plot(week_line, linewidth=1.5, color='orange')
    plt.plot(month_line, linewidth=1.5, color='cyan')
    plt.plot(quarter_line, linewidth=1.5, color='magenta')
    plt.plot(half_line, linewidth=1.5, color='navy')
    plt.plot(year_line, linewidth=1.5, color='olive')

    p2 = fig.add_axes([0, 0.4, 1, 0.2])
    p2.axes.get_xaxis().set_visible(False)
    plt.xlim(0, len(weekday_ohlc) - 1)  # 再次设置一下x轴的范围
    vc = volume_overlay(p2,
                        open,
                        close,
                        volume,
                        colorup='g',
                        alpha=0.5,
                        width=1)  # 成交量

    p3 = fig.add_axes([0, 0.2, 1, 0.2])
    p3.axes.get_xaxis().set_visible(False)  # 关闭x轴
    plt.xlim(0, len(weekday_ohlc) - 1)  # 再次设置一下x轴的范围
    plt.plot(kdj_k, linewidth=2, color='yellow')
    plt.plot(kdj_d, linewidth=2, color='blue')
    plt.plot(kdj_j, linewidth=2, color='purple')

    plt.savefig(picturePath, bbox_inches='tight', pad_inches=0)  #保存图片

    plt.close()
Esempio n. 23
0
 def plot(self, widget, colorup = 'r', colordown = 'b', width = 1):
     """docstring for plot""" 
     finance.volume_overlay(widget, self.open, self.close, self.volume, colorup, colordown, width)
Esempio n. 24
0
data = pd.read_csv('sh1.csv')
num = 100  #画前num个交易日的图
fig = plt.figure(figsize=(15, 8))
ax = fig.add_axes([0, 0.2, 1, 0.5])
ax2 = fig.add_axes([0, 0, 1, 0.2])
mpf.candlestick2_ochl(ax,
                      data['open'][:num],
                      data['close'][:num],
                      data['high'][:num],
                      data['low'][:num],
                      width=0.5,
                      colorup='r',
                      colordown='g',
                      alpha=1)
ax.set_xticks(range(0, num, 10))
ax.grid(True)

mpf.volume_overlay(ax2,
                   data['open'][:num],
                   data['close'][:num],
                   data['volume'][:num],
                   colorup='r',
                   colordown='g',
                   width=0.5,
                   alpha=0.8)
ax2.set_xticks(range(0, num, 10))
ax2.set_xticklabels(data['date'][::10], rotation=30)
ax2.grid(True)

#plt.subplots_adjust(hspace=0)
Esempio n. 25
0
 def plot(self, widget):
     import matplotlib.finance as finance
     self.widget = widget
     finance.volume_overlay(widget, self.open, self.close, self.volume,
                            self.colorup, self.colordown, self.width)
    def createFig(self):
        """
        生成图片:
        1、K线图,包含唐奇安通道,成交量, 入场位置
        2、ATR图
        3、MACD图
        :return:
        """
        for code, data in self.stock_data.items():

            fig = plt.figure(figsize=(10, 6))
            gs = gridspec.GridSpec(4, 1, height_ratios=[2, 0.4, 0.8, 0.8])
            ax = plt.subplot(gs[0])
            ax2 = plt.subplot(gs[1])
            ax3 = plt.subplot(gs[2])
            ax4 = plt.subplot(gs[3])

            # 绘制K线图
            mpf.candlestick2_ochl(ax,
                                  data['open'],
                                  data['close'],
                                  data['high'],
                                  data['low'],
                                  width=0.6,
                                  colorup='red',
                                  colordown='green',
                                  alpha=1)
            # 绘制入场点
            entry_date = self.portfolio[code]['entry_date']
            entry_date = pd.to_datetime(entry_date, format='%Y-%m-%d')
            print entry_date

            entry_price = self.portfolio[code]['entry_price']

            #            for i in range(len(entry_date)):
            #                ax.annotate("{}".format(entry_price[i]), xy=(entry_date[i], entry_price[i] * 0.95), xytext=(entry_date[i], entry_price[i]*0.9),
            #                                 arrowprops=dict(facecolor='R', shrink = 0.05),
            #                                 horizontalalignment='left', verticalalignment='top')
            #                ax.axhline(entry_price[i], xmin = 1 - self.delta_days * 1.0 /self.back_days,color="y", linestyle="-.")
            # 绘制唐奇安通道

            data['date'] = pd.to_datetime(data['date'], format='%Y-%m-%d')
            print data['date']
            #datetime.datetime.strptime(last, '%Y-%m-%d')
            ax.xaxis.set_major_formatter(mdate.DateFormatter('%b %d', None))

            ax.plot(data['date'],
                    data['d_up'],
                    color='r',
                    label='Up: {} days'.format(self.D_Channel['up']))
            ax.plot(data['date'],
                    data['d_down'],
                    color='b',
                    label='Down: {} days'.format(self.D_Channel['down']))
            ax.legend(loc=0)
            ax.set_title(code)
            ax.grid(True)

            # 绘制成交量图
            mpf.volume_overlay(ax2,
                               data['open'],
                               data['close'],
                               data['volume'],
                               colorup='r',
                               colordown='g',
                               width=0.2,
                               alpha=1)
            ax2.grid(True)

            # 绘制MACD图
            ax3.plot(data['diff'], color='y', label='diff')
            ax3.plot(data['dea'], color='b', label='dea')
            ax3.legend(loc=0)
            ax3.grid(True)

            # 绘制ATR图
            ax4.plot(data['date'], data['atr'], color='r', label='atr')
            ax4.legend(loc=0)
            ax4.set_xticks(range(0, len(data['date']), 5))
            ax4.set_xticklabels(data['date'][::5], rotation=45)
            ax4.grid(True)

            plt.subplots_adjust(hspace=0.09)

            # 保存图片
            figPath = os.getcwd() + '/{}.png'.format(code)
            fig.savefig(figPath, dpi=150, bbox_inches='tight')
            self.fig_attachs.append(figPath)
    ax0.autoscale_view()

    ax0.plot(ma5, color='b', lw=2)
    ax0.plot(ma25, color='r', lw=2)

    ax0.legend(loc='best')
    ax0.set_ylabel(u'株価', fontproperties = fp, fontsize=16)

    #ax0.xaxis_date()
    #ax0.autoscale_view()

    ax1 = plt.subplot(gs[1], sharex=ax0)

    #vc = volume_overlay3(ax1, quotes, colorup='k', colordown='r', width=4, alpha=1.0)
    #volume_overlay(ax1, opens, closes, volumes, colorup='g', alpha=0.5, width=1)
    #ax1.set_xticks(ds)

    vc = volume_overlay(ax1, opens, closes, volumes, colorup='g', alpha=0.5, width=1)
    ax1.add_collection(vc)

    ax1.xaxis.set_major_locator(get_locator())
    ax1.xaxis.set_major_formatter(formatter)
    ax1.yaxis.set_major_formatter(millionformatter)
    ax1.yaxis.tick_right()
    ax1.set_ylabel(u'出来高', fontproperties = fp, fontsize=16)

    plt.setp(ax0.get_xticklabels(), visible=False)
    plt.setp(ax1.get_xticklabels(), rotation=30, horizontalalignment='left')
    plt.legend(prop = fp);

    plt.show()
Esempio n. 28
0
def gen_candlestick(d_frame,
                    mode='c',
                    period_list=[],
                    title='',
                    file_name='~/tmp_plot.png',
                    plot_period=None,
                    plot_volume=True,
                    fig_ratio=None,
                    sr_list=None,
                    plot_columns=[],
                    plot_columns_subplot=[]):
    # Vars
    l_bar = ''.join(['-'] * 60)
    def_fig_dim = plt.rcParams['figure.figsize']
    def_font_size = plt.rcParams['font.size']
    def_bars = 50
    def_n_locs = 6

    # Check period list
    if period_list == None:
        period_list = []
    # endif
    if sr_list == None:
        sr_list = []
    # endif

    # Make a copy
    d_frame_c_c = d_frame.copy()

    # Slice the frame which needs to be plotted
    if plot_period:
        d_frame_c = d_frame_c_c[-plot_period:].copy()
        fig_r = int(plot_period * 1.0 / def_bars) + 1
    else:
        d_frame_c = d_frame_c_c.copy()
        fig_r = 1.0
    # endif

    # Check if fig_ratio is passed directly
    if fig_ratio:
        fig_ratio = float(fig_ratio)
    else:
        fig_ratio = fig_r
    # endif

    # Get date list and rmean function
    xdate = [datetime.datetime.fromtimestamp(t) for t in d_frame_c['T']]
    rmean = utils.g_rmean_f(type='e')

    def mydate(x, pos):
        try:
            return xdate[int(x)]
        except IndexError:
            return ''
        # endtry

    # enddef
    def r_ns_tr(p_f, indx=-1, rnd=2):
        return str(round(p_f.iloc[indx], rnd))

    # enddef

    # Calculate new figure dimention
    new_fig_dim = [fig_ratio * x for x in def_fig_dim]
    sub_plot_1 = 211 if len(plot_columns_subplot) > 0 else 111
    sub_plot_2 = 212 if len(plot_columns_subplot) > 0 else 111

    # Pre-processing
    fig = plt.figure(figsize=new_fig_dim)
    ax = fig.add_subplot(sub_plot_1)
    plt.xticks(rotation=45)
    plt.xlabel("Date")
    plt.ylabel("Price")
    #plt.title(title)

    # Title for close
    title2 = '{}:{}'.format('C', r_ns_tr(d_frame_c['c']))

    # Plot candlestick
    candlestick2_ohlc(ax,
                      d_frame_c['o'],
                      d_frame_c['h'],
                      d_frame_c['l'],
                      d_frame_c['c'],
                      width=0.6)
    ## Plot mas
    for period_this in period_list:
        label = 'ema_' + str(period_this)
        d_s = utils.s_mode(d_frame_c, mode)
        d_frame_c[label] = rmean(d_s, period_this)
        d_frame_c.reset_index(inplace=True, drop=True)
        d_frame_c[label].plot(ax=ax)
        title2 = title2 + ' {}:{}'.format(label, r_ns_tr(d_frame_c[label]))
    # endfor
    # Add sr lines if passed
    for l_this in sr_list:
        d_frame_c[str(l_this)] = [l_this] * len(d_frame_c.index)
        d_frame_c[str(l_this)].plot(ax=ax)
    # endfor
    # Plot specific columns if passed
    for column_t in plot_columns:
        d_frame_c.reset_index(inplace=True, drop=True)
        d_frame_c[column_t].plot(ax=ax)
    # endfor
    # Plot overlay columns
    if len(plot_columns_subplot) > 0:
        ax3 = fig.add_subplot(sub_plot_2)
        for column_t in plot_columns_subplot:
            d_frame_c[column_t].reset_index(inplace=True, drop=True)
            d_frame_c[column_t].plot(ax=ax3)
        # endfor

        # Set axes
        ax3.xaxis.set_major_locator(ticker.MaxNLocator(def_n_locs * fig_ratio))
        ax3.xaxis.set_major_formatter(ticker.FuncFormatter(mydate))
    # endif
    if plot_volume:
        # Plot volume
        v_data = [0 if j == 'n/a' else j for j in d_frame_c['v']]
        ax2 = ax.twinx()
        bc = volume_overlay(ax2,
                            d_frame_c['o'],
                            d_frame_c['c'],
                            v_data,
                            colorup='g',
                            alpha=0.2,
                            width=0.6)
        ax2.add_collection(bc)
    # endif

    # Post-processing
    # Set grid
    plt.grid()

    # Set titles
    font_size = int(fig_ratio * def_font_size * 0.7)
    plt.title(title + '\n{}\n'.format(l_bar) + '\n'.join(wrap(title2, 60)),
              fontsize=font_size)

    # Set axes
    ax.xaxis.set_major_locator(ticker.MaxNLocator(def_n_locs * fig_ratio))
    ax.xaxis.set_major_formatter(ticker.FuncFormatter(mydate))
    fig.autofmt_xdate()
    #fig.tight_layout()

    # Plot figure
    plt.savefig(os.path.expanduser(file_name))
    # Clear plot to save memory
    plt.close()
Esempio n. 29
0
    t4 = axMiddle.text(0.4, top, s, fontsize=textsize, transform=axMiddle.transAxes)

    # now do the moviing average.  I'll use a convolution to simulate a
    # real moving average
    ma5 = movavg(r.adj_close, 5)
    ma20 = movavg(r.adj_close, 20)
    axMiddle.plot(vind[5 - 1 :], ma5, "b", linewidth=1)
    axMiddle.plot(vind[20 - 1 :], ma20, "r", linewidth=1)

    axMiddle.set_ylim((300, 800))
    axMiddle.set_yticks(np.arange(800, 800, 100))

    # Now do the volume overlay

    # todo - this is broken
    bars = volume_overlay(axMiddleVol, r.open, r.close, r.volume, alpha=0.5)
    # axMiddleVol.set_ylim(0, 3*r.volume.max())  # use only a third of the viewlim


if 1:  ############### Lower axes #################

    # make up two signals; I don't know what the signals are in real life
    # so I'll just illustrate the plotting stuff
    s1 = random_signal(N, 10)
    s2 = random_signal(N, 20)

    axLower.plot(vind, s1, color=purple)
    axLower.plot(vind, s2, color="k", linewidth=1.0)
    s3 = s2 - s1
    axLower.plot(vind, s3, color="#cccc99")  # wheat
    bars = index_bar(axLower, s3, width=2, alpha=0.5, facecolor="#3087c7", edgecolor="#cccc99")
Esempio n. 30
0
                       transform=axMiddle.transAxes)

    # now do the moviing average.  I'll use a convolution to simulate a
    # real moving average
    ma5 = movavg(r.adj_close, 5)
    ma20 = movavg(r.adj_close, 20)
    axMiddle.plot(vind[5 - 1:], ma5, 'b', linewidth=1)
    axMiddle.plot(vind[20 - 1:], ma20, 'r', linewidth=1)

    axMiddle.set_ylim((300, 800))
    axMiddle.set_yticks(np.arange(800, 800, 100))

    # Now do the volume overlay

    # todo - this is broken
    bars = volume_overlay(axMiddleVol, r.open, r.close, r.volume, alpha=0.5)
    #axMiddleVol.set_ylim(0, 3*r.volume.max())  # use only a third of the viewlim

if 1:  ############### Lower axes #################

    # make up two signals; I don't know what the signals are in real life
    # so I'll just illustrate the plotting stuff
    s1 = random_signal(N, 10)
    s2 = random_signal(N, 20)

    axLower.plot(vind, s1, color=purple)
    axLower.plot(vind, s2, color='k', linewidth=1.0)
    s3 = s2 - s1
    axLower.plot(vind, s3, color='#cccc99')  # wheat
    bars = index_bar(axLower,
                     s3,
Esempio n. 31
0
 def plot(self, widget):
     finance.volume_overlay(widget, self.open, self.close, self.volume,
                            self.colorup, self.colordown, self.width)
Esempio n. 32
0
 def plot(self, widget, colorup = 'r', colordown = 'b', width = 1):
     """docstring for plot""" 
     finance.volume_overlay(widget, self.open, self.close, self.volume, colorup, colordown, width)