예제 #1
0
def Kline_plot(raw_data):
    #raw_data = ts.get_hist_data('hs300', start='2015-07-01')
    #raw_data.index = raw_data.index.map(str2date)
    raw_data['time'] = raw_data.index
    data = DataFrame(raw_data, columns=['time', 'open','close','high','low'])
    alldays = DayLocator()
    months = MonthLocator()
    weekdays = WeekdayLocator()
    month_formater = DateFormatter("%b %Y")
    week_formater = DateFormatter("%m %d")

    ymajorLocator   = MultipleLocator(100) #将y轴主刻度标签设置为0.5的倍数 
    ymajorFormatter = FormatStrFormatter('%1.1f') #设置y轴标签文本的格式 
    yminorLocator   = MultipleLocator(10) #将此y轴次刻度标签设置为0.1的倍数 

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.xaxis.set_major_locator(weekdays)
    ax.xaxis.set_minor_locator(alldays)
    ax.xaxis.set_major_formatter(week_formater)

    ax.yaxis.set_major_locator(ymajorLocator)  
    ax.yaxis.set_major_formatter(ymajorFormatter)
    data = np.array(data)
    candlestick_ochl(ax,data,width=0.6,colordown=u'g',colorup=u'r')
    ax.xaxis_date()
    ax.autoscale_view()
    fig.autofmt_xdate()
    plt.show()
예제 #2
0
    def candlestick_chart(self, time_series, interval=40, show=False, filename='candlestick.png', volume_overlay=None):
        tz = get_localzone()
        adjusted_time_series = []
        for item in time_series:
            item[0] = epoch2num(item[0])
            adjusted_time_series.append(item)
        fig, ax = plt.subplots()
        fig.subplots_adjust(bottom=0.2)

        ax.xaxis.set_major_formatter(self._date_formatter(interval, tz=tz))
        days_interval = interval / 86400.0
        candlestick_ochl(ax, adjusted_time_series, width=(days_interval), colorup='green', colordown='red', alpha=0.9)

        ax.xaxis_date(tz=tz.zone)
        ax.autoscale_view()
        yticks = ax.get_yticks()
        x_start = min(yticks) - ((max(yticks) - min(yticks)) * 0.60)
        plt.ylim([x_start,max(yticks)])
        ax.grid(True)
        plt.setp( plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
        if volume_overlay != None:
            # Add a seconds axis for the volume overlay
            ax2 = ax.twinx()

            yticks = ax.get_yticks()
            print('yticks', yticks)
            # set the position of ax2 so that it is short (y2=0.32) but otherwise the same size as ax
            ax2.set_position(matplotlib.transforms.Bbox([[0.125,0.2],[0.9,0.42]]))
            #print(days_interval * len(adjusted_time_series))
            #ax2.set_position([0.125, 0.2, 0.8, 0.2])

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

            ax2.bar(dates,volume,color='#aaaaaa',width=(days_interval),align='center',linewidth=0.0,alpha=0.8)

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

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

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

        if show:
            plt.show()
        else:
            plt.savefig(const.DATA_DIR + '/' + filename, bbox_inches='tight')
            plt.close()
예제 #3
0
def sample_513():
    """
    5.1.3 k线图的绘制
    :return:
    """
    import matplotlib.finance as mpf

    __colorup__ = "red"
    __colordown__ = "green"
    # 为了示例清晰,只拿出前30天的交易数据绘制蜡烛图,
    tsla_part_df = tsla_df[:30]
    fig, ax = plt.subplots(figsize=(14, 7))
    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)):
        # 蜡烛图的日期要使用matplotlib.finance.date2num进行转换为特有的数字值
        d = mpf.date2num(d)
        # 日期,开盘,收盘,最高,最低组成tuple对象val
        val = (d, o, c, h, l)
        # 加val加入qutotes
        qutotes.append(val)
    # 使用mpf.candlestick_ochl进行蜡烛绘制,ochl代表:open,close,high,low
    mpf.candlestick_ochl(ax,
                         qutotes,
                         width=0.6,
                         colorup=__colorup__,
                         colordown=__colordown__)
    ax.autoscale_view()
    ax.xaxis_date()
    plt.show()
예제 #4
0
def weekday_candlestick(ohlc_data, ax, fmt='%b %d', freq=7, **kwargs):
    """ Wrapper function for matplotlib.finance.candlestick_ohlc
        that artificially spaces data to avoid gaps from weekends """

    # Convert data to numpy array
    ohlc_data_arr = np.array(ohlc_data)
    ohlc_data_arr2 = np.hstack([
        np.arange(ohlc_data_arr[:, 0].size)[:, np.newaxis], ohlc_data_arr[:,
                                                                          1:]
    ])
    ndays = ohlc_data_arr2[:, 0]  # array([0, 1, 2, ... n-2, n-1, n])

    # Convert matplotlib date numbers to strings based on `fmt`
    dates = mdates.num2date(ohlc_data_arr[:, 0])
    date_strings = []
    for date in dates:
        date_strings.append(date.strftime(fmt))

    # Plot candlestick chart
    candlestick_ochl(ax, ohlc_data_arr2, **kwargs)

    # Format x axis
    ax.set_xticks(ndays[::freq])
    ax.set_xticklabels(date_strings[::freq], rotation=45, ha='right')
    ax.set_xlim(ndays.min(), ndays.max())

    plt.show()
예제 #5
0
파일: bi_001.py 프로젝트: Takoony/20170620
def plot_k_line(data):
    """
    data为dataframe格式,第一列为时间,第二到5列为ochl
    """
    import numpy as np
    import pandas as pd

    import datetime as dt
    import talib
    from matplotlib.pylab import date2num
    import matplotlib.pyplot as plt
    import matplotlib.finance as mpf

    def date_to_num(dates):
        num_time = []
        for date in dates:
            date_time = dt.datetime.strptime(date, '%Y-%m-%d')
            num_date = date2num(date_time)
            num_time.append(num_date)
        return num_time

    data['date'] = date_to_num(data['date'])
    data = data.values
    #成交量
    fig, (ax1, ax2) = plt.subplots(2, sharex=True, figsize=(15, 5))
    mpf.candlestick_ochl(ax1, data, width=1.0, colorup='g', colordown='r')
    ax1.set_title('nyang')
    ax1.set_ylabel('Price')
    ax1.grid(True)
    ax1.xaxis_date()
    plt.bar(data[:, 0] - 0.25, data[:, 5], width=0.5)
    ax2.set_ylabel('Volume')
    ax2.grid(True)
    plt.show()
예제 #6
0
파일: c5.py 프로젝트: 3774257/abu
def sample_513():
    """
    5.1.3 k线图的绘制
    :return:
    """
    import matplotlib.finance as mpf

    __colorup__ = "red"
    __colordown__ = "green"
    # 为了示例清晰,只拿出前30天的交易数据绘制蜡烛图,
    tsla_part_df = tsla_df[:30]
    fig, ax = plt.subplots(figsize=(14, 7))
    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)):
        # 蜡烛图的日期要使用matplotlib.finance.date2num进行转换为特有的数字值
        d = mpf.date2num(d)
        # 日期,开盘,收盘,最高,最低组成tuple对象val
        val = (d, o, c, h, l)
        # 加val加入qutotes
        qutotes.append(val)
    # 使用mpf.candlestick_ochl进行蜡烛绘制,ochl代表:open,close,high,low
    mpf.candlestick_ochl(ax, qutotes, width=0.6, colorup=__colorup__,
                         colordown=__colordown__)
    ax.autoscale_view()
    ax.xaxis_date()
    plt.show()
예제 #7
0
def Kline_plot(raw_data):
    #raw_data = ts.get_hist_data('hs300', start='2015-07-01')
    #raw_data.index = raw_data.index.map(str2date)
    raw_data['time'] = raw_data.index
    data = DataFrame(raw_data,
                     columns=['time', 'open', 'close', 'high', 'low'])
    alldays = DayLocator()
    months = MonthLocator()
    weekdays = WeekdayLocator()
    month_formater = DateFormatter("%b %Y")
    week_formater = DateFormatter("%m %d")

    ymajorLocator = MultipleLocator(100)  #将y轴主刻度标签设置为0.5的倍数
    ymajorFormatter = FormatStrFormatter('%1.1f')  #设置y轴标签文本的格式
    yminorLocator = MultipleLocator(10)  #将此y轴次刻度标签设置为0.1的倍数

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.xaxis.set_major_locator(weekdays)
    ax.xaxis.set_minor_locator(alldays)
    ax.xaxis.set_major_formatter(week_formater)

    ax.yaxis.set_major_locator(ymajorLocator)
    ax.yaxis.set_major_formatter(ymajorFormatter)
    data = np.array(data)
    candlestick_ochl(ax, data, width=0.6, colordown=u'g', colorup=u'r')
    ax.xaxis_date()
    ax.autoscale_view()
    fig.autofmt_xdate()
    plt.show()
예제 #8
0
def plotcandle(dateochl):
    larray = np.asarray(dateochl)

    fig = plt.figure()
    ax1 = plt.subplot2grid((1, 1), (0, 0))
    fnplot.candlestick_ochl(ax1,larray.tolist())
    plt.show()
def plt_chart_move_avrg(chart, path=os.path.join(os.getcwd(), "tmp")):
    df_tmp_full = chart.sort_values(by=["date"], ascending=True)
    df_tmp = df_tmp_full.ix[:, [
        'open_price', 'close_price', 'high_price', 'low_price'
    ]]
    move_avrg_lst = [5, 10, 20, 40, 80]

    fig = plt.figure()
    ax = plt.subplot()

    xdate = [x for x in df_tmp_full.date]  # 日付
    ochl = np.vstack((date2num(xdate), df_tmp.values.T)).T
    mpf.candlestick_ochl(ax, ochl, width=0.7, colorup='g', colordown='r')
    ax.grid()  # グリッド表示
    ax.set_xlim(df_tmp_full.iloc[0].date, df_tmp_full.iloc[-1].date)  # x軸の範囲
    fig.autofmt_xdate()  # x軸のオートフォーマット

    for day in move_avrg_lst:
        tmp_chart = chart.loc[:,
                              ["date", "move_avrg_" + str(day)]].sort_values(
                                  by=["date"], ascending=True).copy()
        print(tmp_chart)
        ax.grid()  # グリッド表示
        ax.set_xlim(tmp_chart["date"].values[0],
                    tmp_chart["date"].values[-1])  # x軸の範囲
        fig.autofmt_xdate()  # x軸のオートフォーマット
        plt.plot(tmp_chart["date"],
                 tmp_chart["move_avrg_" + str(day)],
                 label="day-" + str(day))
    plt.legend()

    plt.savefig(os.path.join(path, chart["stock_id"].values[0] +
                             '_chart.png'))  #画像保存
예제 #10
0
def getcandlecharts(codes):
    chinese = mpl.font_manager.FontProperties(
        fname='C:\Windows\Fonts\simhei.ttf')
    plt.figure(figsize=(10, 8), facecolor='w')
    index = 1
    for code in codes:
        print(code)
        shyh = ts.get_k_data(code)
        mat_shyh = shyh.as_matrix()
        num_time = date_to_num(mat_shyh[:, 0])
        mat_shyh[:, 0] = num_time
        ax = plt.subplot(4, 4, index)
        mpf.candlestick_ochl(ax,
                             mat_shyh,
                             width=0.6,
                             colorup="r",
                             colordown="g",
                             alpha=1.0)
        plt.grid(True)
        plt.xticks(rotation=30)
        plt.title('%s: %.2f' % (getstockinfo(code), codes[code]),
                  fontproperties=chinese)
        plt.xlabel("Date")
        plt.ylabel("Price")
        ax.xaxis_date()
        index = index + 1
        if index == 16:
            break
    plt.suptitle('2015-10-01之后上市总市值超过400亿人民币的股票', fontproperties=chinese)
    plt.tight_layout(1.5)
    plt.subplots_adjust(top=0.92)
    plt.show()
예제 #11
0
def getcandlechart(code):
    # date = time.strftime('%Y-%m-%d',time.localtime(time.time()))
    # realmarket = ts.get_k_data(code=code, start="2018-05-02")
    # print(realmarket)
    shyh = ts.get_k_data(code)
    print(shyh)
    mat_shyh = shyh.as_matrix()
    num_time = date_to_num(mat_shyh[:, 0])
    mat_shyh[:, 0] = num_time
    # print(mat_shyh[:3])
    fig, ax = plt.subplots(figsize=(10, 5))
    fig.subplots_adjust(bottom=0.5)
    mpf.candlestick_ochl(ax,
                         mat_shyh,
                         width=0.6,
                         colorup="r",
                         colordown="g",
                         alpha=1.0)
    chinese = mpl.font_manager.FontProperties(
        fname='C:\Windows\Fonts\simhei.ttf')
    plt.grid(True)
    plt.xticks(rotation=30)
    # plt.title(getstockinfo(code))
    plt.title(getstockinfo(code), fontproperties=chinese)
    plt.xlabel("Date")
    plt.ylabel("Price")
    ax.xaxis_date()
    plt.show()
