Пример #1
0
def save_candlestick_with_volume_img(df, save_filepath):
    fig, ax = plt.subplots(nrows=2,
                           ncols=1,
                           figsize=(10, 10),
                           sharex=True,
                           gridspec_kw={'height_ratios': [4, 1]})
    mpl_finance.candlestick2_ochl(ax[0],
                                  df['open'],
                                  df['close'],
                                  df['high'],
                                  df['low'],
                                  width=1,
                                  colorup='r',
                                  colordown='g')
    ax[0].grid(False)
    ax[0].set_xticklabels([])
    ax[0].set_yticklabels([])
    ax[0].xaxis.set_visible(False)
    ax[0].yaxis.set_visible(False)
    ax[0].axis('off')
    mpl_finance.volume_overlay(ax[1],
                               df['open'],
                               df['close'],
                               df['volume'],
                               colorup='r',
                               colordown='g',
                               width=1)
    ax[1].grid(False)
    ax[1].set_xticklabels([])
    ax[1].set_yticklabels([])
    ax[1].xaxis.set_visible(False)
    ax[1].yaxis.set_visible(False)
    ax[1].axis('off')
    plt.savefig(save_filepath)
    plt.close("all")
Пример #2
0
 def __plt_volume(self, ax):
     ax2 = ax.twinx()
     ax2.set_ylim([0, max(self.ohcl["volume"])*4])
     ax2.set_ylabel("volume")
     finance.volume_overlay(ax2, self.ohcl["open"], 
                            self.ohcl["close"],
                            self.ohcl["volume"],
                            colorup='r', colordown='g',
                            width=0.5, alpha=0.5)
Пример #3
0
    def plot_stock_price(self):
        df = self.__data_center.query('TradeData.Stock.Daily', '600000.SSE')

        df = df[df['trade_date'] > years_ago(1)]

        # df['trade_date'] = df['trade_date'].apply(lambda d: mdates.date2num(d.to_pydatetime()))
        adjust_ratio = df['adj_factor']

        price_open = df['open'] * adjust_ratio
        price_close = df['close'] * adjust_ratio
        price_high = df['high'] * adjust_ratio
        price_low = df['low'] * adjust_ratio

        self.__figure.clear()
        ax1 = self.__figure.add_subplot(2, 1, 1)
        ax2 = self.__figure.add_subplot(2, 1, 2)

        time_serial = pd.to_datetime(df['trade_date'], format="%Y/%m/%d")

        # ax1 = plt.subplot2grid((3, 1), (0, 0), rowspan=2, colspan=1)  # 佔全圖2/3的子圖一
        ax1.set_xticks(range(0, len(time_serial), 10))  # 設定X軸座標
        ax1.set_xticklabels(time_serial)  # 設定X軸標籤
        mpf.candlestick2_ohlc(ax1, df['open'], df['high'], df['low'], df['close'], width=0.6, colorup='r',
                              colordown='k', alpha=1)  # 畫出K線圖
        ax1.tick_params('x', bottom=False, labelbottom=False)  # 子圖一不顯示X軸標籤
        ax1.set_axisbelow(True)  # 設定格線在最底圖層
        ax1.grid(True)  # 畫格線

        # ax2 = plt.subplot2grid((3, 1), (2, 0), rowspan=1, colspan=1, sharex=ax1)  # 佔全圖1/3的子圖二,設定X軸座標與子圖一相同
        mpf.volume_overlay(ax2, df['open'], df['close'], df['amount'] / 1000, colorup='b', colordown='b',
                           width=0.6, alpha=1)  # 畫出成交量
        ax2.set_axisbelow(True)  # 設定格線在最底圖層
        ax2.grid(True)  # 畫格線

        plt.gcf().autofmt_xdate()  # 斜放X軸標籤
        self.__canvas.draw()

        # mpf.candlestick2_ochl(axes, price_open, price_close, price_high, price_low, colorup='r', colordown='g')
        #
        # axes.set_xlabel('日期')
        # axes.set_ylabel('价格')
        # axes.set_xlim(0, len(df['trade_date']))
        # axes.set_xticks(range(0, len(df['trade_date']), 15))
        #
        # time_serial = pd.to_datetime(df['trade_date'], format="%Y/%m/%d")
        # axes.set_xticklabels([time_serial[x] for x in axes.get_xticks()])  # 标签设置为日期
        #
        # # X-轴每个ticker标签都向右倾斜45度
        # for label in axes.xaxis.get_ticklabels():
        #     label.set_rotation(45)
        #     label.set_fontsize(10)  # 设置标签字体
        # plt.show()

        self.__canvas.draw()
Пример #4
0
    def show_candle_stick(self, xstep=None, ystep=None):

        # 创建图像和子图
        fig = plt.figure(figsize=(20, 13))
        ax = fig.add_axes([0.02, 0.4, 1, 0.6])
        ax2 = fig.add_axes([0.02, 0.05, 1, 0.35])

        # k 线
        mpf.candlestick2_ochl(ax,
                              self.data['open'],
                              self.data['close'],
                              self.data['high'],
                              self.data['low'],
                              width=0.5,
                              colorup='r',
                              colordown='g',
                              alpha=0.8)

        # 设置横纵轴坐标
        # ax.set_xticks(range(0, len(self.data.index), 10))
        ax.set_yticks(
            np.arange(int(self.min_price * 0.9), int(self.max_price * 1.1), 2))
        # ax.set_ylabel('price')
        ax2.set_yticks(np.arange(0, int(self.max_vol * 1.1), 50000))
        # ax2.set_ylabel('vol')
        ax.plot(self.sma_10, label='10 日均线')
        ax.plot(self.sma_30, label='30 日均线')

        # 创建图例
        ax.legend(loc='upper center', fontsize=14)

        # 网格
        ax.grid(True)

        # 成交量
        mpf.volume_overlay(ax2,
                           self.data['open'],
                           self.data['close'],
                           self.data['volume'],
                           colorup='r',
                           colordown='g',
                           width=0.5,
                           alpha=0.8)
        # ax2.set_xticks(range(0, len(self.data.index), 10))
        # ax2.set_xticklabels(self.data.index.strftime('%Y-%m-%d'),
        #                     fontdict = {'fontsize':14},
        #                     rotation=30)
        ax2.set_xticks(np.arange(0, len(self.data.index), xstep))
        xlabels = list(
            self.data.index.strftime('%Y-%m-%d'))[0:len(self.data.index):xstep]
        ax2.set_xticklabels(xlabels, fontdict={'fontsize': 15}, rotation=45)
        print(xlabels)
        ax2.grid(True)
        plt.show()
