Ejemplo n.º 1
0
    def __init__(self, platform, symbol, time_frame):

        self.__platform = platform
        self.__symbol = symbol
        self.__time_frame = time_frame
        self.__market = MARKET(self.__platform, self.__symbol,
                               self.__time_frame)

        # pull some data
        self.__indicators = INDICATORS(self.__platform, self.__symbol,
                                       self.__time_frame)
        self.__kline = platform.get_kline(self.__time_frame)
        self.__kline.reverse()

        # format it in pandas
        try:  # dataframe有7列的情况
            self.__df = pd.DataFrame(self.__kline,
                                     columns=[
                                         'time', 'open', 'high', 'low',
                                         'close', 'volume', 'currency_volume'
                                     ])
            self.__df = self.__df.astype({
                'time': 'datetime64[ns]',
                'open': 'float64',
                'close': 'float64',
                'high': 'float64',
                'low': 'float64',
                'volume': 'float64',
                'currency_volume': 'float64'
            })
        except:  # dataframe只有6列的情况,如okex的现货k线数据
            self.__df = pd.DataFrame(
                self.__kline,
                columns=['time', 'open', 'high', 'low', 'close', 'volume'])
            self.__df = self.__df.astype({
                'time': 'datetime64[ns]',
                'open': 'float64',
                'close': 'float64',
                'high': 'float64',
                'low': 'float64',
                'volume': 'float64'
            })

        # create three plot 创建三层图纸,第一层画k线,第二层画成交量,第三层画一些适宜于副图显示的指标
        fplt.foreground = '#FFFFFF'  # 前景色
        fplt.background = '#333333'  # 背景色
        fplt.odd_plot_background = '#333333'  # 第二层图纸的背景色
        fplt.cross_hair_color = "#FFFFFF"  # 准星的颜色
        self.__ax, self.__ax2, self.__ax3 = fplt.create_plot(symbol, rows=3)

        # plot candle sticks
        candles = self.__df[['time', 'open', 'close', 'high', 'low']]
        fplt.candlestick_ochl(candles, ax=self.__ax)

        # overlay volume on the plot
        volumes = self.__df[['time', 'open', 'close', 'volume']]
        fplt.volume_ocv(volumes, ax=self.__ax2)
        fplt.add_legend("VOLUME", self.__ax2)  # 增加"VOLUME"图例
Ejemplo n.º 2
0
def plot_kline(kline):
    """
    回测结束时绘制k线图
    :param kline: 回测时传入指定的k线数据
    :return:
    """
    kline = kline
    # kline.reverse()

    # format it in pandas
    try:  # dataframe有7列的情况
        df = pd.DataFrame(kline,
                          columns=[
                              'time', 'open', 'high', 'low', 'close', 'volume',
                              'currency_volume'
                          ])
        df = df.astype({
            'time': 'datetime64[ns]',
            'open': 'float64',
            'close': 'float64',
            'high': 'float64',
            'low': 'float64',
            'volume': 'float64',
            'currency_volume': 'float64'
        })
    except:  # dataframe只有6列的情况,如okex的现货k线数据
        df = pd.DataFrame(
            kline, columns=['time', 'open', 'high', 'low', 'close', 'volume'])
        df = df.astype({
            'time': 'datetime64[ns]',
            'open': 'float64',
            'close': 'float64',
            'high': 'float64',
            'low': 'float64',
            'volume': 'float64'
        })

    # create three plot 创建三层图纸,第一层画k线,第二层画成交量,第三层画一些适宜于副图显示的指标
    fplt.foreground = '#FFFFFF'  # 前景色
    fplt.background = '#333333'  # 背景色
    fplt.odd_plot_background = '#333333'  # 第二层图纸的背景色
    fplt.cross_hair_color = "#FFFFFF"  # 准星的颜色
    ax, ax2 = fplt.create_plot("KLINE", rows=2)

    # plot candle sticks
    candles = df[['time', 'open', 'close', 'high', 'low']]
    fplt.candlestick_ochl(candles, ax=ax)

    # overlay volume on the plot
    volumes = df[['time', 'open', 'close', 'volume']]
    fplt.volume_ocv(volumes, ax=ax2)
    fplt.add_legend("VOLUME", ax2)  # 增加"VOLUME"图例
    fplt.show()