예제 #12
0
    def PlotIt(self):
        # 画图
        self.ax.cla()
        self.ax2.cla()

        finan.candlestick_ochl(self.ax, self.data, colorup=u'r', colordown=u'g',
                               alpha=0.5)
        self.ax.set_ylim(min(self.Df[:, 3]) * 0.9, max(self.Df[:, 2]) * 1.1)
        self.ax.plot(self.riqi, self.MA5)
        # 标注买入标志
        for xu, index in enumerate(self.Buyindex):
            if xu > 0:
                if index == oldindex:
                    LocPlace += self.Df[index, 3] * 0.02
                else:
                    oldindex = index
                    LocPlace = self.Df[index, 3]
            else:
                oldindex = index
                LocPlace = self.Df[index, 3]
            self.ax.text(index, LocPlace, str(self.Buy[xu]), color='b',
                         fontsize=10)
        # 标注卖出标志
        for xu, index in enumerate(self.Sellindex):
            if xu > 0:
                if index == oldindex:
                    LocPlace += 0.02 * self.Df[index, 2]
                else:
                    oldindex = index
                    LocPlace = self.Df[index, 2]
            else:
                oldindex = index
                LocPlace = self.Df[index, 2]
            self.ax.text(index, LocPlace, str(self.Sell[xu]), color='k',
                         fontsize=10)

        if len(self.Kongji) > 0:
            self.title = ",".join(self.Kongji) + u" 无历史数据,已跳过\n" \
                         + self.stocklist[self.index] + self.Leibie[0][0] + " " \
                         + self.Leibie[0][1] + " " + str(self.index)
        else:
            self.title = self.Leibie[0][0] + " " + self.Leibie[0][
                1] + " " + str(self.index)

        self.fig.suptitle(self.title)

        self.ax2.bar(self.riqi[self.pos], self.volume[self.pos], color='r',
                     width=1, align='center')
        self.ax2.bar(self.riqi[self.neg], self.volume[self.neg], color='g',
                     width=1, align='center')
        self.ax2.bar(self.riqi[self.neu], self.volume[self.neu], color='b',
                     width=1, align='center')

        self.ax2.set_ylim(0, max(self.volume) + 1)
        self.ax2.set_xlim(0, self.InfoRow + 1)
        self.fig.canvas.draw()
예제 #13
0
def drawData(ax, _data):
    """
    使用柱状图表示股市数据
    """
    candlestick_ochl(ax,
        _data[["date2num", "open_price", "close_price", "high_price", "low_price"]].values,
        colorup="r", colordown="g", width=0.5)
    ax.xaxis.set_major_locator(YearLocator())
    ax.xaxis.set_major_formatter(DateFormatter('%Y'))
    return ax
예제 #14
0
	def draw_candlestick(self, symbol):
		"""NOTE: Too much points in the timeseries may produce a blank 
		plot.
		"""
		
		data = symbol.get_ochlv()
		
		ax = plt.subplot(111)
		fin.candlestick_ochl(ax, data, width=0.5, colorup=u'g', colordown=u'r', alpha=1.0)
		ax.xaxis_date()
		ax.autoscale_view()
예제 #15
0
def plot(mat_wdyx):
    fig, (ax1, ax2) = plt.subplots(2, sharex=True, figsize=(15,8))
    mpf.candlestick_ochl(ax1, mat_wdyx, width=1.0, colorup = 'g', colordown = 'r')
    ax1.set_title('wandayuanxian')
    ax1.set_ylabel('Price')
    ax1.grid(True)
    ax1.xaxis_date()
    plt.bar(mat_wdyx[:,0]-0.25, mat_wdyx[:,5], width= 0.5)
    ax2.set_ylabel('Volume')
    ax2.grid(True)
    return fig
예제 #16
0
파일: tools.py 프로젝트: qyqbird/stock_work
def some_tt(start,end,sh):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    plt.grid()      
    sh.index = sh['date']
    sh_data = sh[start:end]
    #.loc[row_indexer,col_indexer] = value instead
    sh_data['time'] = sh_data['date'].map(date2num)
    df = DataFrame(sh_data, columns=['time', 'open','close','high','low'])
    df = np.array(df)
    candlestick_ochl(ax,df,width=0.6,colordown=u'g',colorup=u'r')
    ax.set_title('Some Test') 
    ax.xaxis_date()
    plt.show()
예제 #17
0
def some_tt(start, end, sh):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    plt.grid()
    sh.index = sh['date']
    sh_data = sh[start:end]
    #.loc[row_indexer,col_indexer] = value instead
    sh_data['time'] = sh_data['date'].map(date2num)
    df = DataFrame(sh_data, columns=['time', 'open', 'close', 'high', 'low'])
    df = np.array(df)
    candlestick_ochl(ax, df, width=0.6, colordown=u'g', colorup=u'r')
    ax.set_title('Some Test')
    ax.xaxis_date()
    plt.show()
예제 #18
0
def plot_candlestick(frame, ylabel='BTC/USD', candle_width=1.0, freq='1M'):
    """
    Plot candlestick graph.
    @param frame: bitcoin OHLC data frame to be plotted.
    @param ylabel: label on the y axis.
    @param candle_width: width of the candles in days.
    @param freq: frequency of the plotted x labels.
    """
    candlesticks = list(zip(
        date2num(frame.index._mpl_repr()),
        frame['open'],
        frame['close'],
        frame['high'],
        frame['low'],
        frame['amount']))
    # Figure
    ax0 = plt.subplot2grid((3,1), (0,0), rowspan=2)
    ax1 = plt.subplot2grid((3,1), (2,0), rowspan=1, sharex=ax0)
    plt.subplots_adjust(bottom=0.15)
    plt.setp(ax0.get_xticklabels(), visible=False)
    ax0.grid(True)
    ax0.set_ylabel(ylabel, size=20)
    # Candlestick
    candlestick_ochl(ax0, candlesticks, 
        width=0.5*candle_width, 
        colorup='g', colordown='r')
    # Get data from candlesticks for a bar plot
    dates = np.asarray([x[0] for x in candlesticks])
    volume = np.asarray([x[5] for x in candlesticks])
    # Make bar plots and color differently depending on up/down for the day
    pos = np.nonzero(frame['close'] - frame['open'] > 0)
    neg = np.nonzero(frame['open'] - frame['close'] > 0)
    ax1.grid(True)
    ax1.bar(dates[pos], volume[pos], color='g', width=candle_width, align='center')
    ax1.bar(dates[neg], volume[neg], color='r', width=candle_width, align='center')
    # Scale the x-axis tight
    ax1.set_xlim(min(dates),max(dates))
    ax1.set_ylabel('VOLUME', size=20)
    # Format the x-ticks with a human-readable date. 
    xt = [date2num(date) for date in pd.date_range(
            start=min(frame.index), 
            end=max(frame.index),
            freq=freq)]
    ax1.set_xticks(xt)
    xt_labels = [num2date(d).strftime('%Y-%m-%d\n%H:%M:%S') for d in xt]
    ax1.set_xticklabels(xt_labels,rotation=45, horizontalalignment='right')
    # Plot
    plt.show()
    return (ax0, ax1)
예제 #19
0
파일: draw.py 프로젝트: feng1918/qfeng
def draw_candlestick(quotes):
    """docstring for draw_candlestick"""
    COLORUP = 'red'
    COLORDOWN = 'green'
    WIDTH = 0.6

    fig, axes = plt.subplots(figsize=(18, 7))
    candlestick_ochl(axes,
                     zip(mdates.date2num(quotes.index.to_pydatetime()),
                         quotes['open'], quotes['high'], quotes['low'],
                         quotes['close']),
                     width=WIDTH,
                     colorup=COLORUP,
                     colordown=COLORDOWN)
    axes.autoscale_view()
예제 #20
0
 def add_chart(self,
               technical_indicator,
               row=1,
               plot_type='line',
               color='blue'):
     """
     This function adds a chart to the current figure.
     """
     axes = self.current_figure.add_subplot(self.figure_rows,
                                            1,
                                            row,
                                            sharex=self.figure_first_ax)
     if self.figure_first_ax is None:
         self.figure_first_ax = axes
     try:
         # Only works with ScalarFormatter
         axes.ticklabel_format(style='plain')
     except AttributeError:
         # Ignore on error
         pass
     if isinstance(technical_indicator, symbol_list.Symbol):  # Candlesticks
         axes.set_title(str(technical_indicator))
         axes.set_ylabel('Price')
         cols = [
             'DATE', technical_indicator.open, technical_indicator.close,
             technical_indicator.high, technical_indicator.low
         ]
         candlestick_ochl(axes, self.data_frame[cols].values, colorup=u'g')
         self.add_actions(technical_indicator, axes)
     else:
         if not isinstance(technical_indicator, str):
             # Probably forgot to submit the TI value
             technical_indicator = technical_indicator.value
         values = self.data_frame[str(technical_indicator)]
         axes.set_title(technical_indicator)
         axes.set_ylabel('Value')
         if plot_type == 'line':
             line, = axes.plot(self.data_frame['DATE'], values, color=color)
             self.legend.append(line)
         else:
             bars = axes.bar(self.data_frame['DATE'],
                             values,
                             color=color,
                             width=0.3)
             self.legend.append(bars)
         self.legend_labels.append(technical_indicator)
     axes.xaxis_date()
     axes.autoscale_view()
예제 #21
0
 def draw_k_v(self):
     fig, (ax1, ax2) = plt.subplots(2, sharex=True, figsize=(15, 8))
     mpf.candlestick_ochl(ax1,
                          self.mat_data,
                          width=0.5,
                          colorup='r',
                          colordown='k')
     ax1.set_title(self.name + ':' + self.code)
     ax1.set_ylabel('Price')
     ax1.grid(True)
     ax1.xaxis_date()
     plt.bar(self.mat_data[:, 0], self.mat_data[:, 5],
             width=0.5)  # ? mat_data[:,0] - 0.25
     ax2.set_ylabel('Volume')
     ax2.grid(True)
     plt.show()
예제 #22
0
def drawData(ohlcv, macd, trade_loop_back, pdays):
    dif = macd['dif']
    dea = macd['dea']
    bar = macd['bar']
    fig, axs = plt.subplots(nrows=3,
                            ncols=1,
                            facecolor=(0.5, 0.5, 0.5),
                            figsize=(14, 7))
    draw1, draw2, draw3 = axs.ravel()
    # 可视化profit_array
    draw1.plot(np.array(trade_loop_back.profit_array).cumsum(),
               label='profit_array')
    #    #print(trade_loop_back.days_array)
    #
    #可视化K线和交易日
    qutotes = []
    for index, (d, o, c, h, l) in enumerate(
            zip(ohlcv.index, ohlcv.open, ohlcv.close, ohlcv.highest,
                ohlcv.lowest)):
        d = mpf.date2num(d)
        val = (d, o, c, h, l)
        qutotes.append(val)
    mpf.candlestick_ochl(draw2,
                         qutotes,
                         width=0.4,
                         colorup="green",
                         colordown="red")
    #draw2.autoscale_view()
    #draw2.xaxis_date()
    act = pdays[(pdays.stock - pdays.shift(1).stock) != 0]
    #    draw2.axvline(np.array([736875, 736876]), label = 'buy', color="green")
    #    for index, line in act[act.stock == 1].date:
    #        draw2.axvline(qutotes[index][0], label = 'buy', color="green")
    #    for index, line in act[act.stock == 0].date:
    #        draw2.axvline(qutotes[index][0], label = 'sell', color="red")
    #    draw2.axvline(np.float32(act[act.stock == 1].date), label = 'buy', color="green")
    #    draw2.axvline(np.float32(act[act.stock == 0].date), label = 'sell', color="red")

    draw3.plot(ohlcv.index, dif, label='macd dif')
    draw3.plot(ohlcv.index, dea, label='signal dea')
    bar_red = np.where(bar > 0, bar, 0)
    bar_green = np.where(bar < 0, bar, 0)
    draw3.bar(ohlcv.index, bar_red, facecolor='red', label='hist bar')
    draw3.bar(ohlcv.index, bar_green, facecolor='green', label='hist bar')
    draw3.legend(loc='best')
    plt.show()