Пример #5
0
def draw_kchart(stockNumber):
    stock_name = get_stock_name(stockNumber)
    if stock_name == "no": return "股票代碼錯誤!"
    end = datetime.datetime.now()
    date = end.strftime("%Y%m%d")
    year = str(int(date[0:4]) - 1)
    month = date[4:6]
    stock = pdr.DataReader(stockNumber + '.TW', 'yahoo', start= year+"-"+month,end=end)
    stock.index = stock.index.format(formatter=lambda x: x.strftime('%Y-%m-%d'))
    #KD
    sma_10 = talib.SMA(np.array(stock['Close']), 10)
    sma_30 = talib.SMA(np.array(stock['Close']), 30)
    stock['k'], stock['d'] = talib.STOCH(stock['High'], stock['Low'], stock['Close'])
    stock['k'].fillna(value=0, inplace=True)
    stock['d'].fillna(value=0, inplace=True)
    sma_5 = talib.SMA(np.array(stock['Close']), 5)
    sma_20 = talib.SMA(np.array(stock['Close']), 20)
    sma_60 = talib.SMA(np.array(stock['Close']), 60)
    fig = plt.figure(figsize=(20, 10))#,facecolor='black')
    fig.suptitle(stock_name.strip('加到投資組合'),fontsize="x-large", FontProperties=chinese_title)
    ax = fig.add_axes([0.1,0.5,0.75,0.4])
    plt.title("開盤價:"+str(round(stock['Open'][-1], 2))+"  收盤價:"+str(round(stock['Close'][-1], 2))+"\n最高價:"+str(round(stock['High'][-1] ,2))+"  最低價:"+str(round(stock['Low'][-1], 2)),fontsize="25",fontweight='bold',bbox=dict(facecolor='yellow',edgecolor='red',alpha=0.65),loc='left', FontProperties=chinese_subtitle)
    plt.title("更新日期:"+stock.index[-1],fontsize="20",fontweight='bold',loc="right", FontProperties=chinese_subtitle)
    plt.grid(True,linestyle="--",color='gray',linewidth='0.5',axis='both')

    ax2 = fig.add_axes([0.1,0.3,0.75,0.20])
    plt.grid(True,linestyle="--",color='gray',linewidth='0.5',axis='both')
    ax3 = fig.add_axes([0.1,0.03,0.75,0.20])
    mpf.candlestick2_ochl(ax, stock['Open'], stock['Close'], stock['High'],
                      stock['Low'], width=0.6, colorup='r', colordown='g', alpha=0.75)
    ax.plot(sma_5, label='5日均線')
    ax.plot(sma_10, label='10日均線')
    ax.plot(sma_20, label='20日均線')
    ax.plot(sma_60, label='60日均線')

    ax2.plot(stock['k'], label='K值')
    ax2.plot(stock['d'], label='D值')

    ax2.set_xticks(range(0, len(stock.index),10))
    ax2.set_xticklabels(stock.index[::10],fontsize="10", rotation=25)

    mpf.volume_overlay(ax3, stock['Open'], stock['Close'], stock['Volume'], colorup='r', colordown='g', width=0.5, alpha=0.8)
    ax3.set_xticks(range(0, len(stock.index),10))
    ax3.set_xticklabels(stock.index[::5],fontsize="10", rotation=45)

    ax.legend(prop=chinese_font, fontsize=20);
    ax2.legend(prop=chinese_font);
    plt.grid(True,linestyle="--",color='gray',linewidth='0.5',axis='both')
    plt.gcf()
    plt.savefig("Kchrat.png",bbox_inches='tight',dpi=300,pad_inches=0.0)
    plt.show()
    plt.close()
    return Imgur.showImgur("Kchrat")
Пример #6
0
def save_candlestick_img_with_volume(df, save_filepath):
    fig, ax = plt.subplots(nrows=2,
                           ncols=1,
                           figsize=(2.56, 2.56),
                           sharex=True,
                           gridspec_kw={'height_ratios': [2, 1]})
    mpl_finance.candlestick2_ochl(ax[0],
                                  df['Open'],
                                  df['Close'],
                                  df['High'],
                                  df['Low'],
                                  width=1,
                                  colorup='r',
                                  colordown='g')
    x_list = [i for i in range(len(df))]
    ma5_value = numpy.array(df["Open_MA_5"])
    ma25_value = numpy.array(df["Open_MA_25"])
    ma75_value = numpy.array(df["Open_MA_75"])

    ax[0].plot(x_list, ma5_value, markersize=2, color='black')
    ax[0].plot(x_list, ma25_value, markersize=2, color='y')
    ax[0].plot(x_list, ma75_value, markersize=2, color='b')
    ax[0].grid(False)
    ax[0].set_xticklabels([])
    ax[0].set_yticklabels([])
    ax[0].xaxis.set_visible(False)
    ax[0].yaxis.set_visible(False)
    y_min = min(df["Low"].min(), ma5_value.min(), ma25_value.min(),
                ma75_value.min())
    y_max = max(df["High"].max(), ma5_value.max(), ma25_value.max(),
                ma75_value.max())
    ax[0].set_ylim([y_min, y_max])
    ax[0].axis('off')
    mpl_finance.volume_overlay(ax[1],
                               df['Open'],
                               df['Close'],
                               df['volume'],
                               colorup='black',
                               colordown='black',
                               width=2)
    ax[1].grid(False)
    ax[1].set_xticklabels([])
    ax[1].set_yticklabels([])
    ax[1].xaxis.set_visible(False)
    ax[1].yaxis.set_visible(False)
    ax[1].axis('off')
    plt.savefig(save_filepath)
    plt.close("all")
    gc.collect()
Пример #7
0
def cal_plot_bband(ticker):
    print("Calculating B-Bands...")
    stock_data = stock.stock_preprocess_candlestick(ticker)
    upper, middle, lower = talib.BBANDS(stock_data[2],
                                        matype=talib.MA_Type.SMA)

    ##### plotting
    fig, ax_list = plt.subplots(2, 1, figsize=(15, 15))
    plt.suptitle('Bollinger Bands of {}({})'.format(
        stock.check_all_ticker(ticker)[0], ticker),
                 fontsize=20,
                 fontweight='bold')

    candlestick_ochl(ax_list[0],
                     stock_data[0],
                     width=0.8,
                     colorup='#53B987',
                     colordown='#EB4D5C')
    ax_list[0].xaxis.set_major_locator(mdates.MonthLocator())
    ax_list[0].xaxis.set_major_formatter(mdates.DateFormatter('%Y-%b-%d'))
    ax_list[0].get_xaxis().set_visible(False)
    volume_overlay(ax_list[1],
                   *stock_data[1:4],
                   width=0.8,
                   colorup='#53B987',
                   colordown='#EB4D5C')
    #ax_list[1].xaxis.set_major_locator(mdates.MonthLocator())
    #ax_list[1].xaxis.set_major_formatter(mdates.DateFormatter('%Y-%b-%d'))
    ax_list[1].set_xticks(range(0, len(stock_data[4]), 30))
    ax_list[1].set_xticklabels(stock_data[4][::30])

    ax_list[0].plot(stock_data[4], upper, color='#85C0C0')
    ax_list[0].plot(stock_data[4], middle, label='20-SMA', color='#AC7878')
    ax_list[0].plot(stock_data[4], lower, color='#85C0C0')
    ax_list[0].fill_between(stock_data[4], upper, lower, color='#F3F9F9')

    for i in range(2):
        ax_list[i].minorticks_on()
        ax_list[i].tick_params(axis='x', which='minor', bottom='off')

    ax_list[0].legend()
    plt.setp(plt.gca().get_xticklabels())
    fig.tight_layout()
    fig.subplots_adjust(hspace=0, top=0.95)
    #plt.show()
    stock.save_plot('BBANDS', ticker)