Ejemplo n.º 3
0
def update():
    df = delta_bars.df
    # Меняем индекс и делаем его типом datetime
    df = df.set_index(
        pd.to_datetime(df['date_time'], format='%Y-%m-%d %H:%M:%S'))
    df = df.drop(
        'date_time', 1
    )  # Удаляем колонку с датой и временем, т.к. дата у нас теперь в индексе

    play_sound(df.tail(2))  # Вызов функции звукового сигнала

    print(df)

    # pick columns for our three data sources: candlesticks and TD
    candlesticks = df['open close high low'.split()]
    deltabarsec = df['open close sec'.split()]
    delta = df['open close delta'.split()]
    maxvolcluster = df['max_vol']
    if not plots:
        # first time we create the plots
        global ax
        plots.append(fplt.candlestick_ochl(candlesticks, candle_width=0.8))
        plots.append(fplt.volume_ocv(deltabarsec, ax=ax2))
        fplt.add_legend('Время формирования бара', ax=ax2)
        plots.append(
            fplt.volume_ocv(delta, colorfunc=fplt.strength_colorfilter,
                            ax=ax3))
        fplt.add_legend('Дельта', ax=ax3)
        plots.append(
            fplt.plot(maxvolcluster,
                      legend='Max volume',
                      style='o',
                      color='#00f'))
    else:
        # every time after we just update the data sources on each plot
        plots[0].update_data(candlesticks)
        plots[1].update_data(deltabarsec)
        plots[2].update_data(delta)
        plots[3].update_data(maxvolcluster)
Ejemplo n.º 4
0
 def __init__(self, *args, **kwargs):
     super(MainWindow, self).__init__(*args, **kwargs)
     uic.loadUi('chart.ui', self)
     self.initConnections()
     pg.setConfigOptions(foreground=finplot.foreground, background=finplot.background)
     fp = finplot.FinWindow(title="chart")
     self.ax = finplot.create_plot_widget(fp, init_zoom_periods=100)
     fp.ci.addItem(self.ax, row=0, col=0)
     fp.show_maximized = True
     self.plotWidget.setMaximumHeight(0)
     self.plotWidget.axs = [self.ax]  # finplot requires this property
     self.verticalLayout.addWidget(fp)
     self.dayDateEdit.setDate(datetime.date.today())
     self.priceLine = None
     self.stopPriceLine = None
     self.candleItems = None
     self.df = None
     self.filename = None
     self.isFileFirstOpen = True
     self.hoverLabel = finplot.add_legend('', ax=self.ax)
     finplot.set_time_inspector(self.update_legend_text, ax=self.ax, when='hover')
     finplot.display_timezone = gettz('America/New_York')
Ejemplo n.º 5
0
fplt.set_y_scale(ax=ax1, yscale='log')

fplt.plot(btc.Close, color='#000', legend='Log price', ax=ax1)
btc['ma200'] = btc.Close.rolling(200).mean()
btc['ma50'] = btc.Close.rolling(50).mean()
fplt.plot(btc.ma200, legend='MA200', ax=ax1)
fplt.plot(btc.ma50, legend='MA50', ax=ax1)
btc['one'] = 1
fplt.volume_ocv(btc[['ma200', 'ma50', 'one']],
                candle_width=1,
                ax=ax1.overlay(scale=0.02))

daily_ret = btc.Close.pct_change() * 100
fplt.plot(daily_ret, width=3, color='#000', legend='Daily returns %', ax=ax2)

fplt.add_legend('Daily % returns histogram', ax=ax3)
fplt.hist(daily_ret, bins=60, ax=ax3)

fplt.add_legend('Yearly returns in %', ax=ax4)
fplt.bar(btc.Close.resample('Y').last().pct_change().dropna() * 100, ax=ax4)