예제 #23
0
def kline_imgs(input_df, stock_dir, image_save=False):
    price_df = input_df.loc[:, ['date', 'open', 'close', 'high', 'low']]
    date_se = input_df.loc[:, 'date'][19:]
    num_imgs = price_df.shape[0] - 20 + 1
    # TODO 相对位置
    # price_max = price_df.max()
    # price_min = price_df.min()
    plt.grid(False)
    # 用来储存imgs
    imgs_arr = np.zeros(shape=(num_imgs, 224, 224, 3))
    for num in range(num_imgs):
        begin_idx = num
        end_idx = num + 19
        date = str(date_se[end_idx])[:10]
        year = date[:4]
        img_path = stock_dir + '/' + year + '/' + date + '.png'
        img_df = price_df.iloc[begin_idx:end_idx + 1]
        # 图像不标注日期,为了使k线连续,改为连续的数字即可(int或float都可以?)
        img_df['date'] = range(20)
        if image_save:
            # 开始作图
            fig, ax = plt.subplots()
            candlestick_ochl(ax, img_df.values, colorup='g', colordown='r')
            ax.set_xticks([])
            ax.set_yticks([])
            fig.set_size_inches(2.24 / 3, 2.24 / 3)
            ax.set_facecolor('black')
            fig.set_facecolor('black')
            plt.gca().xaxis.set_major_locator(plt.NullLocator())
            plt.gca().yaxis.set_major_locator(plt.NullLocator())
            plt.subplots_adjust(top=1,
                                bottom=0,
                                right=1,
                                left=0,
                                hspace=0,
                                wspace=0)
            plt.margins(0.1, 0.1)
            fig.savefig(img_path,
                        format='png',
                        facecolor='black',
                        dpi=300,
                        pad_inches=0)
            plt.close('all')
        imgs_arr[num] = np.array(Image.open(img_path).convert(mode='RGB'))
    # imgs_arr包含最后一天,最后一天没有label,去掉
    return imgs_arr[:-1]
예제 #24
0
 def draw_k(self):
     fig, ax = plt.subplots(figsize=(15, 5))
     fig.subplots_adjust(bottom=0.5)
     mpf.candlestick_ochl(ax,
                          self.mat_data,
                          width=0.6,
                          colorup='r',
                          colordown='k',
                          alpha=1.0)
     #candlestick_ochl : time must be in float days format - see date2num
     plt.grid(True)
     plt.xticks(rotation=30)  # 设置日期刻度旋转的角度
     plt.title(self.name + ':' + self.code)
     plt.xlabel('Date')
     plt.ylabel('Price')
     # x轴的刻度为日期
     ax.xaxis_date()
     plt.show()
예제 #25
0
def draw_k_svg(id_str,from_date_str,to_date_str):
    u"""
    Parameters:
        id_str (str): - 6位数的上证股票编号
        from_date_str (str): - '2016-6-20'形式的日期数据,表示起始日期
        to_date_str (str): - '2016-6-20'形式的日期数据,表示结束日期
    Returns:
        str : - svg的字符串内容
    """

    #设置x轴坐标刻度
    mondays = WeekdayLocator(MONDAY)            # 主要刻度
    alldays = DayLocator()                      # 次要刻度

    mondayFormatter = DateFormatter('%m-%d-%Y') # 如:2-29-2015
    dayFormatter = DateFormatter('%d')

    from_date = tuple((int(i) for i in from_date_str.strip().split("-")))
    to_date = tuple((int(i) for i in to_date_str.strip().split("-")))
    quotes_ochl = quotes_historical_yahoo_ochl(id_str+'.ss', from_date ,to_date)

    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(mondayFormatter)


    candlestick_ochl(ax, quotes_ochl, width=0.6, colorup='r', colordown='g')
    ax.xaxis_date()
    ax.autoscale_view()
    plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')

    ax.grid(True)
    plt.title(symbol_dict.get(id_str,u"未知"))

    f = BytesIO()
    plt.savefig("ts_o.svg", format="svg")
    plt.savefig(f, format="svg")
    value = f.getvalue()
    result = deal_with_svg(f)
    f.close()
    return result
예제 #26
0
def main():
    hb = ccxt.huobipro()
    hb.proxies = {
        'http': 'http://127.0.0.1:8123',
        'https': 'http://127.0.0.1:8123',
    }
    data = hb.fetch_ohlcv('BTC/USDT', '15m')
    arr = np.array(data)
    ohlcv = pd.DataFrame(arr,
                         columns=('time', 'open', 'highest', 'lowest', 'close',
                                  'volume'))
    ohlcv = ohlcv.sort_index(by='time')
    timeIndex = pd.date_range(time.strftime(
        '%Y-%m-%d %H:%M:%S', time.localtime(int(ohlcv.head(1).time) / 1000)),
                              periods=ohlcv.shape[0],
                              freq='15m')
    ohlcv.index = timeIndex
    dif, dea, bar = talib.MACD(ohlcv.close,
                               fastperiod=12,
                               slowperiod=26,
                               signalperiod=9)

    fig, axs = plt.subplots(figsize=(14, 7))

    #可视化K线和交易日
    qutotes = []
    for index, (d, o, c, h, l) in enumerate(
            zip(ohlcv.index, ohlcv.open, ohlcv.close, ohlcv.highest,
                ohlcv.lowest)):
        print(d)
        d = mpf.date2num(d)
        print(d)
        val = (d, o, c, h, l)
        qutotes.append(val)
    mpf.candlestick_ochl(axs,
                         qutotes,
                         width=1,
                         colorup="green",
                         colordown="red")
    print(qutotes)
    axs.autoscale_view()
    #axs.xaxis_date()#仅日线时使用

    plt.show()
예제 #27
0
def graph_data(stock):
    fig = plt.figure()
    ax1 = plt.subplot2grid(shape=(1, 1), loc=(0, 0))

    stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/' + \
                      stock + '/chartdata;type=quote;range=3m/csv'
    source_code = urllib.request.urlopen(stock_price_url).read().decode()
    stock_data = []
    split_source = source_code.split('\n')

    for line in split_source:
        if len(line.split(',')) == 6 and 'values' not in line:
            stock_data.append(line)

    date, close_price, high_price, low_price, open_price, volume = np.loadtxt(
        stock_data,
        dtype=np.float,
        delimiter=',',
        unpack=True,
        converters={0: bytespdate2num('%Y%m%d')})

    x = 0
    y = len(date)
    ohlc = []
    while x < y:
        append_me = date[x], open_price[x], high_price[x], low_price[x], \
                    close_price[x], volume[x]
        ohlc.append(append_me)
        x += 1

    candlestick_ochl(ax1, ohlc, width=0.4, colorup='g',
                     colordown='r')  # can use hex colors

    for label in ax1.xaxis.get_ticklabels():
        label.set_rotation(45)

    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
    ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))

    plt.xlabel('date')
    plt.ylabel('price')
    plt.title('Stock')
    plt.legend()
    plt.show()
예제 #28
0
def draw_tianbijun(stock):
    '''
    先画田碧君的趋势图片
    K线以及公式图片一起画
    '''
    dl = DownLoad()
    raw_data = dl.load_data(stock)
    #raw_data.index = raw_data.index.map(str2date2)
    H1 = ta.MA(np.asarray(raw_data['close']), timeperiod=8,
               matype=1)  #8日指数平滑均线
    H2 = ta.MA(H1, timeperiod=20, matype=1)

    H3 = ta.MA(np.asarray(raw_data['close']), timeperiod=8, matype=3)  #8日 DEMA
    H4 = ta.MA(H3, timeperiod=20, matype=1)

    H5 = ta.MA(np.asarray(raw_data['close']), timeperiod=8, matype=4)  #8日 DEMA
    H6 = ta.MA(H5, timeperiod=20, matype=1)

    #LH = ta.MA(np.asarray(raw_data['close']), timeperiod=240, matype=1) #240指数平滑均线
    #high_price = ta.MAX(np.asarray(raw_data['high']), timeperiod=36)
    #VAR1 = (high_price - np.asarray(raw_data['close'])) / (high_price - ta.MIN(np.asarray(raw_data['high']), timeperiod=36)) * 100
    #VAR2 = ta.MA(VAR1, timeperiod=5)
    #VAR3 = ta.MA(VAR2,timeperiod=8)

    length = -100
    fig = plt.figure()
    ax = fig.add_subplot(111)
    raw_data['time'] = raw_data['date'].map(date2num)
    data = DataFrame(raw_data,
                     columns=['time', 'open', 'close', 'high', 'low'])
    data = np.array(data)
    candlestick_ochl(ax,
                     data[length:],
                     width=0.6,
                     colordown=u'g',
                     colorup=u'r')

    plt.grid()
    plt.plot(raw_data['date'][length:], H1[length:], color='r', label='H1')
    #plt.plot(raw_data['date'][length:], H3[length:],color='y',label='H3')
    #plt.plot(raw_data['date'][length:], H5[length:],color='k',label='H3')
    plt.plot(raw_data['date'][length:], H2[length:], color='g',
             label='H2')  #没能解决中间周六周天节假日数据问题
    plt.show()
예제 #29
0
파일: figures.py 프로젝트: ifzz/NowTrade
 def add_chart(self, technical_indicator, row=1, plot_type='line', color='blue'):
     """
     This function adds a chart to the current figure.
     """
     axes = self.current_figure.add_subplot(self.figure_rows,
                                            1,
                                            row,
                                            sharex=self.figure_first_ax)
     if self.figure_first_ax is None:
         self.figure_first_ax = axes
     try:
         # Only works with ScalarFormatter
         axes.ticklabel_format(style='plain')
     except AttributeError:
         # Ignore on error
         pass
     if isinstance(technical_indicator, symbol_list.Symbol): # Candlesticks
         axes.set_title(str(technical_indicator))
         axes.set_ylabel('Price')
         cols = ['DATE',
                 technical_indicator.open,
                 technical_indicator.close,
                 technical_indicator.high,
                 technical_indicator.low]
         candlestick_ochl(axes, self.data_frame[cols].values, colorup=u'g')
         self.add_actions(technical_indicator, axes)
     else:
         if not isinstance(technical_indicator, str):
             # Probably forgot to submit the TI value
             technical_indicator = technical_indicator.value
         values = self.data_frame[str(technical_indicator)]
         axes.set_title(technical_indicator)
         axes.set_ylabel('Value')
         if plot_type == 'line':
             line, = axes.plot(self.data_frame['DATE'], values, color=color)
             self.legend.append(line)
         else:
             bars = axes.bar(self.data_frame['DATE'], values, color=color, width=0.3)
             self.legend.append(bars)
         self.legend_labels.append(technical_indicator)
     axes.xaxis_date()
     axes.autoscale_view()
예제 #30
0
    def generateGraph(self, quotes):
        self.clearGraphData()

        self.ax = self.fig.add_subplot(111)

        self.ax.set_title(_("Session candlestick graph"))

        #Set axis labels and grid overlay properites
        self.ax.set_xlabel(_("Sessions"), fontsize=12)
        self.ax.set_ylabel("$", fontsize=12)
        self.ax.grid(color='g', linestyle=':', linewidth=0.2)

        candlestick_ochl(self.ax,
                         quotes,
                         width=0.50,
                         colordown='r',
                         colorup='g',
                         alpha=1.00)
        self.graphBox.layout().addWidget(self.canvas)
        self.canvas.draw()
예제 #31
0
def candle_print(symbol, nmin, start, end):
    db = conn['Ctp_Bar_{}'.format(nmin)]
    coll = db[symbol]
    rs = coll.find({'datetime': {'$gte': parse(start), '$lt': parse(end)}}).sort('datetime', 1)
    rs = list(rs)
    df = pd.DataFrame(rs)
    print 'bar count:', len(df)

    if not len(df):
        return
    fields = ['datetime', 'open', 'close', 'high', 'low', 'volume', 'symbol', 'openInterest', ]
    fields = ['datetime', 'open', 'close', 'high', 'low', 'volume', 'openInterest']
    df = df[fields]
    # data = df.as_matrix()
    data = df.values

    # write into file
    df.to_csv('{}-{}-{}-{}.csv'.format(symbol, nmin, start, end))

    def date_to_num(dates):
        num_time = []
        for date in dates:
            num_date = mpl.dates.date2num(date)
            num_time.append(num_date)
        return num_time

    #     xx = date_to_num(data[:,0])
    data[:, 0] = range(0, len(data))

    fig, ax = plt.subplots(figsize=(15, 8))
    fig.subplots_adjust(bottom=0.5)

    #     ax.set_xticks(range(0,len(data)))

    mpf.candlestick_ochl(ax, data, width=0.6, colorup='r', colordown='g', alpha=1.0)
    plt.grid(True)
    # 设置日期刻度旋转的角度
    plt.xticks(rotation=30)
    plt.title(symbol + ' bar:' + nmin)
    plt.xlabel('Date')
    plt.ylabel('Price')