Пример #8
0
def analysis_stock(twc):
    year=2020
    month=1
    day=1
    
    start = datetime.datetime(year, month, day)
    df_2330 = pdr.DataReader('%d.TW' % twc, 'yahoo', start=start)
    df_2330.index = df_2330.index.format(formatter=lambda x: x.strftime('%Y-%m-%d')) 

    sma_10 = talib.SMA(np.array(df_2330['Close']), 10)
    sma_30 = talib.SMA(np.array(df_2330['Close']), 30)
    df_2330['k'], df_2330['d'] = talib.STOCH(df_2330['High'], df_2330['Low'], df_2330['Close'])
    df_2330['k'].fillna(value=0, inplace=True)
    df_2330['d'].fillna(value=0, inplace=True)

    fig = Figure(figsize=(24, 20))
    ax = fig.add_axes([0,0.3,1,0.4])
    ax2 = fig.add_axes([0,0.2,1,0.1])
    ax3 = fig.add_axes([0,0,1,0.2])

    ax.set_xticks(range(0, len(df_2330.index), 10))
    ax.set_xticklabels(df_2330.index[::10])
    mpf.candlestick2_ochl(ax, df_2330['Open'], df_2330['Close'], df_2330['High'],
                          df_2330['Low'], width=0.6, colorup='r', colordown='g', alpha=0.75)
    ax.plot(sma_10, label='10d avg')
    ax.plot(sma_30, label='30d avg')

    ax2.plot(df_2330['k'], label='K value')
    ax2.plot(df_2330['d'], label='D value')
    ax2.set_xticks(range(0, len(df_2330.index), 10))
    ax2.set_xticklabels(df_2330.index[::10])

    mpf.volume_overlay(ax3, df_2330['Open'], df_2330['Close'], df_2330['Volume'], colorup='r', colordown='g', width=0.5, alpha=0.8)
    ax3.set_xticks(range(0, len(df_2330.index), 10))
    ax3.set_xticklabels(df_2330.index[::10])

    ax.legend()
    ax2.legend()

    # Save it to a temporary buffer.
    buf = BytesIO()
    fig.savefig(buf, format="png")
    # Embed the result in the html output.
    data = base64.b64encode(buf.getbuffer()).decode("ascii")
    return f"<img src='data:image/png;base64,{data}'/>"
Пример #9
0
def draw_volume(df_Stock):
    fig = plt.figure(figsize=(24, 20))
    ax3 = fig.add_axes([0, 0, 1, 0.2])

    mpf.volume_overlay(ax3,
                       df_Stock['open'],
                       df_Stock['close'],
                       df_Stock['volume'],
                       colorup='r',
                       colordown='g',
                       width=0.5,
                       alpha=0.8)
    ax3.set_xticks(range(0, len(df_Stock.index), 1))
    ax3.set_xticklabels(df_Stock.index[::])
    plt.xticks(rotation=90)
    plt.grid()

    plt.savefig('static/media/volume.png')
Пример #10
0
    def buttonClicked(self):
        sid = self.ui.comboBox.currentText().split("-")[0].strip()

        self.ui.figure.clf()
        plt.cla()
        plt.clf()

        sma_20, sma_60, sma_120, sma_240, df = DataProcessing.stock_sma(sid)

        #用add_axes創建副圖框
        ax = self.ui.figure.add_axes([0.03, 0.4, 0.95,
                                      0.5])  #左下角座標 (0.03,0.4),右上角座標 (0.95,0.5)
        plt.title(sid, fontsize='x-large')
        ax2 = self.ui.figure.add_axes([0.03, 0.15, 0.95, 0.2
                                       ])  #左下角座標 (0.03,0.15),右上角座標 (0.95,0.2)

        mpf.candlestick2_ochl(ax,
                              df['Open'],
                              df['Close'],
                              df['High'],
                              df['Low'],
                              width=0.6,
                              colorup='r',
                              colordown='g',
                              alpha=0.75)

        ax.plot(sma_20, label='20MA')
        ax.plot(sma_60, label='60MA')
        ax.plot(sma_120, label='120MA')
        ax.plot(sma_240, label='240MA')

        mpf.volume_overlay(ax2,
                           df['Open'],
                           df['Close'],
                           df['Volume'],
                           colorup='r',
                           colordown='g',
                           width=0.5,
                           alpha=0.8)
        ax2.set_xticks(range(0, len(df.index), 10))
        ax2.set_xticklabels(df.index[::10], rotation=45)

        ax.legend(loc='best', shadow=True, fontsize='x-large')
        self.ui.canvas.draw()
Пример #11
0
def ohlc2cs(fname, seq_len, dataset_type, dimension):
    # python preprocess.py -m ohlc2cs -l 20 -i stockdatas/EWT_testing.csv -t testing
    print("Converting olhc to candlestick")
    symbol = fname.split('_')[0]
    symbol = symbol.split('/')[1]
    print(symbol)
    path = "{}".format(os.getcwd())
    # print(path)
    if not os.path.exists("{}/dataset/{}_{}/{}/{}".format(path, seq_len, dimension, symbol, dataset_type)):
        os.makedirs("{}/dataset/{}_{}/{}/{}".format(path,
                                                    seq_len, dimension, symbol, dataset_type))

    df = pd.read_csv(fname, parse_dates=True, index_col=0)
    df.fillna(0)
    plt.style.use('dark_background')
    df.reset_index(inplace=True)
    df['Date'] = df['Date'].map(mdates.date2num)
    for i in range(0, len(df)):
        # ohlc+volume
        useVolume = False
        if len(c) == int(seq_len):
            my_dpi = 96
            fig = plt.figure(figsize=(dimension / my_dpi,
                                      dimension / my_dpi), dpi=my_dpi)
            ax1 = fig.add_subplot(1, 1, 1)
            candlestick2_ochl(ax1, c['Open'], c['Close'], c['High'],
                              c['Low'], width=1,
                              colorup='#77d879', colordown='#db3f3f')
            ax1.grid(False)
            ax1.set_xticklabels([])
            ax1.set_yticklabels([])
            ax1.xaxis.set_visible(False)
            ax1.yaxis.set_visible(False)
            ax1.axis('off')

            # create the second axis for the volume bar-plot
            # Add a seconds axis for the volume overlay
            if useVolume:
                ax2 = ax1.twinx()
                # Plot the volume overlay
                bc = volume_overlay(ax2, c['Open'], c['Close'], c['Volume'],
                                    colorup='#77d879', colordown='#db3f3f', alpha=0.5, width=1)
                ax2.add_collection(bc)
                ax2.grid(False)
                ax2.set_xticklabels([])
                ax2.set_yticklabels([])
                ax2.xaxis.set_visible(False)
                ax2.yaxis.set_visible(False)
                ax2.axis('off')
            pngfile = 'dataset/{}_{}/{}/{}/{}-{}_combination.png'.format(
                seq_len, dimension, symbol, dataset_type, fname[11:-4], i)
            fig.savefig(pngfile,  pad_inches=0, transparent=False)
            plt.close(fig)
        # normal length - end

    print("Converting olhc to candlestik finished.")
Пример #12
0
    def candleplot(df, name, freq='5min'):
        df = df.resample(freq).last().dropna(axis=0)
        sma_5 = talib.SMA(df.close.values.astype('float'), 5)
        sma_20 = talib.SMA(df.close.values.astype('float'), 20)
        sma_60 = talib.SMA(df.close.values.astype('float'), 60)

        fig = plt.figure(figsize=(16, 12))
        ax = fig.add_axes([0, 0.2, 1, 0.5])
        ax2 = fig.add_axes([0, 0, 1, 0.2])

        candlestick2_ochl(ax,
                          df['open'].astype('float'),
                          df['close'].astype('float'),
                          df['high'].astype('float'),
                          df['low'].astype('float'),
                          width=0.5,
                          colorup='r',
                          colordown='g',
                          alpha=0.6)
        ax.set_xticks(range(0, len(df['day']), 48))
        ax.plot(sma_5, linewidth=0.5, label='MA 5')
        ax.plot(sma_20, linewidth=0.5, label='MA 20')
        ax.plot(sma_60, linewidth=0.5, label='MA 60')
        ax.legend(loc='upper left')
        plt.title(name)
        ax.grid(True)

        volume_overlay(ax2,
                       df['open'].astype('float'),
                       df['close'].astype('float'),
                       df['volume'].astype('float'),
                       colorup='r',
                       colordown='g',
                       width=0.5,
                       alpha=0.8)
        ax2.set_xticks(range(0, len(df['day']), 48))
        ax2.set_xticklabels(df['day'][::48], rotation=45)
        ax2.grid(True)
        plt.savefig('pics/' + name + '.png', bbox_inches='tight')
        plt.show(bbox_inches='tight')
