Exemplo n.º 1
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")
Exemplo n.º 2
0
def plotKLine(open, close, high, low, tech):

    fig = plt.figure(figsize=(30, 15))
    y = len(close)
    date = np.linspace(0, y, y)
    candleAr = []
    ax1 = plt.subplot2grid((10, 4), (0, 0), rowspan=5, colspan=4)
    candlestick2_ochl(ax1,
                      open,
                      close,
                      high,
                      low,
                      width=1,
                      colorup='r',
                      colordown='g',
                      alpha=0.75)
    ax2 = plt.subplot2grid((10, 4), (5, 0), rowspan=4, colspan=4, sharex=ax1)
    if 'ATR' in tech.keys():
        ax2.plot(date, tech['ATR'], '-b')
    if 'ad_ATR' in tech.keys():
        ax2.plot(date, tech['ad_ATR'], '-r')
    if 'my_ATR' in tech.keys():
        ax2.plot(date, tech['my_ATR'], '-m')
    if 'short_ATR' in tech.keys():
        ax2.plot(date, tech_1['short_ATR'], '-b')
    if 'long_ATR' in tech.keys():
        ax2.plot(date, tech_1['long_ATR'], '-r')
    if 'close' in tech.keys():
        ax2.plot(date, tech_2['close'], '-b')
    if 'upper' in tech.keys():
        ax2.plot(date, tech_2['upper'], '-r')
    if 'lower' in tech.keys():
        ax2.plot(date, tech_2['lower'], '-r')
Exemplo n.º 3
0
def plot_candle(stock_code):
    # get stock data
    stock_data = pd.read_csv('../data/' + stock_code + '/hist_k_day.csv')

    data_o = stock_data['open']
    data_c = stock_data['close']
    data_h = stock_data['high']
    data_l = stock_data['low']

    # draw candle stick
    fig = plt.figure()
    #ax1 = fig.add_subplot(1,1,1)
    ax1 = fig.add_axes([0.1, 0.2, 0.85, 0.7])
    ax1.set_title(stock_code)
    #ax1.set_xticks(stock_data['date'][0:80])
    ax1.set_ylabel("Price")
    fin.candlestick2_ochl(ax1,
                          stock_data['open'][0:80],
                          stock_data['close'][0:80],
                          stock_data['high'][0:80],
                          stock_data['low'][0:80],
                          width=1,
                          colorup='r',
                          colordown='g',
                          alpha=0.8)

    for label in ax1.xaxis.get_ticklabels():
        label.set_rotation(45)
    plt.grid(True)
    plt.show()
Exemplo n.º 4
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()
Exemplo n.º 5
0
    def draw_klines(df:pd.DataFrame):
        import matplotlib.pyplot as plt
        import matplotlib.finance as mpf
        from matplotlib import ticker
        import matplotlib.dates as mdates
        columns = ['datetime', 'open', 'close', 'high', 'low', 'volume']
        if not set(df.columns).issuperset(columns):
            raise Exception(f'请包含{columns}字段')

        data = df.loc[:, columns]

        data_mat = data.as_matrix().T

        xdate = data['datetime'].tolist()

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


        fig, ax1,  = plt.subplots(figsize=(1200 / 72, 480 / 72))
        plt.title('KLine', fontsize='large',fontweight = 'bold')
        mpf.candlestick2_ochl(ax1, data_mat[1], data_mat[2], data_mat[3], data_mat[4], colordown='#53c156', colorup='#ff1717', width=0.3, alpha=1)
        ax1.grid(True)
        ax1.xaxis.set_major_formatter(ticker.FuncFormatter(mydate))
        ax1.xaxis.set_major_locator(mdates.HourLocator())
        ax1.xaxis.set_major_locator(mdates.MinuteLocator(byminute=[0, 15, 30, 45],
                                                        interval=1))
        ax1.xaxis.set_major_locator(ticker.MaxNLocator(8))
Exemplo n.º 6
0
    def show(self, start, end):
        """
        show plotted graph (Candlestick + Strategy Plot + P&L) between start and end
        :param start: str, 'YYYYMMDD HH:MM:SS'
        :param end: str, 'YYYYMMDD HH:MM:SS'
        :return: None
        """
        start = datetime.strptime(start, '%Y%m%d %H:%M:%S')
        end = datetime.strptime(end, '%Y%m%d %H:%M:%S')
        data_part = self.__data[(self.__data.index >= start)
                                & (self.__data.index <= end)]
        total_value_part = self.__total_value[
            (self.__total_value.index >= start)
            & (self.__total_value.index <= end)]
        if len(self.__plots) > 0:
            plots_part = self.__plots[(self.__plots.index >= start)
                                      & (self.__plots.index <= end)]
        else:
            plots_part = pd.Series(np.nan, index=data_part.index)
        plt.figure(1)
        ax1 = plt.subplot(211)
        candlestick2_ochl(ax1,
                          opens=data_part['OPEN'],
                          closes=data_part['CLOSE'],
                          highs=data_part['HIGH'],
                          lows=data_part['LOW'])
        plt.plot(plots_part)

        plt.subplot(212)
        plt.plot(total_value_part)
        plt.show()