예제 #32
0
def kline_imgs(input_df, stock_dir, image_save=False, img_shape=(112, 112)):
    price_df = input_df.loc[:, ['date', 'open', 'close', 'high', 'low']]
    date_se = input_df.loc[:, 'date'][19:]
    num_imgs = price_df.shape[0] - 20 + 1
    # TODO 相对位置
    # price_max = price_df.max()
    # price_min = price_df.min()
    plt.grid(False)
    # 用来储存imgs
    row_pix, col_pix = img_shape
    imgs_arr = np.zeros(shape=(num_imgs, row_pix, col_pix, 3), dtype='uint8')
    bar = ProgressBar(total=num_imgs)
    for num in range(num_imgs):
        begin_idx = num
        end_idx = num + 19
        date = str(date_se[end_idx])[:10]
        year = date[:4]
        img_path = stock_dir + '/' + year + '/' + date + '.png'
        img_df = pd.DataFrame(price_df.iloc[begin_idx:end_idx + 1])
        # 图像不标注日期,为了使k线连续,改为连续的数字即可(int或float都可以?)
        img_df.loc[:, 'date'] = list(range(20))
        if image_save:
            # 开始作图
            fig, ax = plt.subplots()
            candlestick_ochl(ax, img_df.values, width=0.005, colorup='g', colordown='r')
            ax.set_xticks([])
            ax.set_yticks([])
            fig.set_size_inches(row_pix / 300, col_pix / 300)
            ax.set_facecolor('black')
            fig.set_facecolor('black')
            plt.gca().xaxis.set_major_locator(plt.NullLocator())
            plt.gca().yaxis.set_major_locator(plt.NullLocator())
            plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
            plt.margins(0.1, 0.1)
            fig.savefig(img_path, format='png', facecolor='black', dpi=300, pad_inches=0)
            plt.close('all')
        imgs_arr[num] = np.array(Image.open(img_path).convert(mode='RGB'))
        bar.move()
        bar.log('generating kline imgs')
    # imgs_arr不包含前19天
    return imgs_arr
예제 #33
0
def pancan(*args):
    if args[0] is not None:
        symbol = args[0]
    else:
        symbol = "GOOG"
    # get the data on a symbol
    data = get_data_yahoo(symbol, datetime.now() - timedelta(days=90))
    close_price = data['Adj Close']
    # format time properly
    dates = data.index.to_pydatetime()
    times = mdates.date2num(dates)
    # make an array of tuples in the specific order needed
    q = izip(times, data['Open'], data['Close'], data['High'], data['Low'])
    # construct and show the plot
    plt.figure(figsize=(10, 4))
    ax1 = plt.gca()
    ax1.xaxis_date()
    candlestick_ochl(ax1, q, width=0.6, colorup='g', colordown='r')
    close_price.plot()
    plt.savefig("static/candle.png")
    plt.clf()
예제 #34
0
 def plot_(self, list):
     """利用plot画K线"""
     fig = plt.figure(facecolor='#07000d',
                      figsize=(self.parameter['ax_width'],
                               self.parameter['ax_high']))
     ax = plt.subplot2grid((6, 4), (1, 0),
                           rowspan=4,
                           colspan=4,
                           axisbg='#07000d')
     #fig, ax = plt.subplots(facecolor='#07000d', figsize=(self.parameter['ax_width'], self.parameter['ax_high']))
     fig.subplots_adjust(bottom=0.2)
     # 设置X轴刻度为日期时间
     ax.xaxis_date()
     # 设置legend
     plt.legend(labels=['a', 'b'], loc='best')
     plt.title(u"{}-{} HistSpreadPrice".format(self.histCode1,
                                               self.histCode2),
               color='r')
     plt.ylabel("spreadPrice")
     plt.xticks(rotation=45)  # 45°
     plt.yticks()
     ax.yaxis.label.set_color("b")  # Y轴图例文字蓝色
     # 边框上色
     ax.spines['top'].set_color('#5998ff')
     ax.spines['right'].set_color('#5998ff')
     ax.spines['left'].set_color("#5998ff")
     ax.spines['bottom'].set_color("#5998ff")
     ax.tick_params(axis='x', colors='w')
     ax.tick_params(axis='y', colors='w')
     # ax 绘图Axes的实例
     # width    图像中红绿矩形的宽度,代表天数
     # alpha    矩形的颜色的透明度
     # colorup  收盘价格大于开盘价格时的颜色
     mpf.candlestick_ochl(ax,
                          list,
                          width=.9,
                          colorup='g',
                          colordown='r',
                          alpha=.9)
     plt.grid()
예제 #35
0
def drawPicture(df):
    #绘图部分
    candleDf = df.as_matrix()
    num_time = exectue.date_to_num(candleDf[:, 0])
    candleDf[:, 0] = num_time
    fig, ax = plt.subplots(figsize=(20, 5))
    fig.subplots_adjust(bottom=0.1)
    mpf.candlestick_ochl(ax,
                         candleDf,
                         width=1,
                         colorup='r',
                         colordown='g',
                         alpha=1.0)
    plt.grid(True)
    # 设置日期刻度旋转的角度
    plt.xticks(rotation=30)
    plt.title(ts_code)
    plt.xlabel('Date')
    plt.ylabel('Price')

    # x轴的刻度为日期
    ax.xaxis_date()
예제 #36
0
    def plot(self):
        dates = list(map(pltdates.datestr2num, self.dates[:self.position + 1]))
        values = zip(dates, self.open[:self.position + 1],
                     self.close[:self.position + 1],
                     self.high[:self.position + 1],
                     self.low[:self.position + 1])

        fig, ax = plt.subplots()
        fig.subplots_adjust(bottom=0.2)
        finance.candlestick_ochl(ax, values, width=60 / 86400)

        plt.plot(self.buy_orders['x'], self.buy_orders['y'], 'g^')
        plt.plot(self.sell_orders['x'], self.sell_orders['y'], 'rv')

        self._plot_indicators(dates)

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

        plt.show()
예제 #37
0
    def draw_result(self, start, end, sh):
        fig = plt.figure()
        ax = fig.add_subplot(311)
        self.raw_data.index = self.raw_data['date']
        raw_data = self.raw_data[start:end]
        raw_data['time'] = raw_data['date'].map(date2num)

        #K线 信号
        data = DataFrame(raw_data,
                         columns=['time', 'open', 'close', 'high', 'low'])
        data = np.array(data)
        candlestick_ochl(ax, data, width=0.6, colordown=u'g', colorup=u'r')

        plt.grid()
        plt.plot(raw_data['date'], raw_data['H1'], color='r', label='H1')
        plt.plot(raw_data['date'], raw_data['H2'], color='y', label='H2')

        #大盘
        ax = fig.add_subplot(312)
        plt.grid()
        sh.index = sh['date']
        sh_data = sh[start:end]
        sh_data['time'] = sh_data['date'].map(date2num)
        df = DataFrame(sh_data,
                       columns=['time', 'open', 'close', 'high', 'low'])
        print df['time']
        df = np.array(df)
        candlestick_ochl(ax, df, width=0.6, colordown=u'g', colorup=u'r')

        #收益图
        plt.subplot(3, 1, 3)
        plt.grid()
        print len(self.money), len(raw_data.index)
        plt.plot(raw_data['date'], self.money)

        # plt.subplot(3,1,3)
        # plt.grid()
        # plt.plot(raw_data['date'], raw_data['line1'], color='b',label='line1')
        plt.show()
예제 #38
0
파일: tools.py 프로젝트: qyqbird/stock_work
    def draw_result(self,start,end,sh):
        fig = plt.figure()
        ax = fig.add_subplot(311)
        self.raw_data.index = self.raw_data['date']
        raw_data = self.raw_data[start:end]
        raw_data['time'] = raw_data['date'].map(date2num)

        #K线 信号
        data = DataFrame(raw_data, columns=['time', 'open','close','high','low'])
        data = np.array(data)
        candlestick_ochl(ax,data,width=0.6,colordown=u'g',colorup=u'r')

        plt.grid()
        plt.plot(raw_data['date'], raw_data['H1'], color='r',label='H1')
        plt.plot(raw_data['date'], raw_data['H2'], color='y',label='H2')

        #大盘
        ax = fig.add_subplot(312)
        plt.grid()      
        sh.index = sh['date']
        sh_data = sh[start:end]
        sh_data['time'] = sh_data['date'].map(date2num)
        df = DataFrame(sh_data, columns=['time', 'open','close','high','low'])
        print df['time']
        df = np.array(df)
        candlestick_ochl(ax,df,width=0.6,colordown=u'g',colorup=u'r')

        #收益图
        plt.subplot(3,1,3)
        plt.grid()
        print len(self.money),len(raw_data.index)
        plt.plot(raw_data['date'],self.money)

        # plt.subplot(3,1,3)
        # plt.grid()
        # plt.plot(raw_data['date'], raw_data['line1'], color='b',label='line1')
        plt.show()
예제 #39
0
def draw_tianbijun(stock):
    '''
    先画田碧君的趋势图片
    K线以及公式图片一起画
    '''
    dl = DownLoad()
    raw_data = dl.load_data(stock)
    #raw_data.index = raw_data.index.map(str2date2)
    H1 = ta.MA(np.asarray(raw_data['close']), timeperiod=8,matype=1)    #8日指数平滑均线
    H2 = ta.MA(H1, timeperiod=20,matype=1)

    H3 = ta.MA(np.asarray(raw_data['close']), timeperiod=8,matype=3)    #8日 DEMA
    H4 = ta.MA(H3, timeperiod=20,matype=1)

    H5 = ta.MA(np.asarray(raw_data['close']), timeperiod=8,matype=4)    #8日 DEMA
    H6 = ta.MA(H5, timeperiod=20,matype=1)

    #LH = ta.MA(np.asarray(raw_data['close']), timeperiod=240, matype=1) #240指数平滑均线
    #high_price = ta.MAX(np.asarray(raw_data['high']), timeperiod=36)
    #VAR1 = (high_price - np.asarray(raw_data['close'])) / (high_price - ta.MIN(np.asarray(raw_data['high']), timeperiod=36)) * 100
    #VAR2 = ta.MA(VAR1, timeperiod=5)
    #VAR3 = ta.MA(VAR2,timeperiod=8)  

    length = -100
    fig = plt.figure()
    ax = fig.add_subplot(111)
    raw_data['time'] = raw_data['date'].map(date2num)
    data = DataFrame(raw_data, columns=['time', 'open','close','high','low'])
    data = np.array(data)
    candlestick_ochl(ax,data[length:],width=0.6,colordown=u'g',colorup=u'r')

    plt.grid()
    plt.plot(raw_data['date'][length:], H1[length:],color='r',label='H1')
    #plt.plot(raw_data['date'][length:], H3[length:],color='y',label='H3')
    #plt.plot(raw_data['date'][length:], H5[length:],color='k',label='H3')
    plt.plot(raw_data['date'][length:], H2[length:], color='g',label='H2')     #没能解决中间周六周天节假日数据问题
    plt.show()
예제 #40
0
def graphData(stockData, color_palette):
    date = stockData['date']
    openp = stockData['openp']
    closep = stockData['closep']
    highp = stockData['highp']
    lowp = stockData['lowp']
    volume = stockData['volume']

    # matplotlibs candlecharts uses tuples
    x = 0
    y = len(date)
    candleAr = []
    while x < y:
        appendLine = date[x],openp[x],closep[x],highp[x],lowp[x]
        candleAr.append(appendLine)
        x= x+1

    # Define colors for plot
    bg_color = color_palette['bg_color']
    text_color = color_palette['text_color']
    spine_color = color_palette['spine_color']
    up_color = color_palette['up_color']
    down_color = color_palette['down_color']
    vol_color = color_palette['vol_color']

    # Define figsize and candle width (depends on tick amount)
    fig_width = max(min(round(len(date)/10), 14),8)
    candle_width = (len(date) < 30)*0.2 + (len(date) < 100)*0.2 + (len(date) < 200)*0.1 + 0.3

    # Create figure and axes with dark color
    fig = plt.figure(facecolor=bg_color, figsize=(fig_width, 6))
    ax1 = plt.subplot2grid((5, 4), (0, 0), rowspan=4, colspan=4, axisbg=bg_color)
    ax1.grid(True, color=text_color)
    candlestick_ochl(ax1, candleAr, width=candle_width, colorup=up_color, colordown=down_color)
    ax1.set_xlabel('Date')
    ax1.set_ylabel('Stock price')
    ax1.yaxis.label.set_color(text_color)

    #Border and tick colors
    ax1.spines['bottom'].set_color(spine_color)
    ax1.spines['top'].set_color(spine_color)
    ax1.spines['left'].set_color(spine_color)
    ax1.spines['right'].set_color(spine_color)
    ax1.tick_params(axis='y', colors=text_color)
    ax1.tick_params(axis='x', colors=text_color)
    ax1.xaxis.set_major_formatter(plt.NullFormatter())
    ax1.axes.get_xaxis().set_ticklabels([])

    ax2 = plt.subplot2grid((5,4), (4,0), rowspan=4, colspan=4, sharex = ax1, axisbg=bg_color)
    ax2.plot(date, volume, vol_color, linewidth=.8)
    volumeMin = volume.min()
    ax2.fill_between(date, volumeMin, volume, facecolor=vol_color, alpha=.5)
    ax2.set_ylabel('Volume', color=text_color)
    ax2.spines['bottom'].set_color(spine_color)
    ax2.spines['top'].set_color(spine_color)
    ax2.spines['left'].set_color(spine_color)
    ax2.spines['right'].set_color(spine_color)
    ax2.tick_params(axis='y', colors=text_color)
    ax2.tick_params(axis='x', colors=text_color)
    ax2.axes.get_yaxis().set_ticklabels([])
    ax2.grid(False)

    # For some reason autfill can't recognize this
    ax2.xaxis.set_major_locator(mticker.MaxNLocator(10))
    ax2.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

    for label in ax2.xaxis.get_ticklabels():
        label.set_rotation(45)

    plt.setp(ax1.get_xticklabels(), visible=False)
    plt.subplots_adjust(bottom=.19, left= .09, right=.93, top=.95, wspace=0.2, hspace=.0)

    plt.show()