Пример #13
0
def main(offset=0, gap_size=140):
    daily001 = main_session.query(models.DailyPro).filter(
        models.DailyPro.ts_code == '000001.SZ').order_by(
            models.DailyPro.trade_date.desc()).all()
    LAST_MARKET_DATE = daily001[offset].trade_date
    FIRST_MARKET_DATE = daily001[offset + gap_size].trade_date

    pro = ts.pro_api()
    res = pro.moneyflow_hsgt(start_date=FIRST_MARKET_DATE,
                             end_date=LAST_MARKET_DATE)

    df = DataFrame()
    for i in range(len(res))[::-1]:
        df.loc[i, 'trade_date'] = res.loc[i, 'trade_date']
        df.loc[i, 'north_money'] = res.loc[i, 'north_money']
        df.loc[i, 'open'] = 0.5
        df.loc[i, 'close'] = 1 if res.loc[i, 'north_money'] > 0 else 0.1

    fig = plt.figure(figsize=(17, 10))
    ax = fig.add_subplot(1, 1, 1)

    step = int(gap_size / 15)
    ax.set_xticks(range(0, len(df['trade_date']), step))
    ax.set_xticklabels(df['trade_date'][::step])
    plt.title('north_money')
    mpf.volume_overlay(ax,
                       df['open'],
                       df['close'],
                       df['north_money'],
                       colorup='r',
                       colordown='g',
                       width=0.5,
                       alpha=0.8)

    plt.savefig('../../buffer/north_money/{date}_north_money.png'.format(
        date=LAST_MARKET_DATE))

    pass
Пример #14
0
def add_volume(ax, open, close, vol):
    volume_params = dict(colorup='g', alpha=0.5, width=1)

    bc = volume_overlay(ax, open, close, vol, **volume_params)
    ax.add_collection(bc)

    idx = np.arange(vol.size)
    sma = tl.SMA(vol, 20)
    sma *= 2

    sma_params = dict(c='#0f07f9', ls='-', linewidth=1)
    ax.plot(idx, sma, **sma_params)

    ax.fill_between(idx, 0, sma, facecolor='#07f2f9', alpha=0.3)
Пример #15
0
def draw_candle(data):
    #get data as a pandas type 
    #data = ts.get_k_data('399300', index=True, start='2013-01-01', end='2017-06-31')
    print (data,type(data))
    sma_10 = talib.SMA(np.array(data['close']), 10)
    sma_30 = talib.SMA(np.array(data['close']), 30)
    sma_60 = talib.SMA(np.array(data['close']), 60)
    fig = plt.figure(figsize=(17, 10))
    plt.rcParams['axes.facecolor'] = 'azure' #background color
    ax = fig.add_axes([0,0.2,1,0.5])
    ax2 = fig.add_axes([0,0,1,0.2])
    mpf.candlestick2_ochl(ax, data['open'], data['close'], data['high'], data['low'], 
                          width=0.5, colorup='r', colordown='g', alpha=0.6)
    ax.set_xticks(range(0, len(data['date']), 10))
    ax.plot(sma_10, label='10 day')
    ax.plot(sma_30, label='30 day')
    ax.plot(sma_60, label='60 day')
    ax.legend(loc='upper left')
    ax.grid(True)
    mpf.volume_overlay(ax2, data['open'], data['close'], data['volume'], colorup='r', colordown='g', width=0.5, alpha=0.8)
    ax2.set_xticks(range(0, len(data['date']), 10))
    ax2.set_xticklabels(data['date'][::10], rotation=30)
    ax2.grid(True)
    plt.show()
Пример #16
0
def df_test2(number):
    plt.rcParams['font.sans-serif']=['Microsoft JhengHei'] #用来正常显示中文标签
    plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
    plt.style.use('ggplot')
    start = datetime.datetime(2020,1,1)
    df_2330 = pdr.DataReader('%s.TW'%number, 'yahoo', start=start)
    df_2330.index = df_2330.index.format(formatter=lambda x: x.strftime('%Y-%m-%d')) 
    #plt.style.use('ggplot')
    fig = plt.figure(figsize=(24, 15))

    #ax = fig.add_subplot(1, 1, 1)
    ax = fig.add_axes([0,0.2,1,0.5])
    ax2 = fig.add_axes([0,0,1,0.2])
    ax.set_xticks(range(0, len(df_2330.index), 100))
    ax.set_xticklabels(df_2330.index[::100])#10唯一循環
    mpf.candlestick2_ochl(ax, df_2330['Open'], df_2330['Close'], df_2330['High'],
    df_2330['Low'], width=0.6, colorup='r', colordown='g', alpha=0.75); 

    sma_10 = talib.SMA(np.array(df_2330['Close']), 10)
    sma_30 = talib.SMA(np.array(df_2330['Close']), 30)

    plt.rcParams['font.sans-serif']=['Microsoft JhengHei'] 
    ax.plot(sma_10, label='10日均線')
    ax.plot(sma_30, label='30日均線')

    mpf.volume_overlay(ax2, df_2330['Open'], df_2330['Close'], df_2330['Volume'], colorup='r', colordown='g', width=0.5, alpha=0.8)
    ax2.set_xticks(range(0, len(df_2330.index), 10))
    ax2.set_xticklabels(df_2330.index[::10])
    ax.legend()


    path_img = ".\static\image\\%s_test.jpg"%number#path_img 為 圖片路竟
    print(path_img)

    plt.savefig(path_img)
    plt.close()
def ohlc2cs(fname, dimension):
    # python preprocess.py -m ohlc2cs -l 20 -i stockdatas/EWT_testing.csv -t testing
    print("Converting olhc to candlestick")
    inout = fname
    df = pd.read_csv(fname, parse_dates=True, index_col=0)
    df.fillna(0)
    plt.style.use('dark_background')
    df.reset_index(inplace=True)
    df['Date'] = df['Date'].map(mdates.date2num)
    my_dpi = 96
    fig = plt.figure(figsize=(dimension / my_dpi,
                              dimension / my_dpi), dpi=my_dpi)
    ax1 = fig.add_subplot(1, 1, 1)
    candlestick2_ochl(ax1, df['Open'], df['Close'], df['High'],
                      df['Low'], width=1,
                      colorup='#77d879', colordown='#db3f3f')
    ax1.grid(False)
    ax1.set_xticklabels([])
    ax1.set_yticklabels([])
    ax1.xaxis.set_visible(False)
    ax1.yaxis.set_visible(False)
    ax1.axis('off')

    # create the second axis for the volume bar-plot
    # Add a seconds axis for the volume overlay
    ax2 = ax1.twinx()
    # Plot the volume overlay
    bc = volume_overlay(ax2, df['Open'], df['Close'], df['Volume'],
                        colorup='#77d879', colordown='#db3f3f', alpha=0.5, width=1)
    ax2.add_collection(bc)
    ax2.grid(False)
    ax2.set_xticklabels([])
    ax2.set_yticklabels([])
    ax2.xaxis.set_visible(False)
    ax2.yaxis.set_visible(False)
    ax2.axis('off')
    pngfile = "temp_class/{}.png".format(inout)
    fig.savefig(pngfile,  pad_inches=0, transparent=False)
    plt.close(fig)
    # normal length - end
    params = []
    params += ["-alpha", "off"]

    subprocess.check_call(["convert", pngfile] + params + [pngfile])
    print("Converting olhc to candlestik finished.")