# calculate monthly returns, display as a 4x3 heatmap
months = btc['Adj Close'].resample(
    'M').last().pct_change().dropna().to_frame() * 100
months.index = mnames = months.index.month_name().to_list()
mnames = mnames[mnames.index('January'):][:12]
mrets = [months.loc[mname].mean()[0] for mname in mnames]
hmap = pd.DataFrame(columns=[2, 1, 0], data=np.array(mrets).reshape((3, 4)).T)
hmap = hmap.reset_index(
)  # use the range index as X-coordinates (if no DateTimeIndex is found, the first column is used as X)
colmap = fplt.ColorMap(
Ejemplo n.º 6
0
            plots.append(fplt.plot(middleband, legend="MIDDLEBAND"))
            plots.append(fplt.plot(lowerband, legend="LOWERBAND"))
        else:
            # every time after we just update the data sources on each plot
            plots[0].update_data(candlesticks)
            plots[1].update_data(volumes)
            plots[2].update_data(upperband)
            plots[3].update_data(middleband)
            plots[4].update_data(lowerband)


if __name__ == "__main__":
    try:
        kline = Kline()
        plots = []
        fplt.foreground = '#FFFFFF'  # 前景色
        fplt.background = '#333333'  # 背景色
        fplt.odd_plot_background = '#333333'  # 第二层图纸的背景色
        fplt.cross_hair_color = "#FFFFFF"  # 准星的颜色
        ax, ax2 = fplt.create_plot('Realtime kline',
                                   init_zoom_periods=100,
                                   maximize=False,
                                   rows=2)
        fplt.add_legend("VOLUME", ax2)  # 增加"VOLUME"图例
        kline.update()
        fplt.timer_callback(
            kline.update,
            5.0)  # update (using synchronous rest call) every N seconds
        fplt.show()
    except:
        logger.error()
Ejemplo n.º 7
0
signal = macd.ewm(span=9).mean()
df['macd_diff'] = macd - signal
fplt.volume_ocv(df[['Date', 'Open', 'Close', 'macd_diff']],
                ax=ax2,
                colorfunc=fplt.strength_colorfilter)
fplt.plot(macd, ax=ax2, legend='MACD')
fplt.plot(signal, ax=ax2, legend='Signal')

# change to b/w coloring templates for next plots
fplt.candle_bull_color = fplt.candle_bear_color = '#000'
fplt.volume_bull_color = fplt.volume_bear_color = '#333'
fplt.candle_bull_body_color = fplt.volume_bull_body_color = '#fff'

# plot price and volume
fplt.candlestick_ochl(df[['Date', 'Open', 'Close', 'High', 'Low']], ax=ax)
hover_label = fplt.add_legend('', ax=ax)
axo = ax.overlay()
fplt.volume_ocv(df[['Date', 'Open', 'Close', 'Volume']], ax=axo)
fplt.plot(df.Volume.ewm(span=24).mean(), ax=axo, color=1)

#######################################################
## update crosshair and legend when moving the mouse ##


def update_legend_text(x, y):
    row = df.loc[df.Date == x]
    # format html with the candle and set legend
    fmt = '<span style="color:#%s">%%.2f</span>' % ('0b0' if (
        row.Open < row.Close).all() else 'a00')
    rawtxt = '<span style="font-size:13px">%%s %%s</span> &nbsp; O%s C%s H%s L%s' % (
        fmt, fmt, fmt, fmt)
Ejemplo n.º 8
0
def plt_chart(fa_info, save_chart=False, interactive=False):
    global df
    global symbol
    global file_png
    # load data and convert date

    symbol, sector, industry, website, num_emp, profile = fa_info

    return_result = (None, None)
    end_t = int(time())
    start_t = end_t - NUM_OF_MONTHS * 30 * 24 * 60 * 60  # twelve months
    interval = '1d'
    url = 'https://query1.finance.yahoo.com/v7/finance/download/%s?period1=%s&period2=%s&interval=%s&events=history' % (
        symbol, start_t, end_t, interval)

    try:
        r = requests.get(url)
        df = pd.read_csv(StringIO(r.text))
        if df.empty:
            print(f"[Warn] symbol {symbol} has no data")
            return return_result

        if df.shape[0] < MA_SLOW:
            print(
                f"[Warn] symbol {symbol} has fewer than {MA_SLOW} data points")
            return return_result

    except Exception as ex:
        print(
            f"[Error] failed to download quote from Yahoo finance for {symbol}"
        )
        return return_result

    last_date = str(df.tail(1)['Date'].values[0]).split("T")[0]

    df['Date'] = pd.to_datetime(df['Date']).astype(
        'int64')  # use finplot's internal representation, which is ns

    log_msg = ""
    if sector:
        title = f"[{symbol}]       {website} - {sector} - {industry}           {last_date}"
        log_msg += title + "\n" + profile
    else:
        title = f"[{symbol}]           {last_date}"
        log_msg += title
    log_msg += "\n======================================================="

    print(log_msg)
    # with open("_finplot-watchlist.log", "a") as f:
    #     f.write(log_msg)

    # print(__file__)
    pardir = os.path.dirname(__file__)
    chart_dir = os.path.join(pardir, "charts", today_str)
    if not os.path.exists(chart_dir):
        os.mkdir(chart_dir)
    file_png = os.path.join(chart_dir, f"{symbol}_{today_str}.png")
    # print(file_png)

    ax, ax1, ax2 = fplt.create_plot(title, rows=3)

    # plot price
    fplt.candlestick_ochl(df[['Date', 'Open', 'Close', 'High', 'Low']], ax=ax)
    hover_label = fplt.add_legend(symbol, ax=ax)
    ma15 = df.Close.ewm(span=MA_FAST).mean()
    ma50 = df.Close.ewm(span=MA_SLOW).mean()
    ma200 = df.Close.ewm(span=MA_LONG).mean()
    fplt.plot(ma15, ax=ax, color=COLOR_IDX["blue"], width=1)
    fplt.plot(ma50, ax=ax, color=COLOR_IDX["red"], width=2)
    fplt.plot(ma200, ax=ax, color=COLOR_IDX["green"], width=3)

    # plot macd with standard colors first
    macd = ma15 - ma50
    signal = macd.ewm(span=MACD_AVG).mean()
    trend = TREND_FACTOR * (ma50 - ma200)
    df['macd_diff'] = MACD_FACTOR * (macd - signal)

    fplt.volume_ocv(df[['Date', 'Open', 'Close', 'macd_diff']],
                    ax=ax1,
                    colorfunc=fplt.strength_colorfilter)
    fplt.plot(macd, ax=ax1)
    # fplt.plot(signal, ax=ax1, legend='Signal')
    fplt.plot(macd, ax=ax1, width=COLOR_IDX["red"])
    fplt.plot(signal, ax=ax1, color=COLOR_IDX["black"])
    fplt.plot(trend, ax=ax1, width=2, color=COLOR_IDX["blue"])

    # # change to b/w coloring templates for next plots
    # fplt.candle_bull_color = fplt.candle_bear_color = '#000'
    # fplt.volume_bull_color = fplt.volume_bear_color = '#333'
    # fplt.candle_bull_body_color = fplt.volume_bull_body_color = '#fff'

    # plot volume
    # axo = ax.overlay()
    vol_factor = 100000
    df['Volume'] = df['Volume'] / vol_factor
    fplt.volume_ocv(df[['Date', 'Open', 'Close', 'Volume']], ax=ax2)
    fplt.plot(df.Volume.ewm(span=20).mean(),
              ax=ax2,
              color=COLOR_IDX["black"],
              width=2)

    # if interactive:
    #     fplt.set_time_inspector(update_legend_text, ax=ax, when='hover')
    #     fplt.add_crosshair_info(update_crosshair_text, ax=ax)

    if save_chart:
        fplt.timer_callback(save, 0.5,
                            single_shot=True)  # wait some until we're rendered

    # print(chart_info)
    return_result = (fplt, file_png)
    return return_result
Ejemplo n.º 9
0
daily_plot = fplt.candlestick_ochl(dfd.dropna(), candle_width=5)
daily_plot.colors.update(
    dict(bull_body='#bfb',
         bull_shadow='#ada',
         bear_body='#fbc',
         bear_shadow='#dab'))
daily_plot.x_offset = 3.1  # resample() gets us start of day, offset +1.1 (gap+off center wick)

# plot high resolution on top
fplt.candlestick_ochl(df[['Open', 'Close', 'High', 'Low']])

# scatter plot correlation between Google and Microsoft stock
df['ret_alphabet'] = df.Close.pct_change()
df['ret_microsoft'] = dfms.Close.pct_change()
dfc = df.dropna().reset_index(drop=True)[['ret_alphabet', 'ret_microsoft']]
fplt.plot(dfc, style='o', color=1, ax=ax2)

# draw least-square line
errfun = lambda arr: [
    y - arr[0] * x + arr[1]
    for x, y in zip(dfc.ret_alphabet, dfc.ret_microsoft)
]
line = scipy.optimize.least_squares(errfun, [0.01, 0.01]).x
linex = [dfc.ret_alphabet.min(), dfc.ret_alphabet.max()]
liney = [linex[0] * line[0] + line[1], linex[1] * line[0] + line[1]]
fplt.add_line((linex[0], liney[0]), (linex[1], liney[1]), color='#993', ax=ax2)
fplt.add_text((linex[1], liney[1]), 'k=%.2f' % line[0], color='#993', ax=ax2)
fplt.add_legend('Alphabet vs. Microsft 90m correlation', ax=ax2)

fplt.show()
Ejemplo n.º 10
0
 def updateCandlePane(self, quotes):
     self.ax.reset()
     finplot.candlestick_ochl(quotes)
     finplot.refresh()
     self.hoverLabel = finplot.add_legend('', ax=self.ax)
     finplot.set_time_inspector(self.updateLegend, ax=self.ax, when='hover')
Ejemplo n.º 11
0
def plot_signal(kline, buy_signal=None, sell_signal=None, *args):
    """回测完成后调用此函数绘制k线图与指标"""
    fplt.foreground = '#FFFFFF'
    fplt.background = '#333333'
    fplt.odd_plot_background = '#333333'
    fplt.cross_hair_color = "#FFFFFF"
    ax, ax2, ax3 = fplt.create_plot('历史K线图',
                                    init_zoom_periods=100,
                                    maximize=True,
                                    rows=3)
    fplt.add_legend("K线主图", ax)
    fplt.add_legend("成交量", ax2)
    fplt.add_legend("指标副图", ax3)

    df = pd.DataFrame(kline)
    df = df[[0, 1, 2, 3, 4, 5]]
    columns = ['time', 'open', 'high', 'low', 'close', 'volume']
    df.columns = columns
    df = df.astype({
        'time': 'datetime64[ns]',
        'open': 'float64',
        'high': 'float64',
        'low': 'float64',
        'close': 'float64',
        'volume': 'float64'
    })
    candlesticks = df['time open close high low'.split()]
    volumes = df['time open close volume'.split()]
    fplt.candlestick_ochl(candlesticks)
    fplt.volume_ocv(volumes, ax=ax2)

    if args:
        count = 1
        for i in args:
            indicators = pd.Series(i)
            fplt.plot(df['time'],
                      indicators,
                      legend="指标{}".format(count),
                      ax=ax3)
            count += 1
    if buy_signal:
        for i in buy_signal:
            df.loc[df['high'] == buy_signal[buy_signal.index(i)],
                   "buy_signal"] = df['high']
        fplt.plot(df['time'],
                  df['buy_signal'],
                  ax=ax,
                  color="#FF0000",
                  style='^',
                  width=2,
                  legend='买入信号')
    if sell_signal:
        for i in sell_signal:
            df.loc[df['low'] == sell_signal[sell_signal.index(i)],
                   "sell_signal"] = df['low']
        fplt.plot(df['time'],
                  df['sell_signal'],
                  ax=ax,
                  color="#00FF00",
                  style='v',
                  width=2,
                  legend='卖出信号')
    fplt.show()