def graph_data(stock):
    fig = plt.figure(facecolor='#f0f0f0')
    ax1 = plt.subplot2grid(shape=(6, 1), loc=(0, 0), rowspan=1, colspan=1)
    plt.title(stock)
    plt.ylabel('H-L')
    ax2 = plt.subplot2grid(shape=(6, 1), loc=(1, 0), rowspan=4, colspan=1,
                           sharex=ax1)
    plt.ylabel('price')
    ax2v = ax2.twinx()
    ax3 = plt.subplot2grid(shape=(6, 1), loc=(5, 0), rowspan=1, colspan=1,
                           sharex=ax1)
    plt.ylabel('MAvgs')

    stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/' + \
                      stock + '/chartdata;type=quote;range=1y/csv'
    source_code = urllib.request.urlopen(stock_price_url).read().decode()
    stock_data = []
    split_source = source_code.split('\n')

    for line in split_source:
        if len(line.split(',')) == 6 and 'values' not in line:
            stock_data.append(line)

    date, close_price, high_price, low_price, open_price, volume = np.loadtxt(
        stock_data,
        dtype=np.float,
        delimiter=',',
        unpack=True,
        converters={0: bytespdate2num('%Y%m%d')})

    x = 0
    y = len(date)
    ohlc = []
    while x < y:
        append_me = date[x], open_price[x], high_price[x], low_price[x], \
                    close_price[x], volume[x]
        ohlc.append(append_me)
        x += 1

    ma1 = moving_average(close_price, MA1)
    ma2 = moving_average(close_price, MA2)
    start = len(date[MA2 - 1:])

    h_l = list(map(high_miinus_low, high_price, low_price))

    ax1.plot_date(date[-start:], h_l[-start:], '-', label='H-L')
    ax1.yaxis.set_major_locator(mticker.MaxNLocator(nbins=5, prune='lower'))

    candlestick_ochl(ax2, ohlc[-start:], width=0.4, colorup='g',
                     colordown='r')  # can use hex colors

    ax2.grid(True)

    bbox_props = dict(boxstyle='round', facecolor='y', edgecolor='k', lw=1)

    ax2.annotate(str(close_price[-1]), xy=(date[-1], close_price[-1]),
                 xytext=(date[-1] + 4, close_price[-1]), bbox=bbox_props)
    ax2v.plot([], [], color='#007983', label='Volume', alpha=0.4)
    ax2v.fill_between(date[-start:], 0, volume[-start:], facecolor='#007983',
                      alpha=0.4)
    ax2v.axes.yaxis.set_ticklabels([])
    ax2v.grid(False)
    ax2v.set_ylim(0, 2 * volume.max())

    ax2.yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))
    ax2.yaxis.set_major_locator(mticker.MaxNLocator(prune='lower'))

    ax3.plot(date[-start:], ma1[-start:], linewidth=1, label=str(MA1) + 'MA')
    ax3.plot(date[-start:], ma2[-start:], linewidth=1, label=str(MA2) + 'MA')
    ax3.yaxis.set_major_locator(mticker.MaxNLocator(prune='upper', nbins=5))

    for label in ax3.xaxis.get_ticklabels():
        label.set_rotation(45)

    ax3.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
    ax3.xaxis.set_major_locator(mticker.MaxNLocator(10))

    ax3.fill_between(date[-start:], ma2[-start:], ma1[-start:],
                     where=(ma1[-start:] < ma2[-start:]),
                     facecolor='r', edgecolor='r', alpha=0.5)
    ax3.fill_between(date[-start:], ma2[-start:], ma1[-start:],
                     where=(ma1[-start:] > ma2[-start:]),
                     facecolor='g', edgecolor='g', alpha=0.5)

    plt.setp(ax1.get_xticklabels(), visible=False)
    plt.setp(ax2.get_xticklabels(), visible=False)
    plt.subplots_adjust(left=0.11, bottom=0.24, right=0.90, top=0.90,
                        wspace=0.2, hspace=0)

    ax1.legend()
    leg = ax1.legend(loc=9, ncol=1, prop={'size': 11})
    leg.get_frame().set_aplha = 0.4
    ax2v.legend()
    leg = ax2v.legend(loc=9, ncol=1, prop={'size': 11})
    leg.get_frame().set_aplha = 0.4
    ax3.legend()
    leg = ax3.legend(loc=8, ncol=2, prop={'size': 11})
    leg.get_frame().set_aplha = 0.4

    plt.show()
    fig.savefig('google.png', facecolor='#f0f0f0')
예제 #42
0
#Plotting financial plots
import matplotlib.finance as mpf

start=(2014,5,1)
end=(2014,6,30)

#Get historic prices of German DAX index ^GDAXI
quotes=mpf.quotes_historical_yahoo_ochl('^GDAXI',start,end)

#Data comes out as Open, High,Low,Close,and Volume
quotes[:2]

#Create candlestick plots
fig,ax=plt.subplots(figsize=(7,5))
fig.subplots_adjust(bottom=0.2)
mpf.candlestick_ochl(ax,quotes,width=0.6,colorup='b',colordown='r')
plt.grid(True)
ax.xaxis_date()
ax.autoscale_view()
plt.setp(plt.gca().get_xticklabels(),rotation=30)

#Create daily summary plots
fig,ax=plt.subplots(figsize=(7,5))
fig.subplots_adjust(bottom=0.2)
mpf.plot_day_summary_oclh(ax,quotes,colorup='b',colordown='r')
plt.grid(True)
ax.xaxis_date()
plt.title('DAX Index')
plt.ylabel('index level')
plt.setp(plt.gca().get_xticklabels(),rotation=30)
예제 #43
0
 def _plot(data, ax, **kwds):
     candles = candlestick_ochl(ax, data.values,
                                **kwds)
     return candles
예제 #44
0
def graphData(stock,MA1,MA2):
    stockFile = loadStock(stock)
    stockFile = stockFile[1:100]
    try:
        date, closep, highp, lowp, openp, volume = np.loadtxt(stockFile,delimiter=',', unpack=True,
                                                              converters={ 0: bytespdate2num('%Y%m%d')})
        x = 0
        y = len(date)
        newAr = []
        while x < y:
            appendLine = date[x],openp[x],highp[x],lowp[x],closep[x],volume[x]
            newAr.append(appendLine)
            x+=1

        Av1 = movingaverage(closep, MA1)
        Av2 = movingaverage(closep, MA2)
        print(closep)
        SP = len(date[MA2-1:])
        cA,cD = pywt.dwt(closep,'haar')
#SMA
#--------------------------------------
        fig = plt.figure(facecolor='#07000d')

        ax1 = plt.subplot2grid((6,4), (1,0), rowspan=4, colspan=4, axisbg='#07000d')
        candlestick_ochl(ax1, newAr[-SP:], width=.6, colorup='#53c156', colordown='#ff1717')

        Label1 = str(MA1)+' SMA'
        Label2 = str(MA2)+' SMA'
        newDate = date[-SP:]
        newDate = newDate[1::2]
        ax1.plot(newDate[-SP/2:],cA[-SP/2:],'#e1edf9',label=Label1, linewidth=1.5)
        ax1.plot(newDate[-SP/2:],cD[-SP/2:],'#4ee6fd',label=Label2, linewidth=1.5)

        ax1.grid(True, color='w')
        ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
        ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
        ax1.yaxis.label.set_color("w")
        ax1.spines['bottom'].set_color("#5998ff")
        ax1.spines['top'].set_color("#5998ff")
        ax1.spines['left'].set_color("#5998ff")
        ax1.spines['right'].set_color("#5998ff")
        ax1.tick_params(axis='y', colors='w')
        plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))
        ax1.tick_params(axis='x', colors='w')
        plt.ylabel('Stock price and Volume')
        maLeg = plt.legend(loc=9, ncol=2, prop={'size':7},
                   fancybox=True, borderaxespad=0.)
        maLeg.get_frame().set_alpha(0.4)
        textEd = pylab.gca().get_legend().get_texts()
        pylab.setp(textEd[0:5], color = 'w')

        ax1.yaxis.set_major_locator(mticker.MaxNLocator(nbins=5, prune='upper'))
        for label in ax1.xaxis.get_ticklabels():
            label.set_rotation(45)

        plt.suptitle(stock.upper(),color='w')
        plt.setp(ax1.get_xticklabels(), visible=True)

        # ax1.annotate('Big news!',(date[510],Av1[510]),
        #     xytext=(0.8, 0.9), textcoords='axes fraction',
        #     arrowprops=dict(facecolor='white', shrink=0.05),
        #     fontsize=14, color = 'w',
        #     horizontalalignment='right', verticalalignment='bottom')

        plt.subplots_adjust(left=.09, bottom=.14, right=.94, top=.95, wspace=.20, hspace=0)
        plt.show()
        # fig.savefig('example.png',facecolor=fig.get_facecolor())

    except Exception as e:
        print('main loop',str(e))
예제 #45
0
def graphData(stock,MA1,MA2):
    stockFile = loadStock(stock)
    try:
        date, closep, highp, lowp, openp, volume = np.loadtxt(stockFile,delimiter=',', unpack=True,
                                                              converters={ 0: bytespdate2num('%Y%m%d')})
        x = 0
        y = len(date)
        newAr = []
        while x < y:
            appendLine = date[x],openp[x],highp[x],lowp[x],closep[x],volume[x]
            newAr.append(appendLine)
            x+=1

        Av1 = movingaverage(closep, MA1)
        Av2 = movingaverage(closep, MA2)

        SP = len(date[MA2-1:])

        fig = plt.figure(facecolor='#07000d')

        ax1 = plt.subplot2grid((6,4), (1,0), rowspan=4, colspan=4, axisbg='#07000d')
        candlestick_ochl(ax1, newAr[-SP:], width=.6, colorup='#53c156', colordown='#ff1717')

        Label1 = str(MA1)+' SMA'
        Label2 = str(MA2)+' SMA'
#SMA
#--------------------------------------
        ax1.plot(date[-SP:],Av1[-SP:],'#e1edf9',label=Label1, linewidth=1.5)
        ax1.plot(date[-SP:],Av2[-SP:],'#4ee6fd',label=Label2, linewidth=1.5)

        ax1.grid(True, color='w')
        ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
        ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
        ax1.yaxis.label.set_color("w")
        ax1.spines['bottom'].set_color("#5998ff")
        ax1.spines['top'].set_color("#5998ff")
        ax1.spines['left'].set_color("#5998ff")
        ax1.spines['right'].set_color("#5998ff")
        ax1.tick_params(axis='y', colors='w')
        plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))
        ax1.tick_params(axis='x', colors='w')
        plt.ylabel('Stock price and Volume')

#RSI
#--------------------------------------
        maLeg = plt.legend(loc=9, ncol=2, prop={'size':7},
                   fancybox=True, borderaxespad=0.)
        maLeg.get_frame().set_alpha(0.4)
        textEd = pylab.gca().get_legend().get_texts()
        pylab.setp(textEd[0:5], color = 'w')

        volumeMin = 0

        ax0 = plt.subplot2grid((6,4), (0,0), sharex=ax1, rowspan=1, colspan=4, axisbg='#07000d')
        rsi = rsiFunc(closep)
        rsiCol = '#c1f9f7'
        posCol = '#386d13'
        negCol = '#8f2020'



        ax0.plot(date[-SP:], rsi[-SP:], rsiCol, linewidth=1.5)
        ax0.axhline(70, color=negCol)
        ax0.axhline(30, color=posCol)
        ax0.fill_between(date[-SP:], rsi[-SP:], 70, where=(rsi[-SP:]>=70), facecolor=negCol, edgecolor=negCol, alpha=0.5)
        ax0.fill_between(date[-SP:], rsi[-SP:], 30, where=(rsi[-SP:]<=30), facecolor=posCol, edgecolor=posCol, alpha=0.5)
        ax0.set_yticks([30,70])
        ax0.yaxis.label.set_color("w")
        ax0.spines['bottom'].set_color("#5998ff")
        ax0.spines['top'].set_color("#5998ff")
        ax0.spines['left'].set_color("#5998ff")
        ax0.spines['right'].set_color("#5998ff")
        ax0.tick_params(axis='y', colors='w')
        ax0.tick_params(axis='x', colors='w')
        plt.ylabel('RSI')