Пример #18
0
    def draw_chlcv(self, plt):
        """draw_chlcv func

        Open, High, Low, Close, Volume の値を取り出し描画する

        Args:
            plt(module): 描画するためのモジュール

        Returns:
            module:                                 描画した情報
            matplotlib.figure.Figure:               描画した情報
            matplotlib.axes._subplots.AxesSubplot   描画した情報
        """
        data_df = copy.deepcopy(self.data_df)
        data_df = data_df.iloc[-self.graph_length:]
        data_df.columns = [
            "Open", "High", "Low", "Close", "Adj_Close", "Volume"
        ]
        data_df = data_df[["Open", "High", "Low", "Close", "Volume"]]

        fig = plt.figure(figsize=(18, 9))
        fig.subplots_adjust(left=0.045,
                            bottom=0.075,
                            right=0.95,
                            top=0.95,
                            wspace=0.15,
                            hspace=0.15)
        ax = plt.subplot(1, 1, 1)

        candlestick2_ohlc(ax,
                          data_df["Open"],
                          data_df["High"],
                          data_df["Low"],
                          data_df["Close"],
                          width=0.9,
                          colorup="grey",
                          colordown="black")

        place = ax.get_xticks()
        place[-2] = place[-2] - 1.0
        ax.set_xticks(place)

        labels_length = len(ax.get_xticks())

        def cal_index(x):
            """cal_index func

            新たなindexを計算

            Args:
                x(int): もともとのindex

            Returns:
                float: 新たなindex

            """
            return x / (labels_length - 1) * len(data_df)

        def my_round(f):
            """my_round func

            四捨五入関数

            Args:
                f(float): 四捨五入計算後の入力

            Returns:
                int: 四捨五入計算後の出力

            """
            return int(
                Decimal(str(f)).quantize(Decimal('0'), rounding=ROUND_HALF_UP))

        def get_date_index(i):
            """get_date_index

            index として使用する日付を取得

            Args:
                i(int); index

            Returns:
                str: 日付のindex

            """
            return data_df.index[i]

        new_labels = [data_df.index[0]] + \
                     [get_date_index(my_round(cal_index(x))) for x in range(1, labels_length - 1)] + \
                     [data_df.index[-1]]
        ax.set_xticklabels(new_labels, rotation=30)

        ax.set_xlim([-1, data_df.shape[0] + 1])
        ax.set_ylabel("Price")

        # 出来高を描写する範囲を指定
        bottom, top = ax.get_ylim()
        ax.set_ylim(bottom - (top - bottom) / 4, top)

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

        # 出来高チャートは下側25%に収める
        ax2.set_ylim([0, float(data_df["Volume"].max()) * 4])
        ax2.set_ylabel("Volume")

        return plt, fig, ax
Пример #19
0
ax = fig.add_axes([0, 0.2, 1, 0.5])
ax2 = fig.add_axes([0, 0, 1, 0.2])

mpf.candlestick2_ochl(ax,
                      data['open'],
                      data['close'],
                      data['high'],
                      data['low'],
                      width=0.5,
                      colorup='r',
                      colordown='g',
                      alpha=0.6)
ax.set_xticks(range(0, len(data['date']), 10))
ax.plot(sma_10, label='SMA 10')
ax.plot(sma_30, label='SMA 30')
ax.legend(loc='upper left')
ax.grid(True)

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

plt.show()
Пример #20
0
 def plot(self, widget):
     import mpl_finance as finance
     self.widget = widget
     finance.volume_overlay(widget, self.open, self.close, self.volume,
                            self.colorup, self.colordown, self.width)
Пример #21
0
def PlotStockData(Symbol, df_data, PlotType, TechIndicators, size_factor):

    fig = plt.figure()
    fig.canvas.set_window_title('Wanna join the Axis Cult?')
    fig.suptitle('Stock: {0} ({1} ~ {2})'.format(
        Symbol,
        df_data.index.min().strftime('%Y-%m-%d'),
        df_data.index.max().strftime('%Y-%m-%d')),
                 y=1,
                 fontsize=14)

    DefaultSize = fig.get_size_inches()
    fig.set_size_inches(
        (DefaultSize[0] * size_factor, DefaultSize[1] * size_factor))

    row_size = 3
    row_index = [0]
    for indicator in TechIndicators:
        IndicatorName = indicator[strName]
        if TechIndicatorPlotMode[IndicatorName][strPlotInAxPrice] == False:
            row_size += 1

    ax_price = plt.subplot2grid((row_size, 1), (0, 0), rowspan=2)
    row_index[0] = 2
    ax_volume = plt.subplot2grid((row_size, 1), (row_size - 1, 0),
                                 sharex=ax_price)

    # for using mpl_finance
    df_data = df_data.reset_index()
    df_data.columns = [strDate, strOpen, strHigh, strLow, strClose, strVolume]
    df_data[strDate] = df_data[strDate].map(mdates.date2num)

    DateSize = len(df_data[strDate])
    date_indices = numpy.arange(DateSize)

    df_data_Date = df_data[strDate]
    df_data[strDate] = date_indices

    def format_date(x, pos):
        this_index = numpy.clip(int(x + 0.5), 0, DateSize - 1)
        return mdates.num2date(df_data_Date[this_index]).strftime('%m/%d/%y')

    if PlotType == strCandle:
        lines, patches = mpl_finance.candlestick_ohlc(ax_price,
                                                      df_data.values,
                                                      width=1,
                                                      colorup='r',
                                                      colordown='g')
        for line, patch in zip(lines, patches):
            patch.set_edgecolor("k")
            patch.set_linewidth(0.72)
            patch.set_antialiased(False)
            line.set_color("k")
            line.set_zorder(0)  # make lines appear behind the patches
            line.set_visible(True)  # make them invisible
    elif PlotType == strBasic:
        df_data[strClose].plot(ax=ax_price, kind='line', color='g')

    mpl_finance.volume_overlay(ax_volume,
                               df_data[strOpen],
                               df_data[strClose],
                               df_data[strVolume],
                               colorup='r',
                               colordown='g',
                               width=1)

    def GetMondayList(df_data_Date):
        MondayList = []
        for index, value in enumerate(df_data_Date):
            if mdates.num2date(value).weekday() == 0:
                MondayList.append(index)

        return MondayList

    ax_volume.xaxis.set_major_locator(
        ticker.FixedLocator(GetMondayList(df_data_Date)))
    ax_volume.xaxis.set_minor_locator(ticker.MultipleLocator(1))

    ax_volume.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))

    plt.xlabel("Date")
    ax_price.set_ylabel("Price")
    ax_volume.set_ylabel('Volume')

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

    for indicator in TechIndicators:
        TechIndicatorName = indicator[strName]
        TechIndicatorFuncDict[TechIndicatorName][strFuncName](
            indicator[strParam], df_data, ax_price, row_size, row_index)

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

    ax_price.grid(color='grey', linestyle='--', linewidth=0.5)
    ax_volume.grid(color='grey', linestyle='--', linewidth=0.5)

    plt.tight_layout()
    return fig