Exemplo n.º 7
0
    def animate(i):
        global data
        global timeframe

        # Scraping page.
        page = requests.get(
            'https://bitcoinwisdom.com/markets/bitstamp/btcusd')
        tree = html.fromstring(page.content)
        p = float(tree.xpath('//*[@id="price"]/text()')[0])
        t = dt.datetime.now()
        columns = ['Time', 'Price']
        data = pd.concat([data, pd.DataFrame([(t, p)], columns=columns)])

        # Resamplig data.
        if len(data) > 1:
            df = data.set_index('Time')
            opensList = list(df.Price.resample(timeframe).first())
            closesList = list(df.Price.resample(timeframe).last())
            highsList = list(df.Price.resample(timeframe).max())
            lowsList = list(df.Price.resample(timeframe).min())

            # Plotting.
            ax1.clear()
            finance.candlestick2_ochl(ax1,
                                      opensList,
                                      closesList,
                                      highsList,
                                      lowsList,
                                      width=0.8,
                                      colorup='k',
                                      colordown='r',
                                      alpha=0.75)
Exemplo n.º 8
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()
Exemplo n.º 9
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)
Exemplo n.º 10
0
    def plot_k_data(self):
        _, axes = plt.subplots(1, 1)
        fin.candlestick2_ochl(axes, self.open, self.close,
                              self.high, self.low, width=0.5,
                              colorup='r', colordown='g')
        self.ema.compute_indicator(self.close, n=24)
        self.ema.plot_indicator(axes)

        plt.show()
Exemplo n.º 11
0
def dwAxO(ax, os, hs, ls, cs):
    mpf.candlestick2_ochl(ax,
                          os,
                          hs,
                          ls,
                          cs,
                          width=0.6,
                          colorup='w',
                          colordown='w',
                          alpha=0.15)
    ax.set_xlim(left=0.0)
Exemplo n.º 12
0
def test_dchannel(ohlc):
    """DCHANNEL test function."""
    dchannel10 = dchannel(ohlc, 10)
    data = pd.concat([ohlc, dchannel10], axis=1)
    # print(data)
    ax1 = plt.subplot2grid((6,4), (0,0), rowspan=6, colspan=6)
    ax1.grid(True)
    candlestick2_ochl(ax1, ohlc["open"], ohlc["close"], ohlc["high"], ohlc["low"], width=0.7, colorup="r", colordown="g")
    ax1.plot(dchannel10)
    plt.title("DCHANNEL Chart")
    plt.show()
Exemplo n.º 13
0
    def plt(self, savefig=False):
        # 動作が重くならないようにクリアする
        plt.clf()
        fig = plt.figure(figsize=(10, 7.5))
        ax = fig.add_subplot(111)
        ax.set_title('code:' + str(self.code), loc='center', fontsize=20)
        ax.set_xlabel('day')
        ax.set_ylabel('price')
        ax.autoscale_view()
        ax.patch.set_facecolor('k')  # 背景色
        ax.patch.set_alpha(0.6)  # 透明度

        finance.candlestick2_ochl(ax, opens=self.ohcl["open"],\
                                      highs=self.ohcl["high"],\
                                      lows=self.ohcl["low"],\
                                      closes=self.ohcl["close"],\
                                      width=0.5, colorup='r',\
                                      colordown='g', alpha=0.75)

        # 一目均衡雲をプロットする
        self.__calc_leading_span()
        x_data = [x for x in range(26, 26 + len(self._span1))]
        plt.plot(x_data, self._span1, color="r", alpha=0.5)
        plt.plot(x_data, self._span2, color="b", alpha=0.5)
        plt.fill_between(x_data,
                         self._span1,
                         self._span2,
                         where=self._span1 > self._span2,
                         facecolor='r',
                         alpha=0.25)
        plt.fill_between(x_data,
                         self._span1,
                         self._span2,
                         where=self._span1 < self._span2,
                         facecolor='b',
                         alpha=0.25)

        self.__plt_bolinger_band(ax)
        self.__plt_envelope(ax)
        self.__plt_upper_support_line(ax)
        self.__plt_GMMA(ax)
        self.__plt_volume(ax)

        plt.xlim([100, 120])
        plt.grid(True, linestyle='--', color='0.75')

        # 画像を保存する
        if savefig == True:
            fig_name = str(self.code) + ".png"
            plt.savefig(fig_name)

        plt.show()
Exemplo n.º 14
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()
 def candleStick():
     dff = callback()
     dff = dff[-int(mEntry2.get()) - 90:-int(mEntry2.get())]
     fig, ax = plt.subplots()
     mpf.candlestick2_ochl(ax,
                           opens=dff['Open'],
                           closes=dff['Close'],
                           highs=dff['High'],
                           lows=dff['Low'],
                           width=2,
                           colorup='g',
                           colordown='r',
                           alpha=0.75)
     ax.set_ylabel('Price per Share ($)')
     ax.set_xlabel('Days Before Prediction ')
     plt.show()