#MACD
#--------------------------------------
        ax1v = ax1.twinx()
        ax1v.fill_between(date[-SP:],volumeMin, volume[-SP:], facecolor='#00ffe8', alpha=.4)
        ax1v.axes.yaxis.set_ticklabels([])
        ax1v.grid(False)
        ###Edit this to 3, so it's a bit larger
        ax1v.set_ylim(0, 3*volume.max())
        ax1v.spines['bottom'].set_color("#5998ff")
        ax1v.spines['top'].set_color("#5998ff")
        ax1v.spines['left'].set_color("#5998ff")
        ax1v.spines['right'].set_color("#5998ff")
        ax1v.tick_params(axis='x', colors='w')
        ax1v.tick_params(axis='y', colors='w')
        ax2 = plt.subplot2grid((6,4), (5,0), sharex=ax1, rowspan=1, colspan=4, axisbg='#07000d')
        fillcolor = '#00ffe8'
        nslow = 26
        nfast = 12
        nema = 9
        emaslow, emafast, macd = computeMACD(closep)
        ema9 = ExpMovingAverage(macd, nema)
        ax2.plot(date[-SP:], macd[-SP:], color='#4ee6fd', lw=2)
        ax2.plot(date[-SP:], ema9[-SP:], color='#e1edf9', lw=1)
        ax2.fill_between(date[-SP:], macd[-SP:]-ema9[-SP:], 0, alpha=0.5, facecolor=fillcolor, edgecolor=fillcolor)

        plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))
        ax2.spines['bottom'].set_color("#5998ff")
        ax2.spines['top'].set_color("#5998ff")
        ax2.spines['left'].set_color("#5998ff")
        ax2.spines['right'].set_color("#5998ff")
        ax2.tick_params(axis='x', colors='w')
        ax2.tick_params(axis='y', colors='w')
        plt.ylabel('MACD', color='w')
        ax2.yaxis.set_major_locator(mticker.MaxNLocator(nbins=5, prune='upper'))
        for label in ax2.xaxis.get_ticklabels():
            label.set_rotation(45)

        plt.suptitle(stock.upper(),color='w')
        plt.setp(ax0.get_xticklabels(), visible=False)
        plt.setp(ax1.get_xticklabels(), visible=False)

        # ax1.annotate('Big news!',(date[510],Av1[510]),
        #     xytext=(0.8, 0.9), textcoords='axes fraction',
        #     arrowprops=dict(facecolor='white', shrink=0.05),
        #     fontsize=14, color = 'w',
        #     horizontalalignment='right', verticalalignment='bottom')

        plt.subplots_adjust(left=.09, bottom=.14, right=.94, top=.95, wspace=.20, hspace=0)
        plt.show()
        # fig.savefig('example.png',facecolor=fig.get_facecolor())

    except Exception as e:
        print('main loop',str(e))
예제 #46
0
def CandleStickPlotting(plotdata):
	mondays = WeekdayLocator(MONDAY)        # major ticks on the mondays
	alldays    = DayLocator()              # minor ticks on the days
	weekFormatter = DateFormatter('%b %d')  # e.g., Jan 12
	dayFormatter = DateFormatter('%d')      # e.g., 12

	title = 'Candlestick diagram'
	#and then following the official example. 

	
	ala=np.matrix(plotdata)

	#print SP
	fig = plt.figure()
	#fig, ax = plt.subplot2grid((6,1), (0,0), rowspan=2, colspan=1)
	ax = plt.subplot2grid((6,1), (0,0), rowspan=3, colspan=1)
	plt.title('DSV stocks')
	ax2 = ax.twinx()
	ax3 = plt.subplot2grid((6,1), (3,0), rowspan=2,colspan=1, sharex=ax)

	# set the position of ax2 so that it is short (y2=0.32) but otherwise the same size as ax
	#ax2.set_position(matplotlib.transforms.Bbox([[0.125,0.1],[0.9,0.32]]))
	fig.subplots_adjust(bottom=0.2)
	ax.xaxis.set_major_locator(mondays)
	ax.xaxis.set_minor_locator(alldays)
	ax.xaxis.set_major_formatter(weekFormatter)

	#if ave1:
	SP = len(ala[:,0])
	candlestick_ochl(ax2, plotdata, width=0.6, colorup='#00ff00',colordown='#ff0000', alpha=0.4)
	#volume_overlay3(ax, plotdata, colorup='#00ff00', colordown='#ff0000', width=0.6, alpha=0.4)
	ax3.plot( ala[:,0], ala[:,2], 'g-', linewidth=0.4)

	# 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.yaxis.tick_right()
	ax2.yaxis.tick_left()
	
	# make bar plots and color differently depending on up/down for the day
	dates = np.squeeze(np.asarray(np.transpose(ala[:,0])))
	vol = np.squeeze(np.asarray(np.transpose(ala[:,5])))
	pos = ala[:,1]-ala[:,2]<0
	neg = ala[:,1]-ala[:,2]>0
	pos = np.squeeze(np.asarray(pos))
	neg = np.squeeze(np.asarray(neg))
	
	ax.bar(dates[pos],vol[pos],color='green',alpha=0.8)#,width=1,align='center')
	ax.bar(dates[neg],vol[neg],color='#df3a01',alpha=0.8)#,width=1,align='center')
	#x = np.arange(0.0, 2, 0.01)
	#y1 = np.sin(2*np.pi*x)
	#print np.squeeze(np.asarray(np.transpose(ala[:,0])))
	#ax.bar(ala[:,0],ala[:,5],color='cyan', alpha=0.4)#width=1,align='center'
	#ax.fill_between(np.squeeze(np.asarray(np.transpose(ala[:,0]))), np.squeeze(np.asarray(np.transpose(ala[:,5]))), 0,color='blue')#,color='blue', alpha=0.4)
	
	#scale the x-axis tight
	#ax.set_xlim(min(ala[:,0]),max(ala[:,0]))
	plt.setp(ax.get_xticklabels(), visible=False)
	ax.set_ylim(0, 3*max(ala[:,5]))
	ax.set_yticks([0,max(ala[:,5])])
	# the y-ticks for the bar were too dense, keep only every third one
	#yticks = ax2.get_yticks()
	#ax2.set_yticks(yticks[::3])

	ax.yaxis.set_label_position("right")
	ax.set_ylabel('Volume', size=12)

	ax2.yaxis.set_label_position("left")
	ax2.set_ylabel('Price', size=12)

	# format the x-ticks with a human-readable date. 
	xt = ax3.get_xticks()
	new_xticks = [datetime.date(num2date(d)) for d in xt]
	ax3.set_xticklabels(new_xticks,rotation=45, horizontalalignment='right')
	
	ax.patch.set_facecolor('gray')
	
	#plt.tight_layout()
	plt.setp( plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
	
	#plt.hod(True)
	#plt.show()
	savefig('foo.pdf', facecolor='gray', edgecolor='gray')#fig.get_facecolor()
예제 #47
0
파일: screener.py 프로젝트: tamulemon/tata
def plotGraph(stock, date, SP, prices, volume, sma1, sma2, smap1, smap2, rsi, macd, ema9):
    try:   
        fig = plt.figure(facecolor='#07000d')

        ax1 = plt.subplot2grid((9,4), (1,0), rowspan=4, colspan=4, axisbg='#07000d')
        candlestick_ochl(ax1, prices[-SP:], width=.6, colorup='#53c156', colordown='#ff1717')

        Label1 = str(smap1)+' SMA'
        Label2 = str(smap2)+' SMA'

        ax1.plot(date[-SP:],sma1[-SP:],'#e1edf9',label=Label1, linewidth=1.5)
        ax1.plot(date[-SP:],sma2[-SP:],'#4ee6fd',label=Label2, linewidth=1.5)
        
        ax1.grid(True, color='w')
        ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
        ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
        ax1.yaxis.label.set_color("w")
        ax1.spines['bottom'].set_color("#5998ff")
        ax1.spines['top'].set_color("#5998ff")
        ax1.spines['left'].set_color("#5998ff")
        ax1.spines['right'].set_color("#5998ff")
        ax1.tick_params(axis='y', colors='w')
        plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))
        ax1.tick_params(axis='x', colors='w')
        plt.ylabel('Stock price and Volume')

        maLeg = plt.legend(loc=9, ncol=2, prop={'size':7},
                   fancybox=True, borderaxespad=0.)
        maLeg.get_frame().set_alpha(0.4)
        textEd = pylab.gca().get_legend().get_texts()
        pylab.setp(textEd[0:5], color = 'w')

        volumeMin = 0
        
        ax0 = plt.subplot2grid((9,4), (0,0), sharex=ax1, rowspan=1, colspan=4, axisbg='#07000d')

        rsiCol = '#c1f9f7'
        posCol = '#386d13'
        negCol = '#8f2020'
        
        ax0.plot(date[-SP:], rsi[-SP:], rsiCol, linewidth=1.5)
        ax0.axhline(70, color=negCol)
        ax0.axhline(30, color=posCol)
        ax0.fill_between(date[-SP:], rsi[-SP:], 70, where=(rsi[-SP:]>=70), facecolor=negCol, edgecolor=negCol, alpha=0.5)
        ax0.fill_between(date[-SP:], rsi[-SP:], 30, where=(rsi[-SP:]<=30), facecolor=posCol, edgecolor=posCol, alpha=0.5)
        ax0.set_yticks([30,70])
        ax0.yaxis.label.set_color("w")
        ax0.spines['bottom'].set_color("#5998ff")
        ax0.spines['top'].set_color("#5998ff")
        ax0.spines['left'].set_color("#5998ff")
        ax0.spines['right'].set_color("#5998ff")
        ax0.tick_params(axis='y', colors='w')
        ax0.tick_params(axis='x', colors='w')
        plt.ylabel('RSI')

        ax1v = ax1.twinx()
        ax1v.fill_between(date[-SP:],volumeMin, volume[-SP:], facecolor='#00ffe8', alpha=.4)
        ax1v.axes.yaxis.set_ticklabels([])
        ax1v.grid(False)
        ###Edit this to 3, so it's a bit larger
        ax1v.set_ylim(0, 3*volume.max())
        ax1v.spines['bottom'].set_color("#5998ff")
        ax1v.spines['top'].set_color("#5998ff")
        ax1v.spines['left'].set_color("#5998ff")
        ax1v.spines['right'].set_color("#5998ff")
        ax1v.tick_params(axis='x', colors='w')
        ax1v.tick_params(axis='y', colors='w')

        ax2 = plt.subplot2grid((9,4), (5,0), sharex=ax1, rowspan=1, colspan=4, axisbg='#07000d')
        fillcolor = '#00ffe8'
        ax2.plot(date[-SP:], macd[-SP:], color='#4ee6fd', lw=2)
        ax2.plot(date[-SP:], ema9[-SP:], color='#e1edf9', lw=1)
        ax2.fill_between(date[-SP:], macd[-SP:]-ema9[-SP:], 0, alpha=0.5, facecolor=fillcolor, edgecolor=fillcolor)

        plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))
        ax2.spines['bottom'].set_color("#5998ff")
        ax2.spines['top'].set_color("#5998ff")
        ax2.spines['left'].set_color("#5998ff")
        ax2.spines['right'].set_color("#5998ff")
        ax2.tick_params(axis='x', colors='w')
        ax2.tick_params(axis='y', colors='w')
        plt.ylabel('MACD', color='w')
        ax2.yaxis.set_major_locator(mticker.MaxNLocator(nbins=5, prune='upper'))

        plt.suptitle(stock,color='w')

        plt.setp(ax0.get_xticklabels(), visible=False)
        ### add this ####
        plt.setp(ax1.get_xticklabels(), visible=False)
        plt.setp(ax2.get_xticklabels(), visible=False)
        
        #plt.subplots_adjust(left=.09, bottom=.14, right=.94, top=.95, wspace=.20, hspace=0)
        plt.show()
        fig.savefig('example.png',facecolor=fig.get_facecolor())    
    except Exception,e:
        print 'plotGraph',str(e)
예제 #48
0
        newAr = []
        while x < y:
            appendLine = date[x],openp[x],closep[x],highp[x],lowp[x],volume[x]
            newAr.append(appendLine)
            x+=1

        Av1 = movingaverage(closep, MA1)
        Av2 = ExpMovingAverage(closep, MA2)

        SP = len(date[MA2-1:])

        fig = plt.figure(facecolor='#07000d')