Пример #22
0
def plotCandlestickChart(StockID, ShowDays):

    l = crawlerStockServes_TW.get_data(StockID)
    col = ["Date", "Name", "Open", "High", "Low", "Close", "Volume", "PER"]
    df = pd.DataFrame(l, columns=col)
    df.set_index("Date", inplace=True)
    print(df[-20:])
    inputs = {
        'open': df['Open'].values,
        'high': df['High'].values,
        'low': df['Low'].values,
        'close': df['Close'].values,
        'volume': df['Volume'].values
    }
    df = df[ShowDays:]

    #df.index = df.index.format(formatter=lambda x: x.strftime('%Y-%m-%d'))

    sma_10 = talib.SMA(inputs["close"], timeperiod=10)
    sma_20 = talib.SMA(inputs["close"], timeperiod=20)
    upper, middle, lower = talib.BBANDS(inputs["close"], 20, 2, 2)

    sma_10 = sma_10[ShowDays:]
    sma_20 = sma_20[ShowDays:]
    upper = upper[ShowDays:]
    lower = lower[ShowDays:]

    fig = plt.figure(figsize=(16, 10))

    ax = fig.add_axes([0.05, 0.4, 0.9, 0.5])
    ax2 = fig.add_axes([0.05, 0.2, 0.9, 0.2])
    ax.set_xticks(range(0, len(df.index), 10))
    ax.set_xticklabels(df.index[::10])
    mpf.candlestick2_ochl(ax,
                          df['Open'],
                          df['Close'],
                          df['High'],
                          df['Low'],
                          width=0.6,
                          colorup='r',
                          colordown='g',
                          alpha=0.75)

    #plt.rcParams['font.sans-serif']=['Microsoft JhengHei']
    ax.plot(sma_10, label='10MA')
    ax.plot(sma_20, label='20MA')
    ax.plot(upper, label='BBU')
    ax.plot(lower, label='BBL')
    ax.grid(True, which='both')
    ax.legend()
    mpf.volume_overlay(ax2,
                       df['Open'],
                       df['Close'],
                       df['Volume'],
                       colorup='r',
                       colordown='g',
                       width=0.5,
                       alpha=0.8)
    ax2.set_xticks(range(0, len(df.index), 10))
    ax2.set_xticklabels(df.index[::10])

    ax2.grid(True, which='both')
    return plt
Пример #23
0
def plot_stock_line(api,
                    code,
                    name,
                    table_name,
                    current,
                    start='2017-10-01',
                    save=False):
    title = '{} {} {} {}'.format(current, code, name, table_name)
    title = title.replace('*', '_')

    if os.path.exists(title + '.png'):
        return

    if code is None and name is not None:
        code = base_info[base_info['name'] == name]['code'].values[0]

    df = None
    for _ in range(4):

        try:
            df = ts.bar(code, conn=api, start_date=start)

        except Exception as e:
            logger.info(e)
            ts.close_apis(api)
            time.sleep(random.random() * 30)
            api = ts.get_apis()

        else:
            break

    if df is None:
        return

    df = df.sort_index()

    if name is None:
        name = base_info[base_info['code'] == code]['name'].values[0]

    df = df.reset_index()
    df['datetime'] = df['datetime'].dt.strftime('%Y-%m-%d')
    sma5 = talib.SMA(df['close'].values, 5)
    sma20 = talib.SMA(df['close'].values, 10)
    # ax.set_xticks(range(0,len(df),20))
    # # ax.set_xticklabels(df['date'][::5])
    # ax.set_xticklabels(df['datetime'][::20])
    fig = plt.figure(figsize=(10, 8))
    # fig,(ax,ax2)=plt.subplots(2,1,sharex=True,figsize=(16,10))
    ax = fig.add_axes([0, 0.3, 1, 0.50])
    ax2 = fig.add_axes([0, 0.1, 1, 0.20])

    candlestick2_ochl(ax,
                      df['open'],
                      df['close'],
                      df['high'],
                      df['low'],
                      width=1,
                      colorup='r',
                      colordown='g',
                      alpha=0.6)
    ax.grid(True)
    ax.set_title(title)
    ax.plot(sma5, label='MA5')
    ax.legend()
    ax.plot(sma20, label='MA20')
    ax.legend(loc=2)
    ax.grid(True)
    # df['vol'].plot(kind='bar')
    volume_overlay(ax2,
                   df['open'],
                   df['close'],
                   df['vol'],
                   width=1,
                   alpha=0.8,
                   colordown='g',
                   colorup='r')
    ax2.set_xticks(range(0, len(df), 5))
    # ax.set_xticklabels(df['date'][::5])
    ax2.set_xticklabels(df['datetime'][::5])
    plt.setp(ax2.get_xticklabels(), rotation=30, horizontalalignment='right')
    ax2.grid(True)
    plt.subplots_adjust(hspace=0.3)

    if save:
        # path = os.path.join(os.path.dirname(__file__),'data',today)
        fig.savefig(title + '.png')
    else:
        plt.show()

    plt.close()
    ax1.plot(Select['sma_short'], label='MA short')
    ax1.plot(Select['sma_long'], label='MA long')
    ax1.legend()
    ax1.autoscale()
    ax1.set_ylim((Select['Close'].min() * 0.9, Select['Close'].max() * 1.1))

    # b.) KD line chart.
    ax2.plot(Select['K'], label='K')
    ax2.plot(Select['D'], label='D')
    ax2.legend()

    # c.) Volume bar chart.
    mpf.volume_overlay(ax3,
                       Select['Open'],
                       Select['Close'],
                       Select['Volume %s' % GD.SYMBOL],
                       colorup='r',
                       colordown='g',
                       width=0.5,
                       alpha=0.8)

    ax3.set_xticks(range(0, len(Select.index), 20))
    ax3.set_xticklabels(Select.index[::20])

    fig.savefig("./fig/%s_charts.png" % GD.SYMBOL)
    plt.clf()
    plt.close()
    print(data_train.shape)
    print(data_test.shape)
    print(train_norm.shape)
    print(test_norm.shape)
Пример #25
0
def plot_stock_line(api,code, name, table_name, current, start='2017-10-01', save=False):
    title = '{} {} {} {}'.format(current, code, name, table_name)
    title = title.replace('*', '_')


    if os.path.exists(title + '.png'):
        return



    if code is None and name is not None:
        code = base_info[base_info['name'] == name]['code'].values[0]

    df = None
    for _ in range(4):

        try:
            df = ts.bar(code, conn=api, start_date=start)

        except Exception as e:
            logger.info(e)
            ts.close_apis(api)
            time.sleep(random.random() * 30)
            api = ts.get_apis()

        else:
            break

    if df is None:
        return

    df = df.sort_index()

    if name is None:
        name = base_info[base_info['code'] == code]['name'].values[0]

    df = df.reset_index()
    df['datetime'] = df['datetime'].dt.strftime('%Y-%m-%d')
    sma5 = talib.SMA(df['close'].values, 5)
    sma20 = talib.SMA(df['close'].values, 10)
    # ax.set_xticks(range(0,len(df),20))
    # # ax.set_xticklabels(df['date'][::5])
    # ax.set_xticklabels(df['datetime'][::20])
    fig = plt.figure(figsize=(10, 8))
    # fig,(ax,ax2)=plt.subplots(2,1,sharex=True,figsize=(16,10))
    ax = fig.add_axes([0, 0.3, 1, 0.50])
    ax2 = fig.add_axes([0, 0.1, 1, 0.20])

    candlestick2_ochl(ax, df['open'], df['close'], df['high'], df['low'], width=1, colorup='r', colordown='g',
                      alpha=0.6)
    ax.grid(True)
    ax.set_title(title)
    ax.plot(sma5, label='MA5')
    ax.legend()
    ax.plot(sma20, label='MA20')
    ax.legend(loc=2)
    ax.grid(True)
    # df['vol'].plot(kind='bar')
    volume_overlay(ax2, df['open'], df['close'], df['vol'], width=1, alpha=0.8, colordown='g', colorup='r')
    ax2.set_xticks(range(0, len(df), 5))
    # ax.set_xticklabels(df['date'][::5])
    ax2.set_xticklabels(df['datetime'][::5])
    plt.setp(ax2.get_xticklabels(), rotation=30, horizontalalignment='right')
    ax2.grid(True)
    plt.subplots_adjust(hspace=0.3)

    if save:
        # path = os.path.join(os.path.dirname(__file__),'data',today)
        fig.savefig(title + '.png')
    else:
        plt.show()

    plt.close()