Exemplo n.º 16
0
def plot_chart_data(data, currency_pair, file_name=None, ymin=None, ymax=None):
    fig1, ax1 = plt.subplots()
    candlestick2_ochl(ax1,
                      opens=[float(d["open"]) for d in data],
                      closes=[float(d["close"]) for d in data],
                      highs=[float(d["high"]) for d in data],
                      lows=[float(d["low"]) for d in data],
                      width=0.5,
                      colorup='green')

    change = helper.calculate_difference_in_percent(float(data[0]['open']), float(data[-1]['close']))

    plt.title("{0} {1:.2f}%".format(currency_pair, change))

    if ymin and ymax:
        plt.ylim(ymin=ymin, ymax=ymax)

    plt.tight_layout()
    if file_name:
        plt.savefig(file_name)
        plt.close()
    else:
        plt.show()
Exemplo n.º 17
0
def plot_chart_data(data, currency_pair, file_name=None, ymin=None, ymax=None):
    fig1, ax1 = plt.subplots()
    candlestick2_ochl(ax1,
                      opens=[float(d["open"]) for d in data],
                      closes=[float(d["close"]) for d in data],
                      highs=[float(d["high"]) for d in data],
                      lows=[float(d["low"]) for d in data],
                      width=0.5,
                      colorup='green')

    change = helper.calculate_difference_in_percent(float(data[0]['open']),
                                                    float(data[-1]['close']))

    plt.title("{0} {1:.2f}%".format(currency_pair, change))

    if ymin and ymax:
        plt.ylim(ymin=ymin, ymax=ymax)

    plt.tight_layout()
    if file_name:
        plt.savefig(file_name)
        plt.close()
    else:
        plt.show()
Exemplo n.º 18
0
from matplotlib.finance import candlestick2_ochl

import atj.candlestick

vsamplet = np.asarray([1., 2., 3., 4., 5., 6.])
lookback = 2
vt = np.asarray([1., 2., 3., 4., 5.])
vpx = np.asarray([108., 102., 103., 101., 105.])
vsz = np.asarray([10., 15., 5., 25., 20.])
res = atj.candlestick.candlestick_trades(vsamplet, lookback, vt, vpx, vsz)
res = np.reshape(res, (-1, 6))

fig, ax = plt.subplots()
#fig.subplots_adjust(bottom=0.2)
#ax.xaxis.set_major_locator(mondays)
#ax.xaxis.set_minor_locator(alldays)
#ax.xaxis.set_major_formatter(weekFormatter)
##ax.xaxis.set_minor_formatter(dayFormatter)

np.save
candlestick2_ochl(ax, res[:, 1], res[:, 2], res[:, 3], res[:, 4], width=0.2, colorup=u'k', colordown=u'r', alpha=1.0)

##plot_day_summary(ax, quotes, ticksize=3)

ax.xaxis_date()
ax.autoscale_view()
plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')