# Plotting the main price graph
        ax1 = plt.subplot2grid((7,4), (1,0), rowspan=4, colspan=4, axisbg='#07000d')
        candlestick_ochl(ax1, newAr[-SP:], width=.6, colorup='#53c156', colordown='#ff1717')

        Label1 = 'SMA '+str(Av1[-1]) #+str(Av1[-1])
        Label2 = str("%.2f" % updatingMoneyWave(highp, lowp, closep, nextMWPrice = True))+' new Price'     #+str(Av2[-1])

        ax1.plot(date[-SP:],Av1[-SP:],'#e1edf9',label=Label1, linewidth=1.5)
        ax1.plot(date[-SP:],Av2[-SP:],'#4ee6fd',label=Label2, linewidth=1.5)

        ax1.grid(True, color='w')
        ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
        ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
        ax1.yaxis.label.set_color("w")
        ax1.spines['bottom'].set_color("#5998ff")
        ax1.spines['top'].set_color("#5998ff")
        ax1.spines['left'].set_color("#5998ff")
        ax1.spines['right'].set_color("#5998ff")
예제 #49
0
def vGraphData(sSymbol, date, closep, highp, lowp, openp, volume,
               iShortSMA=10, iLongSMA=50,
               iRsiUpper=70, iRsiLower=30,
               iMacdSlow=26, iMacdFast=12, iMacdEma=9,
               bUseTalib=False,
               ):
    if bUseTalib:
        import talib

    x = 0
    y = len(date)
    newAr = []
    while x < y:
        appendLine = (date[x], openp[x], closep[x], highp[x], lowp[x], volume[x],)
        newAr.append(appendLine)
        x+=1

    if bUseTalib:
        Av1 = talib.SMA(closep, iShortSMA)
        Av2 = talib.SMA(closep, iLongSMA)
    else:
        Av1 = nSMA(closep, iShortSMA)
        Av2 = nSMA(closep, iLongSMA)

    SP = len(date[iLongSMA-1:])

    fig = plt.figure(facecolor='#07000d')

    ax1 = plt.subplot2grid((6,4), (1,0), rowspan=4, colspan=4, axisbg='#07000d')
    candlestick_ochl(ax1, newAr[-SP:], width=.6, colorup='#53c156', colordown='#ff1717')

    Label1 = str(iShortSMA)+' SMA'
    Label2 = str(iLongSMA)+' SMA'

    ax1.plot(date[-SP:],Av1[-SP:],'#e1edf9',label=Label1, linewidth=1.5)
    ax1.plot(date[-SP:],Av2[-SP:],'#4ee6fd',label=Label2, linewidth=1.5)

    uSpinesFg = "#5998ff"
    ax1.grid(True, color='white')
    ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
    ax1.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%Y-%m'))
    ax1.yaxis.label.set_color("w")
    ax1.spines['bottom'].set_color(uSpinesFg)
    ax1.spines['top'].set_color(uSpinesFg)
    ax1.spines['left'].set_color(uSpinesFg)
    ax1.spines['right'].set_color(uSpinesFg)
    ax1.tick_params(axis='y', colors='white')
    plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))
    ax1.tick_params(axis='x', colors='white')
    plt.ylabel('Stock price and Volume')

    maLeg = plt.legend(loc=9, ncol=2, prop={'size': 7},
                       fancybox=True, borderaxespad=0.0)
    maLeg.get_frame().set_alpha(0.4)

    oLegend = pylab.gca().get_legend()
    if oLegend:
        # AttributeError: 'NoneType' object has no attribute 'get_texts'
        textEd = oLegend.get_texts()
        pylab.setp(textEd[0:5], color = 'white')

    volumeMin = 0

    ax0 = plt.subplot2grid((6,4), (0,0), sharex=ax1, rowspan=1, colspan=4, axisbg='#07000d')
    rsi = rsiFunc(closep)
    rsiCol = '#c1f9f7'
    posCol = '#386d13'
    negCol = '#8f2020'

    ax0.plot(date[-SP:], rsi[-SP:], rsiCol, linewidth=1.5)
    ax0.axhline(iRsiUpper, color=negCol)
    ax0.axhline(iRsiLower, color=posCol)
    ax0.fill_between(date[-SP:], rsi[-SP:], iRsiUpper, where=(rsi[-SP:]>=iRsiUpper), facecolor=negCol, edgecolor=negCol, alpha=0.5)
    ax0.fill_between(date[-SP:], rsi[-SP:], iRsiLower, where=(rsi[-SP:]<=iRsiLower), facecolor=posCol, edgecolor=posCol, alpha=0.5)
    ax0.set_yticks([iRsiLower, iRsiUpper])
    ax0.yaxis.label.set_color("w")
    ax0.spines['bottom'].set_color(uSpinesFg)
    ax0.spines['top'].set_color(uSpinesFg)
    ax0.spines['left'].set_color(uSpinesFg)
    ax0.spines['right'].set_color(uSpinesFg)
    ax0.tick_params(axis='y', colors='white')
    ax0.tick_params(axis='x', colors='white')
    plt.ylabel('RSI')

    uVolumeFg = '#00ffe8'
    ax1v = ax1.twinx()
    ax1v.fill_between(date[-SP:],volumeMin, volume[-SP:], facecolor=uVolumeFg, alpha=.4)
    ax1v.axes.yaxis.set_ticklabels([])
    ax1v.grid(False)
    ###Edit this to 3, so it's a bit larger
    ax1v.set_ylim(0, 3*volume.max())
    ax1v.spines['bottom'].set_color(uSpinesFg)
    ax1v.spines['top'].set_color(uSpinesFg)
    ax1v.spines['left'].set_color(uSpinesFg)
    ax1v.spines['right'].set_color(uSpinesFg)
    ax1v.tick_params(axis='x', colors='white')
    ax1v.tick_params(axis='y', colors='white')

    ax2 = plt.subplot2grid((6,4), (5,0), sharex=ax1, rowspan=1, colspan=4, axisbg='#07000d')
    uMacdFill = '#00ffe8'
    emaslow, emafast, macd = computeMACD(closep, slow=iMacdSlow, fast=iMacdFast)
    ema9 = ExpMovingAverage(macd, iMacdEma)
    ax2.plot(date[-SP:], macd[-SP:], color='#4ee6fd', lw=2)
    ax2.plot(date[-SP:], ema9[-SP:], color='#e1edf9', lw=1)
    ax2.fill_between(date[-SP:], macd[-SP:]-ema9[-SP:], 0,
                     alpha=0.5, facecolor=uMacdFill, edgecolor=uMacdFill)

    plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))
    ax2.spines['bottom'].set_color(uSpinesFg)
    ax2.spines['top'].set_color(uSpinesFg)
    ax2.spines['left'].set_color(uSpinesFg)
    ax2.spines['right'].set_color(uSpinesFg)
    ax2.tick_params(axis='x', colors='white')
    ax2.tick_params(axis='y', colors='white')
    plt.ylabel('MACD', color='w')
    ax2.yaxis.set_major_locator(mticker.MaxNLocator(nbins=5, prune='upper'))
    for label in ax2.xaxis.get_ticklabels():
        label.set_rotation(45)

    plt.suptitle(sSymbol.upper(), color='white')

    plt.setp(ax0.get_xticklabels(), visible=False)
    ### add this ####
    plt.setp(ax1.get_xticklabels(), visible=False)

    ## ax1.annotate('Big news!',(date[510],Av1[510]),
    ##     xytext=(0.8, 0.9), textcoords='axes fraction',
    ##     arrowprops=dict(facecolor='white', shrink=0.05),
    ##     fontsize=14, color = 'w',
    ##     horizontalalignment='right', verticalalignment='bottom')

    plt.subplots_adjust(left=.09, bottom=.14, right=.94, top=.95, wspace=.20, hspace=0)
    plt.show()
예제 #50
0
def graphData(stock, plotStock, dataDict):
    try:
        stockFile = 'data/'+stock+'.txt'                
        date, openp, highp, lowp, closep, volume, adjclose = np.loadtxt(stockFile,delimiter=',',unpack=True,
                                                              converters={0: mdates.strpdate2num('%Y-%m-%d')})
        niftyFile = 'data/nsei.txt'
        dateNifty, openpNifty, highpNifty, lowpNifty, closepNifty, volumeNifty, adjclosep = np.loadtxt(niftyFile,delimiter=',',unpack=True,
                                                                  converters={0: mdates.strpdate2num('%Y-%m-%d')})
        date = np.flipud(date)
        openp = np.flipud(openp)
        highp = np.flipud(highp)
        lowp = np.flipud(lowp)
        closep = np.flipud(closep)
        volume = np.flipud(volume)
        dateNifty = np.flipud(dateNifty)
        closepNifty = np.flipud(closepNifty)

        print 'Drawing main chart...'        
        x = 0
        numOfDates = len(date)
        print "no of Dates: ", numOfDates
        numOfDatesNifty = len(dateNifty)
        print "no of Dates in Nifty: ", numOfDatesNifty
        candleArray = []
        otherDataList = np.repeat(0.0, numOfDatesNifty)
        print "len of candleArray", len(candleArray)

        while x < numOfDatesNifty:
            if plotStock == False:
                # create otherDataList for FII
                key = num2date(date[x])
                try:
                    otherDataList[x] = dataDict[key]
                except Exception, e:
                    #suppress this message if we are ploting stock because EPS date is very limited
                    if plotStock == False:
                        print 'No FII data for date: ' , str(e)
                        otherDataList[x] = 0
            else:
                #in most of the cases, reduntant data is present in stocks from yahoo. Delete stock data not present
                #in nifty
                if date[x] != dateNifty[x]:
                    print num2date(date[x]), num2date(dateNifty[x])
                    date = np.delete(date, x)
                    openp = np.delete(openp, x)
                    highp = np.delete(highp, x)
                    lowp = np.delete(lowp, x)
                    closep = np.delete(closep, x)
                    volume = np.delete(volume, x)
                    #otherDataList = np.delete(otherDataList, x)
                    continue
                else:
                    otherDataList[x] = closep[x]/closepNifty[x]*100
            #create candlArray in expected order for candlestic_ochl
            #maintain the below order of variables
            appendLine = date[x],openp[x],closep[x],highp[x],lowp[x]
            candleArray.append(appendLine)
            x+=1

        print "len of candleArray", len(candleArray)
        print 'len of otherdata', len(otherDataList)
        #print candleArray
        global MA1
        global MA2
        
        if len(date) > MA2:
            draw_MA = 1
            label1 = str(MA1)+' SMA'
            label2 = str(MA2)+' SMA'
        else:
            #skip MA ploting if no of candles are less than the bigger MA
            draw_MA = 0
            print 'skip MA'
           
        if draw_MA==1:
            Av1 = movingAverage(closep, MA1)
            Av2 = movingAverage(closep, MA2)
            
        fig = plt.figure(facecolor=blackThemeBG)
        fig.canvas.set_window_title(stock)
        mainChart = plt.subplot2grid((7,4), (0,0), rowspan=5, colspan=4, axisbg=blackThemeBG)
        candlestick_ochl(mainChart, candleArray, width=.75, colorup=blackThemeColorUp, colordown=blackThemeColorDown)
         
        if draw_MA==1:                     
            mainChart.plot(date[MA1:], Av1[MA1:], fastMA, label=label1, linewidth=1.5)  
            mainChart.plot(date[MA2:], Av2[MA2:], slowMA, label=label2, linewidth=1.5)
 
        mainChart.grid(True, color='w')
        mainChart.xaxis.set_major_locator(mticker.MaxNLocator(10))
        mainChart.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
        mainChart.yaxis.label.set_color("w")
        setAllSpineColor(mainChart, spinesColor)
        mainChart.tick_params(axis='y', colors='w')
        plt.ylabel('Stock Price')

        if draw_MA==1:
            plt.legend(loc=3, prop={'size':7}, fancybox=True)
            maLeg = plt.legend(loc=3, ncol=1, prop={'size':7}, fancybox=True, borderaxespad=0.)
            maLeg.get_frame().set_alpha(0.4)
        
        if plotStock == 1 and NiftyOverlay == True:
            plotNiftyOverlay(mainChart)

        print 'Drawing main chart... Done'
        if plotStock == 1:
            plotVolume(mainChart, date, volume)        
        
        print 'Drawing EPS/FII chart...'
        if plotStock == True:
            epsChart= plt.subplot2grid((7,4), (5,0), sharex=mainChart, rowspan=1, colspan=4, axisbg=blackThemeBG)
            epsChart.xaxis.set_visible(False)
        else:
            epsChart= plt.subplot2grid((7,4), (5,0), sharex=mainChart, rowspan=2, colspan=4, axisbg=blackThemeBG)
            epsChart.xaxis.set_visible(True)

        setAllSpineColor(epsChart, spinesColor)
        epsChart.tick_params(axis='y', colors='w')
        epsChart.tick_params(axis='x', colors='w')
        epsChart.yaxis.label.set_color("w")        
        epsChart.grid(True, color='w')
        
        if plotStock == True:
            plt.ylabel('Relative Strength')
        else:
            plt.ylabel('FII Data')
            epsChart.bar(date, otherDataList, color=epsBarColor, linewidth=0)
        
        #enable if you want lable pad to move further
        #epsChart.yaxis.labelpad = 20

        if plotStock == True:
            RS_MA = 200
            RS_AV = movingAverage(otherDataList, RS_MA)
            global TypeMansfield

            """
            MRP = (( RP(today) / sma(RP(today), n)) - 1 ) * 100
            Full details can be found in below link,
            http://www.trade2win.com/boards/technical-analysis/134944-stan-weinsteins-stage-analysis-97.html#post2137398
            """
            MansfieldRPI = np.repeat(0.0, numOfDatesNifty)
            x = 0
            while x < numOfDatesNifty:
                MansfieldRPI[x] = (otherDataList[x]/RS_AV[x] - 1)*100
                x +=1

            if TypeMansfield == True:
                epsChart.plot(dateNifty[RS_MA:], MansfieldRPI[RS_MA:], "#FFFF00", linewidth=1.5)
                #Draw a horizontal line --- on 0
                epsChart.plot([min(dateNifty),max(dateNifty)], [0, 0], '--', color='w')
            else:
                epsChart.plot(dateNifty, otherDataList, '#b93904', linewidth=1.5)
                epsChart.plot(dateNifty[RS_MA:], RS_AV[RS_MA:], slowMA, linewidth=1.5)

        epsChart.tick_params(axis='x', colors='w')
        epsChart.tick_params(axis='y', colors='w')
        print 'Drawing EPS chart.. Done'
            
        for label in mainChart.xaxis.get_ticklabels():
            label.set_rotation(90)
        
        if plotStock == 0:
            for label in epsChart.xaxis.get_ticklabels():
                label.set_rotation(45)
                    
        plt.xlabel('Date', color='w')
        plt.suptitle(stock+' Stock Price', color='w')        
        plt.setp(mainChart.get_xticklabels(), visible=False)
        plt.subplots_adjust(left=.09, bottom=.18, right=.94, top=.94, wspace=.20, hspace=0)
        plt.show()            
        fig.savefig('example.png', facecolor=fig.get_facecolor())
        matplotlib.rcParams.update({'savefig.facecolor':fig.get_facecolor()})