Пример #26
0
ax = fig.add_axes([0, 0.2, 1, 0.5])
ax2 = fig.add_axes([0, 0, 1, 0.2])

ax.set_xticks(range(0, len(df_1109.index), 10))
ax.set_xticklabels(df_1109.index[::10])
mpf.candlestick2_ochl(ax,
                      df_1109['Open'],
                      df_1109['Close'],
                      df_1109['High'],
                      df_1109['Low'],
                      width=0.6,
                      colorup='r',
                      colordown='g',
                      alpha=0.75)
plt.rcParams['font.sans-serif'] = ['Microsoft JhengHei']
ax.plot(sma_10, label='10日均線')
ax.plot(sma_30, label='30日均線')

mpf.volume_overlay(ax2,
                   df_1109['Open'],
                   df_1109['Close'],
                   df_1109['Volume'],
                   colorup='r',
                   colordown='g',
                   width=0.5,
                   alpha=0.8)
ax2.set_xticks(range(0, len(df_1109.index), 10))
ax2.set_xticklabels(df_1109.index[::10])

ax.legend()
Пример #27
0
def draw_klines(df: pd.DataFrame,
                main_chart_lines=None,
                sub_chart_lines=None,
                *,
                annotate=False,
                to_file=None):
    """
    基础画图方法
    :param df: dataframe->基础需包含['datetime', 'open', 'close', 'high', 'low', 'volume'],
                可选trades: List[Dict],若有则会添加交易标识Dict中包含字段['price', 'size', 'direction']
    :param extra_lines: 添加想要的线
    :param to_file:  生成图片,默认None为不生成
    :return:
    """
    import matplotlib.pyplot as plt
    import mpl_finance as mpf
    from matplotlib import ticker
    import matplotlib.dates as mdates

    columns = ['datetime', 'open', 'close', 'high', 'low', 'volume']
    if not set(df.columns).issuperset(columns):
        raise Exception(f'请包含{columns}字段')

    data = df.loc[:, columns]

    data_mat = data.values.T

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

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

    data_len = len(data_mat[2])

    fig, [ax1, ax2, ax3] = plt.subplots(3, 1, sharex=True)
    fig.set_figheight(300 / 72)
    fig.set_figwidth(1200 / 72)
    ax1.set_position([0.1, 0.4, 0.8, 0.55])
    ax2.set_position([0.1, 0.2, 0.8, 0.15])
    ax3.set_position([0.1, 0.05, 0.8, 0.1])

    ax1.set_title('KLine', fontsize='large', fontweight='bold')
    ax2.set_title('MACD')
    ax3.set_title('Volume')
    mpf.candlestick2_ochl(ax1,
                          data_mat[1],
                          data_mat[2],
                          data_mat[3],
                          data_mat[4],
                          colordown=DEFALUT_CHART_COLOR['barDown'],
                          colorup=DEFALUT_CHART_COLOR['barUp'],
                          width=min(120 / data_len, 1),
                          alpha=1)
    mpf.volume_overlay(ax3,
                       data_mat[1],
                       data_mat[2],
                       data_mat[5],
                       colordown=DEFALUT_CHART_COLOR['barDown'],
                       colorup=DEFALUT_CHART_COLOR['barUp'],
                       width=min(120 / data_len, 1),
                       alpha=1)
    ax1.grid(True)
    ax2.grid(True)
    ax3.grid(True)
    ax1.xaxis.set_major_formatter(ticker.FuncFormatter(mydate))
    ax1.xaxis.set_major_locator(mdates.HourLocator())
    ax1.xaxis.set_major_locator(
        mdates.MinuteLocator(byminute=[0, 15, 30, 45], interval=1))
    ax1.xaxis.set_major_locator(ticker.MaxNLocator(8))

    if main_chart_lines:
        for l in main_chart_lines:
            ax1.add_line(l)
    else:
        import talib
        l = range(data_len)
        for p in [5, 10, 30, 60]:
            ma_line = mpf.Line2D(l,
                                 talib.MA(data_mat[2].astype(float), p),
                                 color=DEFALUT_CHART_COLOR[f'ma{p}'],
                                 linewidth=120 / data_len)
            ax1.add_line(ma_line)

    if sub_chart_lines:
        for l in main_chart_lines:
            ax2.add_line(l)
    else:
        import talib
        dif, dea, macd = talib.MACDEXT(data_mat[2].astype(float),
                                       fastperiod=12,
                                       fastmatype=1,
                                       slowperiod=26,
                                       slowmatype=1,
                                       signalperiod=9,
                                       signalmatype=1)
        macd = macd * 2
        l = range(data_len)
        dif_line = mpf.Line2D(l,
                              dif,
                              color=DEFALUT_CHART_COLOR['dif'],
                              linewidth=120 / data_len)
        dea_line = mpf.Line2D(l,
                              dea,
                              color=DEFALUT_CHART_COLOR['dea'],
                              linewidth=120 / data_len)
        ax2.add_line(dif_line)
        ax2.add_line(dea_line)
        mpf.candlestick2_ochl(ax2, [0] * len(macd),
                              macd,
                              np.where(macd >= 0, macd, 0),
                              np.where(macd < 0, macd, 0),
                              colordown=DEFALUT_CHART_COLOR['barDown'],
                              colorup=DEFALUT_CHART_COLOR['barUp'],
                              width=120 / data_len,
                              alpha=0.7)

    if 'trades' in df.columns:
        trades_long_x = []
        trades_long_y = []
        trades_long_s = []
        trades_short_x = []
        trades_short_y = []
        trades_short_s = []

        size_ratio = 100 * 120 / data_len
        for i, (_, tl) in enumerate(df.trades.iteritems()):
            if isinstance(tl, Iterable):
                long_n = 0
                short_n = 0
                total_long = 0
                total_short = 0
                for t in tl:
                    if t['direction'] == 'long':
                        trades_long_x.append(i)
                        trades_long_y.append(t['price'])
                        trades_long_s.append(t['size'] * size_ratio)
                        long_n += t['size']
                        total_long += t['price']
                    elif t['direction'] == 'short':
                        trades_short_x.append(i)
                        trades_short_y.append(t['price'])
                        trades_short_s.append(t['size'] * size_ratio)
                        short_n += t['size']
                        total_short += t['price']
                else:
                    if annotate and long_n:
                        avg_long_price = total_long / long_n
                        ax1.annotate(f'+{long_n}@{avg_long_price:.1f}',
                                     xy=(i, avg_long_price),
                                     xytext=(i + 0.1, avg_long_price - 0.1))
                    if annotate and short_n:
                        avg_short_price = total_short / short_n
                        ax1.annotate(f'-{short_n}@{avg_short_price:.1f}',
                                     xy=(i, avg_short_price),
                                     xytext=(i + 0.1, avg_short_price + 0.1))
        else:
            ax1.scatter(trades_long_x,
                        trades_long_y,
                        s=trades_long_s,
                        color=DEFALUT_CHART_COLOR['longMark'],
                        marker='^',
                        alpha=0.8,
                        linewidths=0,
                        zorder=2)
            ax1.scatter(trades_short_x,
                        trades_short_y,
                        s=trades_short_s,
                        color='',
                        edgecolors=DEFALUT_CHART_COLOR['shortMark'],
                        marker='v',
                        alpha=0.8,
                        linewidths=1,
                        zorder=2)

    if to_file:
        try:
            fig.savefig(to_file,
                        dpi=DEFALUT_CHART_PARAMS['dpi'],
                        figsize=(120, 30))
        except Exception as e:
            print('errSaveFig:', e)

    return fig