plt.show()

    #fp = FontProperties(fname=r'D:\Dev\stockdb\ipagp.ttf')
    fp = FontProperties(fname=fontpath)

    fig = plt.figure()
    fig.subplots_adjust(bottom=0.15)
    fig.subplots_adjust(hspace=0)

    fig.suptitle(stockname, fontproperties=fp, fontsize=24, fontweight='bold')

    gs = gridspec.GridSpec(2, 1, height_ratios=[4, 1])
    ax0 = plt.subplot(gs[0])

    candles = candlestick2_ochl(ax0,
                                opens,
                                closes,
                                highs,
                                lows,
                                width=1,
                                colorup='blue',
                                colordown='r')
    textsize = 8  # size for axes text

    left, height, top = 0.025, 0.06, 0.9
    t1 = ax0.text(left,
                  top,
                  '%s daily' % symbol,
                  fontsize=textsize,
                  transform=ax0.transAxes)
    t2 = ax0.text(left,
                  top - height,
                  'EMA(5)',
                  color='b',
Exemplo n.º 20
0
def moving_average_convergence(x, nslow=26, nfast=12):
    """
    compute the MACD (Moving Average Convergence/Divergence) using a fast and slow exponential moving avg'
    return value is emaslow, emafast, macd which are len(x) arrays
    """
    emaslow = moving_average(x, nslow, type='exponential')
    emafast = moving_average(x, nfast, type='exponential')
    return emaslow, emafast, emafast - emaslow

start = datetime.datetime(2010, 1, 1)
end = datetime.datetime(2013, 1, 27)
f = web.DataReader("F", 'yahoo', start, end)
f['12_exma'] = pandas.ewma(f['Adj Close'], span=12, min_periods=12)
f['26_exma'] = pandas.ewma(f['Adj Close'], span=26, min_periods=26)
f['MACD'] = f['12_exma']  - f['26_exma']
f['singal'] = pandas.ewma(f['MACD'], span=9, min_periods=9)
f['histogram'] = f['MACD'] - f['singal']
#print f.ix['2010-01-04']
#print f[:100]
print f[:10]

f['t'] = f.index.map(dates.date2num)
fig, ax = plt.subplots()
#candlestick(ax, f[['t', 'Open', 'High', 'Low', 'Close']].values)
candlestick2_ochl(f['t'], f['Open'], f['Close'], f['High'], f['Low'])
ax.xaxis_date()
#f.plot()
plt.show()

Exemplo n.º 21
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
Exemplo n.º 22
0
#Visualize
plt.figure()

closes = data['Close'].values[start:stop]
opens = data['Open'].values[start:stop]
highs = data['High'].values[start:stop]
lows = data['Low'].values[start:stop]

ax = plt.subplot(311)

plt.grid(True)
fnc.candlestick2_ochl(ax,
                      opens,
                      closes,
                      highs,
                      lows,
                      width=1,
                      colorup='g',
                      colordown='r',
                      alpha=0.75)

plt.subplot(312)
plt.plot(df['RSI'].values[start:stop])
plt.plot(30 * np.ones(stop - start), 'r--')
plt.plot(70 * np.ones(stop - start), 'r--')
plt.plot(df['RSI_MA1'].values[start:stop])
plt.plot(df['RSI_MA2'].values[start:stop])
plt.grid(True)

plt.subplot(313)
plt.plot(df['MACD'].values[start:stop])
 highs = np.array(highs) - vert_shift
 lows = np.array(lows) - vert_shift
 
 from matplotlib.finance import candlestick2_ochl
 
 
 
 tag_to_dist = {"T" : 19.95045714285714,"M" : 13.535514285714285,"B" : -22.043857142857142,"OH1" : 15.330485714285714,"OH2" : 1.617575,"OH3" : -2.5823,"OH4" : -8.916849999999998,"HP1" : 17.293228571428568,"HP2" : 3.939978571428571,"HP3" : -4.974257142857143,"HP4" : -12.003725,"CC" : -1.9202571428571429}
 
 
 
 ## Code for the absolute
 if(True):
 
  
   candlestick2_ochl(ax1,opens,closes,highs,lows,width= 1, colorup='#77d879', colordown='#db3f3f')
   plt.xlabel('Z-coordinate [Angstrom]', fontsize = 24, color = fc)
   plt.xticks([i for i in range(len(lines[0]))][::10],lines[0][::10], fontsize = 22)
   plt.yticks(fontsize=22)
   plt.ylabel('Smoothed Channel Radius [Angstrom]',fontsize = 24, color = fc)
   
   titletag = tag.replace("min_","Minimal").replace("6AA_","Residues within 6 $\AA$").replace("4AA_","Residues within 4 $\AA$").replace("5AA_","Residues within 5 $\AA$").replace("fc"," Forward (Correction)").replace("bc", " Backward (Correction)").replace("f"," Forward").replace("b"," Backward").replace("12"," Sites AB and DE").replace("1"," Site AB").replace("2"," Site DE")
   #plt.title(titletag, fontsize = 24, color = fc)
   plt.subplots_adjust(left=0.09, bottom=0.20, right=0.94, top=0.90, wspace=0.2, hspace=0)
  
    
   if(tag=="min_f12"):
     for i,j in zip(tag_to_dist.keys(),tag_to_dist.values()):
       plt.plot([j+40, j+40], [-29.5, 7.3], 'k--', lw=1, color =fc)
       shif = 0.0
       if(i=="CC"): shif = 0.4
Exemplo n.º 24
0
begin_time = '2017-05-17'
end_time = '2018-05-17'
code = '002129'
df = ts.get_hist_data(code, start=begin_time, end=end_time)
df = df.sort_index(0)
df_idx = df.index.values

fig, ax = plt.subplots(figsize=(20, 10))

# matplotlib.finance.candlestick2_ochl(ax, opens, closes, highs, lows, width=4, colorup='r', colordown='g', alpha=0.75)
candlestick2_ochl(ax=ax,
                  opens=df["open"].values,
                  closes=df["close"].values,
                  highs=df["high"].values,
                  lows=df["low"].values,
                  width=0.75,
                  colorup='r',
                  colordown='g',
                  alpha=0.75)
ax.xaxis.set_major_locator(ticker.MaxNLocator(20))


#设置自动格式化时间
def mydate_formatter(x, pos):
    try:
        return df_idx[int(x)]
    except IndexError:
        return ''

Exemplo n.º 25
0
    #     sma_5 = pd.ewma(np.array(data['close']), 5)
    #     sma_10 = pd.ewma(np.array(data['close']), 10)
    #     sma_20 = pd.ewma(np.array(data['close']), 20)
    #     sma_30 = pd.ewma(np.array(data['close']), 30)
    #     sma_60 = pd.ewma(np.array(data['close']), 60)

    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.set_xticks(range(0, len(data['date']), 10))

    ax.set_xticklabels(data['date'][::10], rotation=45)
    ax.plot(sma_5, label='MA5')
    ax.plot(sma_10, label='MA10')
    ax.plot(sma_20, label='MA20')
    ax.plot(sma_30, label='MA30')
    ax.plot(sma_60, label='MA60')
    ax.legend(loc='upper left')

    mpf.candlestick2_ochl(ax,
                          data['open'],
                          data['close'],
                          data['high'],
                          data['low'],
                          width=0.5,
                          colorup='r',
                          colordown='green',
                          alpha=0.6)
    plt.grid()
    plt.show()
Exemplo n.º 26
0
from matplotlib.finance import candlestick2_ochl
import matplotlib.dates as mdates

##style.use('ggplot')

##Reading csv file and storing as dataframe in df
df = pd.read_csv('TCS.csv')

df_ohlc = df

##Mapping dates of csv file to matplotlib dates  format
df_ohlc['Date'] = df_ohlc['Date'].map(mdates.datestr2num)
##df_volume['Date']=df_volume['Date'].map(mdates.datestr2num)

ax1 = plt.subplot2grid((6, 1), (0, 0), rowspan=5, colspan=1)

##ax2=plt.subplot2grid((6,1),(5,0),rowspan=1,colspan=1,sharex=ax1)

ax1.set_title('TCS')
candlestick2_ochl(ax1,
                  df_ohlc['Open'],
                  df_ohlc['Close'],
                  df_ohlc['High'],
                  df_ohlc['Low'],
                  width=2,
                  colorup='g')

##ax2.fill_between(df_volume['Date'],df_volume['Total Traded Quantity'].mean(),0)
##ax1.scatter(df_ohlc['Date'],df_ohlc['Total Traded Quantity'])
plt.show()
Exemplo n.º 27
0
    fig.set_size_inches(18.5, 10.5)
    ax1 = plt.subplot2grid((1, 1), (0, 0))
    ax1.set_facecolor(bc)

    ax1.spines['bottom'].set_color(fc)
    ax1.spines['top'].set_color(fc)
    ax1.spines['right'].set_color(fc)
    ax1.spines['left'].set_color(fc)

    ax1.tick_params(axis='x', colors=fc)
    ax1.tick_params(axis='y', colors=fc)

    candlestick2_ochl(ax1,
                      opens,
                      closes,
                      highs,
                      lows,
                      width=1,
                      colorup='#77d879',
                      colordown='#db3f3f')
    plt.xlabel('Z-coordinate [Angstrom]', fontsize=24, color=fc)
    plt.xticks([i for i in range(len(lines[0]))][::5],
               lines[0][::5],
               fontsize=18)
    plt.yticks(fontsize=18)
    plt.ylabel('Smoothed Channel Radius [Angstrom]', fontsize=24, color=fc)

    titletag = tag.replace("min_", "Minimal").replace(
        "6AA_", "Residues within 6 $\AA$").replace(
            "4AA_", "Residues within 4 $\AA$").replace(
                "5AA_", "Residues within 5 $\AA$").replace(
                    "fc", " Forward (Correction)").replace(
Exemplo n.º 28
0
    def get_relation(self, k_data):
        ## 判断包含关系
        after_fenxing = pd.DataFrame()
        temp_data = k_data[:1]
        zoushi = [3]  # 3-持平 4-向下 5-向上
        print(temp_data.high)
        for i in range(len(k_data)):
            case1_1 = temp_data.high.values[-1] > k_data.high.values[
                i] and temp_data.low.values[-1] < k_data.low.values[
                    i]  # 第1根包含第2根
            case1_2 = temp_data.high.values[-1] > k_data.high.values[
                i] and temp_data.low.values[-1] == k_data.low.values[
                    i]  # 第1根包含第2根
            case1_3 = temp_data.high.values[-1] == k_data.high.values[
                i] and temp_data.low.values[-1] < k_data.low.values[
                    i]  # 第1根包含第2根
            case2_1 = temp_data.high.values[-1] < k_data.high.values[
                i] and temp_data.low.values[-1] > k_data.low.values[
                    i]  # 第2根包含第1根
            case2_2 = temp_data.high.values[-1] < k_data.high.values[
                i] and temp_data.low.values[-1] == k_data.low.values[
                    i]  # 第2根包含第1根
            case2_3 = temp_data.high.values[-1] == k_data.high.values[
                i] and temp_data.low.values[-1] > k_data.low.values[
                    i]  # 第2根包含第1根
            case3 = temp_data.high.values[-1] == k_data.high.values[
                i] and temp_data.low.values[-1] == k_data.low.values[
                    i]  # 第1根等于第2根
            case4 = temp_data.high.values[-1] > k_data.high.values[
                i] and temp_data.low.values[-1] > k_data.low.values[i]  # 向下趋势
            case5 = temp_data.high.values[-1] < k_data.high.values[
                i] and temp_data.low.values[-1] < k_data.low.values[i]  # 向上趋势
            if case1_1 or case1_2 or case1_3:
                if zoushi[-1] == 4:
                    temp_data.high.values[-1] = k_data.high.values[i]
                else:
                    temp_data.low.values[-1] = k_data.low.values[i]

            elif case2_1 or case2_2 or case2_3:
                temp_temp = temp_data[-1:]
                temp_data = k_data[i:i + 1]
                if zoushi[-1] == 4:
                    temp_data.high.values[-1] = temp_temp.high.values[0]
                else:
                    temp_data.low.values[-1] = temp_temp.low.values[0]

            elif case3:
                zoushi.append(3)
                pass

            elif case4:
                zoushi.append(4)
                after_fenxing = pd.concat([after_fenxing, temp_data], axis=0)
                temp_data = k_data[i:i + 1]

            elif case5:
                zoushi.append(5)
                after_fenxing = pd.concat([after_fenxing, temp_data], axis=0)
                temp_data = k_data[i:i + 1]
                # after_fenxing.head()

        ## 因为使用candlestick2函数,要求输入open、close、high、low。为了美观,处理k线的最大最小值、开盘收盘价,之后k线不显示影线。
        for i in range(len(after_fenxing)):
            if after_fenxing.open.values[i] > after_fenxing.close.values[i]:
                after_fenxing.open.values[i] = after_fenxing.high.values[i]
                after_fenxing.close.values[i] = after_fenxing.low.values[i]
            else:
                after_fenxing.open.values[i] = after_fenxing.low.values[i]
                after_fenxing.close.values[i] = after_fenxing.high.values[i]

        ## 画出k线图
        stock_middle_num = self.middle_num(after_fenxing)
        fig, ax = plt.subplots(figsize=(50, 20))
        fig.subplots_adjust(bottom=0.2)
        mpf.candlestick2_ochl(ax,
                              list(after_fenxing.open),
                              list(after_fenxing.close),
                              list(after_fenxing.high),
                              list(after_fenxing.low),
                              width=0.6,
                              colorup='r',
                              colordown='b',
                              alpha=0.75)
        plt.grid(True)
        dates = after_fenxing.index
        ax.set_xticklabels(dates)  # Label x-axis with dates
        # ax.autoscale_view()
        ax.plot(stock_middle_num, 'k', lw=1)
        ax.plot(stock_middle_num, 'ko')
        plt.setp(plt.gca().get_xticklabels(), rotation=30)
        plt.title(self.coin_type + "_" + self.time_type +
                  time.strftime('%Y-%m-%d-%H-%M-%S') + "_ftb.png")
        self.K_Line_fig = fig
        return after_fenxing
Exemplo n.º 29
0
def dwAxStd(ax,os,hs,ls,cs):
    mpf.candlestick2_ochl(ax, os,hs,ls,cs, width=0.6, colorup='r', colordown = 'g', alpha=0.75)
    ax1.set_xlim(left = 0.0)    
Exemplo n.º 30
0
k, d = STOCH(f.High.values,
             f.Low.values,
             f.Close.values,
             fastk_period=8,
             slowk_period=3,
             slowk_matype=0,
             slowd_period=3,
             slowd_matype=0)

fig = plt.figure(figsize=(11, 8))
ax1 = fig.add_subplot(2, 1, 1)
candlestick2_ochl(ax1,
                  opens,
                  closes,
                  highs,
                  lows,
                  width=0.5,
                  colorup='r',
                  colordown='g')
ax1.set_xticks(np.linspace(0, l - 1, 6).astype('int'))
ax1.set_xticklabels(f.index[np.linspace(0, l - 1, 6).astype('int')])
ax1.grid(color='r', linestyle='--', linewidth=1)

ax2 = fig.add_subplot(2, 1, 2)
ax2.plot(k)
ax2.plot(d)
ax2.set_xticks(np.linspace(0, l - 1, 6).astype('int'))
ax2.set_yticks([15, 20, 30, 40, 50, 60, 70, 80, 85])
ax2.set_xticklabels(f.index[np.linspace(0, l - 1, 6).astype('int')])
ax2.grid(color='b', linestyle='--', linewidth=1)
plt.show()
Exemplo n.º 31
0
        #ignore the clear signal
        if df1['cumsum'][n] > 0:
            df1['signals'][n] = -1 * (df1['cumsum'][n - 1])
        elif df1['cumsum'][n] < 0:
            df1['signals'][n] = 0

#plotting the backtesting result
#first plot is Heikin-Ashi candlestick
#use candlestick function and set Heikin-Ashi O,C,H,L
#the second plot is the actual price with long/short positions as up/down arrows

ax1 = plt.subplot2grid((200, 1), (0, 0), rowspan=120, ylabel='HA price')
mpf.candlestick2_ochl(ax1,
                      df1['HA open'],
                      df1['HA close'],
                      df1['HA high'],
                      df1['HA low'],
                      width=1,
                      colorup='g',
                      colordown='r')
plt.grid(True)
plt.xticks([])
plt.title('Heikin-Ashi')

ax2 = plt.subplot2grid((200, 1), (120, 0),
                       rowspan=80,
                       ylabel='price',
                       xlabel='')
df1['Close'].plot(ax=ax2, label=ticker, c='k')
#long/short positions are attached to the real close price of the stock
#set the line width to zero
#thats why we only observe markers
    millionformatter = FuncFormatter(millions)
    thousandformatter = FuncFormatter(thousands)
    #fig = plt.figure(figsize=(8, 6))
    #fp = FontProperties(fname=r'D:\Dev\stockdb\ipagp.ttf')
    fp = FontProperties(fname=fontpath)

    fig = plt.figure()
    fig.subplots_adjust(bottom=0.15)
    fig.subplots_adjust(hspace=0)

    fig.suptitle(stockname, fontproperties=fp, fontsize=24, fontweight='bold')

    gs = gridspec.GridSpec(2, 1, height_ratios=[4, 1])
    ax0 = plt.subplot(gs[0])

    candles = candlestick2_ochl(ax0, opens, closes, highs, lows, width=1, colorup='blue',colordown='r')
    textsize = 8        # size for axes text

    left, height, top = 0.025, 0.06, 0.9
    t1 = ax0.text(left, top, '%s daily'%symbol, fontsize=textsize,
                   transform=ax0.transAxes)
    t2 = ax0.text(left, top-height, 'EMA(5)', color='b', fontsize=textsize, transform=ax0.transAxes)
    t3 = ax0.text(left, top-2*height, 'EMA(25)', color='r', fontsize=textsize, transform=ax0.transAxes)

    s = '%s O:%1.2f H:%1.2f L:%1.2f C:%1.2f, V:%1.1fM Chg:%+1.2f' %(
        time.strftime('%d-%b-%Y'),
        opens[-1], highs[-1],
        lows[-1], closes[-1],
        volumes[-1]*1e-6,
        closes[-1]-opens[-1])
    t4 = ax0.text(0.4, top, s, fontsize=textsize,
Exemplo n.º 33
0
    def draw_k_line(self, path, title):
        X = self.X
        data = {}
        data["open"] = np.array(X[:, 1], dtype=np.float)[-500:]
        data["close"] = np.array(X[:, 4], dtype=np.float)[-500:]
        data["high"] = np.array(X[:, 2], dtype=np.float)[-500:]
        data["low"] = np.array(X[:, 3], dtype=np.float)[-500:]

        self.average_axis_buy["Y"] = data["close"][self.average_axis_buy["X"]]
        self.average_axis_sell["Y"] = data["close"][
            self.average_axis_sell["X"]]

        fig, ax = plt.subplots(figsize=(50, 20))
        fig.subplots_adjust(bottom=0.2)
        plt.grid(True)
        mpf.candlestick2_ochl(ax,
                              data["open"],
                              data["close"],
                              data["high"],
                              data["low"],
                              width=0.6,
                              colorup='r',
                              colordown='green',
                              alpha=0.75)
        hhv_20 = HHV(self.ma3, 50)
        hhv_20 = hhv_20.series[-500:]

        ax.plot(self.ma90.series[-500:])
        ax.plot(self.ma3.series[-500:], color='#054E9F')
        ax.plot(hhv_20, color='#436EEE')
        axis_map, judge_trend_map = self.get_top_liner_point()

        ax.scatter(axis_map["X"], axis_map["Y"], s=75)
        ax.scatter(judge_trend_map["X"],
                   judge_trend_map["Y"],
                   s=75,
                   c='#FF00FF',
                   marker='x')
        ax.scatter(self.average_axis_buy["X"],
                   self.average_axis_buy["Y"],
                   s=75,
                   c='#FF00FF',
                   marker='D')
        ax.scatter(self.average_axis_sell["X"],
                   self.average_axis_sell["Y"] * 1.02,
                   s=300,
                   c='green',
                   marker='v')
        if len(self.zhibiao_axis_map) > 0:
            ax.scatter(self.zhibiao_axis_map["X"],
                       self.zhibiao_axis_map["Y"] * 0.98,
                       s=300,
                       c='r',
                       marker="^")

        if len(self.additional_map_list) > 0:
            for additional_map in self.additional_map_list:
                for i, txt in enumerate(additional_map["Y"]):
                    ax.annotate(
                        CommonTools.as_num(additional_map["Z"][i], 2),
                        (additional_map["X"][i], additional_map["Y"][i]))

        plt.setp(plt.gca().get_xticklabels(), rotation=30)
        plt.title(title)
        fig.savefig(path)
        self.X = None
Exemplo n.º 34
0
df5 = web.DataReader('VZ', "yahoo", start,
                     end)  #VERIZON stock values, from yahoo, between times
print(df5.head())
df5.to_csv('stocks/VZ.csv')

df6 = web.DataReader('GOOG', "yahoo", start,
                     end)  #GOOGLE stock values, from yahoo, between times
print(df6.head())
df6.to_csv('stocks/GOOG.csv')

dfGold = web.DataReader('GLD', "yahoo", start,
                        end)  #google stock values, from yahoo, between times
print(dfGold.head())
dfGold.to_csv('stocks/GOLD.csv')

df = pd.read_csv('GOOG.csv', parse_dates=True, index_col=0)
fig, ax = plt.subplots()
mpf.candlestick2_ochl(ax,
                      opens=df['Open'],
                      closes=df['Close'],
                      highs=df['High'],
                      lows=df['Low'],
                      width=2,
                      colorup='g',
                      colordown='r',
                      alpha=0.75)

df['Adj Close'].plot()
plt.show()
Exemplo n.º 35
0
    # 1.3 K线图绘制
    __colorup__ = 'red'
    __colordown__ = 'green'
    tsla_part_df = tsla_df[-30:]
    fig, ax = plt.subplots()
    # 用来存放等待绘制的数据
    qutotes = []
    # for index,(d,o,c,h,l) in enumerate(zip(tsla_part_df.index,tsla_part_df.open,tsla_part_df.close,tsla_part_df.high,tsla_part_df.low)):
    #     # 把日期数据从日期格式转换为数字格式
    #     d=mpf.date2num(d)
    #     # 存储数据
    #     val=(d,o,c,h,l)
    #     qutotes.append(val)
    #利用mpf进行绘图
    mpf.candlestick2_ochl(ax,
                          tsla_part_df.open,
                          tsla_part_df.close,
                          tsla_part_df.high,
                          tsla_part_df.low,
                          width=0.6,
                          colorup=__colorup__,
                          colordown=__colordown__)
    ax.autoscale_view()
    # 使用这个方法将x轴的数据改成时间已经不行了
    # ax.xaxis_date(tsla_part_df.index.values.tolist())
    # 需要这样来进行处理
    ax.set_xticks(range(0, len(tsla_part_df['date']), 5))
    ax.set_xticklabels(tsla_part_df['date'][::5])
    plt.show()
    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)
Exemplo n.º 37
0
def gen_plot(dataframe,startidx,endidx):
	#dataframe is a pandas dataframe with open, high, low, close and volume for each time interval
	
	open=dataframe['Open'][startidx:endidx].tolist()
	high=dataframe['High'][startidx:endidx].tolist()
	low=dataframe['Low'][startidx:endidx].tolist()
	close=dataframe['Close'][startidx:endidx].tolist()
	volume=dataframe['Volume'][startidx:endidx].tolist()
	
	date=dataframe['Date'][startidx:endidx].tolist()
	num_ticks=6

	def mydate(x,pos):
		try:
			return date[int(x)]
		except IndexError:
			return ''
	
	#####
	# plot just price
	#####
	'''
	fig = plt.figure()
	ax = plt.subplot()
	candlestick2_ochl(ax,open,low,high,close,width=0.5,colorup='b',colordown='r',alpha=0.75)
	ax.xaxis.set_major_locator(ticker.MaxNLocator(num_ticks))
	ax.xaxis.set_major_formatter(ticker.FuncFormatter(mydate))
	fig.autofmt_xdate()
	fig.tight_layout()
	ax.set_ylabel('Price')
	ax.set_xlabel('Date')
	ax.set_xlim(-1.0,len(date)-1.0)
	ax.xaxis.set_major_locator(ticker.MaxNLocator(num_ticks))
	ax.xaxis.set_major_formatter(ticker.FuncFormatter(mydate))
	ax.grid()
	plt.show()
	'''
	
	#####
	# plot price with volume by price
	#####
	fig = plt.figure()
	
	ax4 = plt.subplot()
	candlestick2_ochl(ax4,open,low,high,close,width=0.5,colorup='b',colordown='r',alpha=0.75)
	ax4.xaxis.set_major_locator(ticker.MaxNLocator(num_ticks))
	ax4.xaxis.set_major_formatter(ticker.FuncFormatter(mydate))
	fig.autofmt_xdate()
	fig.tight_layout()
	ax4.set_ylabel('Price')
	ax4.set_xlabel('Date')
	ax4.set_xlim(-1.0,len(date)-1.0)
	ax4.grid()
	# plt.show()
	
	#plot horizontal bar chart with volume
	#generate volume by price, using value at close
	min_price=min(close)
	max_price=max(close)
	
	
	###############
	###############
	#set the nbins for qty of volume bars
	nbins=75
	barheight=5
	num_ticks_vol=5
	###############
	###############
	
	
	dy=(max_price-min_price)/nbins
	ys = np.arange(min_price,max_price+dy,dy).round(decimals=2)
	pairs=[]
	bins=[0 for x in range(len(ys))]
	for i in range(len(close)):
		for z in range(len(ys)-1):
			if ys[z] <= close[i] < ys[z+1]:
				bins[z]=bins[z]+volume[i]
				
				
	def setbins(x,pos):
		try:
			return ys[int(x)]
		except IndexError:
			return ''
	
	ax3 = ax4.twinx()
	ax3 = ax4.twiny()
	# ax3.yaxis.set_major_formatter(ticker.FuncFormatter(setbins))
	ax3.barh(ys,bins,align='center',height=barheight,color='gray',alpha=0.5)
	# ax3.set_yticks(ys)
	# ax3.yaxis.set_major_locator(ticker.MaxNLocator(num_ticks_vol))
	ax3.yaxis.set_visible(False)
	ax3.xaxis.set_visible(False)
	# ax3.set_yticklabels(ys)
	# ax3.grid()
	plt.show()
	
	
	#####
	# plot price with volume in second view below
	#####
	'''