today = date.today()
start = (today.year - 1, today.month, today.day)

alldays = DayLocator()
months = MonthLocator()
month_formatter = DateFormatter("%b %Y")

# 从财经频道下载股价数据
symbol = 'BIDU' # 百度的股票代码
quotes = quotes_historical_yahoo_ochl(symbol, start, today)

# 创建figure对象,这是绘图组件的顶层容器
fig = plt.figure()
# 增加一个子图
ax = fig.add_subplot(111)
# x轴上的主定位器设置为月定位器,该定位器负责x轴上较粗的刻度
ax.xaxis.set_major_locator(months)
# x轴上的次定位器设置为日定位器,该定位器负责x轴上较细的刻度
ax.xaxis.set_minor_locator(alldays)
# x轴上的主格式化器设置为月格式化器,该格式化器负责x轴上较粗刻度的标签
ax.xaxis.set_major_formatter(month_formatter)

# 使用matplotlib.finance包的candlestick函数绘制k线图
candlestick_ochl(ax, quotes)
# 将x轴上的标签格式化为日期
fig.autofmt_xdate()
plt.title('Baidu, Inc. (BIDU)')
plt.show()

예제 #52
0
def candlestickData(stock,MA1,MA2):
    try:
        stockFile = 'dataDaily/'+stock+'.txt'

        date,closep,highp,lowp,openp,volume = np.loadtxt(stockFile,delimiter=',',unpack=True,
                                                         converters={0:mdates.strpdate2num('%Y%m%d')})

        # use while loop to build candlestick DATA set
        x = 0
        y = len(date)
        candleAr = []
        while x < y:
            appendLine = date[x],openp[x],closep[x],highp[x],lowp[x],volume[x]
            candleAr.append(appendLine)
            x+=1

        # generate moving average
        Av1 = movingaverage(closep, MA1)
        Av2 = movingaverage(closep, MA2)

        SP = len(date[MA2-1:]) # starting point

        #
        label1 = str(MA1)+' SMA'
        label2 = str(MA2)+' SMA'

        #print len(Av1),len(Av2),len(date)
        #print len(date),SP
        #print date[-SP:],Av1[-SP:]
        #time.sleep(5)
        
            
        #fig = plt.figure()
        fig = plt.figure(facecolor='#07000d') # background color
        
        # subplot 1: price
        #ax1 = plt.subplot(2,1,1)#(2,3,6), 2X3, and at place 6
        ax1 = plt.subplot2grid((5,4),(0,0),rowspan=4,colspan=4,axisbg='#07000d')

        # candle stick plot
        # make change to vline in candlestick()
        #candlestick(ax1,candleAr,width=0.8,colorup='#9eff15',colordown='#ff1717')
        candlestick_ochl(ax1,candleAr,width=0.8,colorup='#9eff15',colordown='#ff1717')

        #plot moving average
        ax1.plot(date[-SP:],Av1[-SP:],'#6998ff',label=label1,linewidth=1.5)
        ax1.plot(date[-SP:],Av2[-SP:],'#e1edf9',label=label2,linewidth=1.5)
        #ax1.plot(date[MA1-1:],Av1[:],'#6998ff',label=label1,linewidth=1.5)
        #ax1.plot(date[MA2-1:],Av2[:],'#e1edf9',label=label2,linewidth=1.5)
        
        #
        ax1.yaxis.label.set_color('w')
        ax1.spines['bottom'].set_edgecolor('#5998ff')
        ax1.spines['top'].set_edgecolor('#5998ff')
        ax1.spines['left'].set_edgecolor('#5998ff')
        ax1.spines['right'].set_edgecolor('#5998ff')
        ax1.tick_params(axis='y',colors='w')
        
        # label
        #plt.xlabel('Date')
        plt.ylabel('Price ($)',color='w')
        plt.suptitle(stock,color='w')

        # plot legend
        plt.legend(loc=2,prop={'size':6})

        # fill color
        #volumeMin = volume.min()
        volumeMin = 0

        # set tick label
        plt.setp(ax1.get_xticklabels(),visible=False)

        #grid
        ax1.grid(True,color='w')
        
        ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
        #ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

        for label in ax1.xaxis.get_ticklabels():
            label.set_rotation(45)

        # subplot 2: volume
        #ax2 = plt.subplot(2,1,2,sharex=ax1) #share axis, sync the axis
        ax2 = plt.subplot2grid((5,4),(4,0),sharex=ax1,rowspan=1,colspan=4,axisbg='#07000d') # shared axis
        # remove y axis tick lable for subplot2
        ax2.axes.yaxis.set_ticklabels([])
        
        ax2.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

        #
        ax2.yaxis.label.set_color('w')
        ax2.spines['bottom'].set_edgecolor('#5998ff')
        ax2.spines['top'].set_edgecolor('#5998ff')
        ax2.spines['left'].set_edgecolor('#5998ff')
        ax2.spines['right'].set_edgecolor('#5998ff')
        ax2.tick_params(axis='x',colors='w')
        ax2.tick_params(axis='y',colors='w')
        
        #ax2.bar(date,volume)
        ax2.plot(date,volume,'#00ffe8',linewidth=.8)
        ax2.fill_between(date,volumeMin,volume,facecolor='#00ffe8',alpha=.5)
        
        ax2.grid(False)
        plt.xlabel('Date')
        plt.ylabel('Volume')

        for label in ax2.xaxis.get_ticklabels():
            label.set_rotation(45)

        #adjust plot spaces
        plt.subplots_adjust(left=.09,bottom=.17,right=.93,top=.93,wspace=.20,hspace=.00)
        
        plt.show()
        fig.savefig('example.png',facecolor=fig.get_facecolor())

    except Exception, e:
        print 'failed main loop',str(e)
예제 #53
0
def _do_plot_candle(date, p_open, high, low, close, volume, view_index, symbol, day_sum, save, minute):
    """
    绘制不可交互的k线图
    param date: 融时间序列交易日时间,pd.DataFrame.index对象
    :param p_open: 金融时间序列开盘价格序列,np.array对象
    :param high: 金融时间序列最高价格序列,np.array对象
    :param low: 金融时间序列最低价格序列,np.array对象
    :param close: 金融时间序列收盘价格序列,np.array对象
    :param volume: 金融时间序列成交量序列,np.array对象
    :param symbol: symbol str对象
    :param day_sum: 端线图 matplotlib的版本有些有bug显示不对
    :param save: 是否保存可视化结果在本地
    :param minute: 是否是绘制分钟k线图
    """

    # 需要内部import不然每次import abupy都有warning,特别是子进程很烦人
    try:
        # noinspection PyUnresolvedReferences, PyDeprecation
        import matplotlib.finance as mpf
    except ImportError:
        # 2.2 才会有
        # noinspection PyUnresolvedReferences, PyDeprecation
        import matplotlib.mpl_finance as mpf

    if not g_only_draw_price:
        # 成交量,价格都绘制
        # noinspection PyTypeChecker
        fig, (ax1, ax2) = plt.subplots(2, sharex=True, figsize=(20, 12))
    else:
        # 只绘制价格
        fig, ax1 = plt.subplots(figsize=(6, 6))
    if day_sum:
        # 端线图绘制
        qutotes = []
        for index, (d, o, c, l, h) in enumerate(zip(date, p_open, close, low, high)):
            d = index if minute else mpf.date2num(d)
            val = (d, o, c, l, h)
            qutotes.append(val)
        # plot_day_summary_oclh接口,与mpf.candlestick_ochl不同,即数据顺序为开收低高
        mpf.plot_day_summary_oclh(ax1, qutotes, ticksize=5, colorup=__colorup__, colordown=__colordown__)
    else:
        # k线图绘制
        qutotes = []
        for index, (d, o, c, h, l) in enumerate(zip(date, p_open, close, high, low)):
            d = index if minute else mpf.date2num(d)
            val = (d, o, c, h, l)
            qutotes.append(val)
        # mpf.candlestick_ochl即数据顺序为开收高低
        mpf.candlestick_ochl(ax1, qutotes, width=0.6, colorup=__colorup__, colordown=__colordown__)

    if not g_only_draw_price:
        # 开始绘制成交量
        ax1.set_title(symbol)
        ax1.set_ylabel('ochl')
        ax1.grid(True)
        if not minute:
            ax1.xaxis_date()
        if view_index is not None:
            # 开始绘制买入交易日,卖出交易日,重点突出的点位
            e_list = date.tolist()
            # itertools.cycle循环使用备选的颜色
            for v, csColor in zip(view_index, itertools.cycle(K_PLT_MAP_STYLE)):
                try:
                    v_ind = e_list.index(v)
                except Exception as e:
                    # logging.exception(e)
                    logging.debug(e)
                    # 向前倒一个
                    v_ind = len(close) - 1
                label = symbol + ': ' + str(date[v_ind])
                ax1.plot(v, close[v_ind], 'ro', markersize=12, markeredgewidth=4.5,
                         markerfacecolor='None', markeredgecolor=csColor, label=label)

                # 因为candlestick_ochl 不能label了,所以使用下面的显示文字
                # noinspection PyUnboundLocalVariable
                ax2.plot(v, 0, 'ro', markersize=12, markeredgewidth=0.5,
                         markerfacecolor='None', markeredgecolor=csColor, label=label)
            plt.legend(loc='best')

        # 成交量柱子颜色,收盘价格 > 开盘,即红色
        # noinspection PyTypeChecker
        bar_red = np.where(close >= p_open, volume, 0)
        # 成交量柱子颜色,开盘价格 > 收盘。即绿色
        # noinspection PyTypeChecker
        bar_green = np.where(p_open > close, volume, 0)

        date = date if not minute else np.arange(0, len(date))
        ax2.bar(date, bar_red, facecolor=__colorup__)
        ax2.bar(date, bar_green, facecolor=__colordown__)

        ax2.set_ylabel('volume')
        ax2.grid(True)
        ax2.autoscale_view()
        plt.setp(plt.gca().get_xticklabels(), rotation=30)
    else:
        ax1.grid(False)

    if save:
        # 保存可视化结果在本地
        from pylab import savefig
        save_dir = os.path.join(K_SAVE_CACHE_PNG_ROOT, ABuDateUtil.current_str_date())
        png_dir = os.path.join(save_dir, symbol)
        ABuFileUtil.ensure_dir(png_dir)
        r_cnt = 0
        while True:
            png_name = '{}{}.png'.format(png_dir, '' if r_cnt == 0 else '-{}'.format(r_cnt))
            if not ABuFileUtil.file_exist(png_name):
                break
            r_cnt += 1
        # noinspection PyUnboundLocalVariable
        savefig(png_name)
        fig.clf()
        plt.close(fig)
    else:
        """
            save 了就不show了
        """
        plt.show()