Пример #28
0
                          df['Low'],
                          width=0.6,
                          alpha=0.75,
                          colorup='r',
                          colordown='g')

    ax.set_xticks(range(0, len(df.index), 100))
    ax.set_xticklabels(df.index[::100])
    ax.set_xlim(0, len(df.index))
    ax.axes.xaxis.set_ticks([])

    ax.plot(sma20.index, sma20, label='ma20')
    ax.set_title('stock')
    ax.set_ylabel('price')
    ax.legend(loc=2)

    # 量圖---------------------------------------------------------------------
    mpf.volume_overlay(ax2,
                       df['Open'],
                       df['Close'],
                       df['Volume'],
                       width=0.6,
                       colorup='r',
                       colordown='g')

    ax2.set_xticks(range(0, len(df.index), 100))
    ax2.set_xticklabels(df.index[::100])
    ax2.set_xlim(0, len(df.index))

#ax2.set_yticks(range(0, max(df['Volume']), max(df['Volume'])/4))
Пример #29
0
def test_ohlc2cs(df, seq_len, dimension, add_v, stock_name):
    # python preprocess.py -m ohlc2cs -l 20 -i stockdatas/EWT_testing.csv -t testing
    print("Converting test olhc to candlestick")

    df = df
    plt.style.use('dark_background')
    df.reset_index(inplace=True)

    figs = np.zeros((1, dimension, dimension, 3))
    labels = []
    # ohlc+volume
    c = df.loc[len(df) - int(seq_len):len(df) - 1, :]

    if len(c) == int(seq_len):
        my_dpi = 100
        fig = plt.figure(figsize=(dimension / my_dpi, dimension / my_dpi),
                         dpi=my_dpi)
        ax1 = fig.add_subplot(1, 1, 1)
        candlestick2_ochl(ax1,
                          c['Open'],
                          c['Close'],
                          c['High'],
                          c['Low'],
                          width=0.5,
                          colorup='#db3f3f',
                          colordown='#77d879')

        ax1.grid(False)

        ax1.set_xticklabels([])
        ax1.set_yticklabels([])
        ax1.xaxis.set_visible(False)
        ax1.yaxis.set_visible(False)
        ax1.axis('off')

        if add_v == 1:
            ax2 = fig.add_subplot(2, 1, 1)
            volume_overlay(ax2,
                           opens=c['Open'],
                           closes=c['Close'],
                           volumes=c['Volume'],
                           colorup='#db3f3f',
                           colordown='#77d879',
                           width=0.5)

            ax2.grid(False)
            ax2.set_xticklabels([])
            ax2.set_yticklabels([])
            ax2.xaxis.set_visible(False)
            ax2.yaxis.set_visible(False)
            ax2.axis('off')

        # create the second axis for the volume bar-plot
        # Add a seconds axis for the volume overlay

        fig.canvas.draw()

        fig_np = np.array(fig.canvas.renderer._renderer)
        figs[0] = fig_np[:, :, :3]
        fig.savefig(stock_name + '_sample.png')
        plt.close(fig)
        # normal length - end

    print("Converting olhc to candlestik finished.")
    return figs
Пример #30
0
def ohlc2cs(df, seq_len, dimension, add_v):
    # python preprocess.py -m ohlc2cs -l 20 -i stockdatas/EWT_testing.csv -t testing
    print("Converting olhc to candlestick")

    df = df
    plt.style.use('dark_background')
    df.reset_index(inplace=True)

    figs = np.zeros((len(df) - 1, dimension, dimension, 3))
    labels = []
    for i in range(0, len(df) - 1):
        # ohlc+volume
        c = df.loc[i:i + int(seq_len) - 1, :]
        c_ = df.loc[i:i + int(seq_len), :]
        if len(c) == int(seq_len):
            my_dpi = 100
            fig = plt.figure(figsize=(dimension / my_dpi, dimension / my_dpi),
                             dpi=my_dpi)
            ax1 = fig.add_subplot(1, 1, 1)
            candlestick2_ochl(ax1,
                              c['Open'],
                              c['Close'],
                              c['High'],
                              c['Low'],
                              width=0.5,
                              colorup='#db3f3f',
                              colordown='#77d879')

            ax1.grid(False)

            ax1.set_xticklabels([])
            ax1.set_yticklabels([])
            ax1.xaxis.set_visible(False)
            ax1.yaxis.set_visible(False)
            ax1.axis('off')

            if add_v == 1:
                ax2 = fig.add_subplot(2, 1, 1)
                volume_overlay(ax2,
                               opens=c['Open'],
                               closes=c['Close'],
                               volumes=c['Volume'],
                               colorup='#db3f3f',
                               colordown='#77d879',
                               width=0.5)

                ax2.grid(False)
                ax2.set_xticklabels([])
                ax2.set_yticklabels([])
                ax2.xaxis.set_visible(False)
                ax2.yaxis.set_visible(False)
                ax2.axis('off')

            # create the second axis for the volume bar-plot
            # Add a seconds axis for the volume overlay

        starting = c_["Close"].iloc[-2]
        endvalue = c_["Close"].iloc[-1]
        if endvalue > starting:
            label = 1
        else:
            label = 0
        labels.append(label)

        fig.canvas.draw()

        fig_np = np.array(fig.canvas.renderer._renderer)
        figs[i] = fig_np[:, :, :3]
        #fig.savefig('./sample/sample_'+str(i)+'.png')
        plt.close(fig)
        # normal length - end

    print("Converting olhc to candlestik finished.")
    return figs, labels
Пример #31
0
 def plot(self, widget):
     import mpl_finance as finance
     self.widget = widget
     finance.volume_overlay(widget, self.open, self.close, self.volume,
                            self.colorup, self.colordown, self.width)
Пример #32
0
                   width=0.5,
                   colorup='r',
                   colordown='g',
                   alpha=0.6)
 ax.grid(True)
 ax.set_title(title)
 ax.plot(sma5, label='MA5')
 ax.legend()
 ax.plot(sma20, label='MA20')
 ax.legend(loc=2)
 ax.grid(True)
 # df['vol'].plot(kind='bar')
 volume_overlay(ax2,
                df['open'],
                df['close'],
                df['vol'],
                width=0.5,
                alpha=0.8,
                colordown='g',
                colorup='r')
 ax2.set_xticks(range(0, len(df), 1))
 # ax.set_xticklabels(df['date'][::5])
 ax2.set_xticklabels(df['datetime'][::1])
 plt.setp(ax2.get_xticklabels(), rotation=30, horizontalalignment='right')
 ax2.grid(True)
 # plt.subplots_adjust(hspace=0)
 if save:
     # path = os.path.join(os.path.dirname(__file__),'data',today)
     fig.savefig(title + '.png')
 else:
     plt.show()
 plt.close()