Пример #1
0
def worker(sym, inter, ops, csvlock, plots):
    def drawplot():
        url = 'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=%s&interval=%s&apikey=%s&datatype=csv&outputsize=%s'%(sym, inter, APIKEY, ops)
        res = rq.get(url)
        
        with open(sym+'temp.csv', 'wb') as f:
            for chunk in res.iter_content():
                f.write(chunk)
        
        try:
            data = pd.read_csv(sym+'temp.csv', parse_dates=['timestamp'], index_col='timestamp').sort_index()
            
        except:
            return # if API does not respond with valid data.
        
        update_csv(sym, data)
        
        candles = data[['open','close','high','low']]

        volumes = data[['open','close','volume']]
            
        if len(plots) == 0:
            plots.append(fplt.volume_ocv(volumes, ax=ax2))
            plots.append(fplt.candlestick_ochl(candles, ax=ax))
            
        else:
            plots[0].update_data(volumes)
            plots[1].update_data(candles)
            
    #==============================================#
    
    ax, ax2 = fplt.create_plot(sym+' Stock Time Series - '+inter+' - '+ops, rows=2)    
    drawplot()
    fplt.timer_callback(drawplot, 3600.0)   # draw the graphs every 60 mins (3600 secs)
    fplt.show()
Пример #2
0
 def save_plot(self, plot_title, kbars):
     fplt = self.setup_plot(plot_title, kbars)
     with open(f'{plot_title}.png', 'wb') as f:
         fplt.timer_callback(lambda: fplt.screenshot(f),
                             1,
                             single_shot=True)
         fplt.show()
Пример #3
0
    def __init__(self):
        super().__init__()

        self.setWindowTitle("QGraphicsView")
        layout = QGridLayout()
        self.setLayout(layout)
        self.resize(800, 300)
        self.ws = BinanceFutureWebsocket()

        plots = {}
        fplt.y_pad = 0.07  # pad some extra (for control panel)
        fplt.max_zoom_points = 7
        fplt.autoviewrestore()
        self.ax, self.ax_rsi = fplt.create_plot('Complicated Binance Futures Example', rows=2, init_zoom_periods=3000)
        self.axo = self.ax.overlay()
        layout.addWidget(self.ax.vb.win, 0, 0)

        self.ax_rsi.hide()
        self.ax_rsi.vb.setBackgroundColor(None)  # don't use odd background color
        self.ax.set_visible(xaxis=True)

        self.symbol = "BTCUSDT"
        self.interval = "1m"

        self.change_asset()
        fplt.timer_callback(self.realtime_update_plot, 1)  # update every second
        fplt.show(qt_exec=False)
Пример #4
0
 def __init__(self, pipe, init_data, init_sym, tech_indicators, fps=10):
     super().__init__()
     self.plots = []
     self.tech_indicators = tech_indicators
     self.data, self.watched_sym = init_data, init_sym
     self.ax, self.ax2 = fplt.create_plot('Live Stock Trader',
                                          init_zoom_periods=500,
                                          maximize=False,
                                          rows=2)
     self.live_data = None
     self.update_data()
     self.fps = fps
     self.plots = [
         fplt.candlestick_ochl(self.live_data[0], ax=self.ax),
         fplt.volume_ocv(self.live_data[1], ax=self.ax.overlay()),
         fplt.plot(self.live_data[2], ax=self.ax, legend='VWAP')
     ]
     self.plots.extend([
         fplt.plot(ti_d, ax=self.ax2, legend=t)
         for t, ti_d in zip(tech_indicators, self.live_data[3:])
     ])
     fplt.timer_callback(
         self.step,
         1 / fps)  # update (using synchronous rest call) every N seconds
     self.pipe = pipe
Пример #5
0
    def __init__(self, data_host):
        self.plots = []
        self.data_host = data_host
        symbol = data_host.request['symbol']
        fplt.create_plot(f"{symbol}", init_zoom_periods=75, maximize=True)
        self.update_plot()

        def upd():
            try:
                if self.data_host.changed:
                    self.update_plot()
                    self.data_host.changed = False
            except Exception as ex:
                print(ex)

        fplt.timer_callback(upd, 0.1)  # update in 10 Hz
        #fplt.autoviewrestore()
        fplt.show()
Пример #6
0
        t -= t % (60*interval_mins)
        c = trade['price']
        if t < df['t'].iloc[-1]:
            # ignore already-recorded trades
            continue
        elif t > df['t'].iloc[-1]:
            # add new candle
            o = df['c'].iloc[-1]
            h = c if c>o else o
            l = o if o<c else c
            df1 = pd.DataFrame(dict(t=[t], o=[o], c=[c], h=[l], l=[l]))
            df = pd.concat([df, df1], ignore_index=True, sort=False)
        else:
            # update last candle
            i = df.index.max()
            df.loc[i,'c'] = c
            if c > df.loc[i,'h']:
                df.loc[i,'h'] = c
            if c < df.loc[i,'l']:
                df.loc[i,'l'] = c
    update_plot(df)


if __name__ == '__main__':
    df = pd.DataFrame(price_history())
    ws = BitMEXWebsocket(endpoint=baseurl+'/v1', symbol='XBTUSD')
    ax = fplt.create_plot('Realtime Bitcoin/Dollar 1m (BitMEX websocket)', init_zoom_periods=100, maximize=False)
    update_plot(df)
    fplt.timer_callback(update_data, 1.0) # update every second
    fplt.show()
Пример #7
0
#!/usr/bin/env python3

import finplot as fplt
import numpy as np
import pandas as pd


dates = pd.date_range('01:00', '01:00:01.200', freq='1ms')
prices = pd.Series(np.random.random(len(dates))).rolling(30).mean() + 4
fplt.plot(dates, prices, width=3)
line = fplt.add_line((dates[100], 4.4), (dates[1100], 4.6), color='#9900ff', interactive=True)
## fplt.remove_primitive(line)
text = fplt.add_text((dates[500], 4.6), "I'm here alright!", color='#bb7700')
## fplt.remove_primitive(text)
rect = fplt.add_rect((dates[700], 4.5), (dates[850], 4.4), color='#8c8', interactive=True)
## fplt.remove_primitive(rect)

def save():
    fplt.screenshot(open('screenshot.png', 'wb'))
fplt.timer_callback(save, 0.5, single_shot=True) # wait some until we're rendered

fplt.show()
Пример #8
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()
Пример #9
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
Пример #10
0
    ask['price'] += 0.5  # ask above price
    ask['volume'] = -ask['volume'].cumsum(
    )  # negative volume means pointing left
    bid['volume'] = -bid['volume'].cumsum()
    orderbook = [[len(df) + 0.5, pd.concat([bid.iloc[::-1], ask])]]


if __name__ == '__main__':
    df = pd.DataFrame(price_history())
    ws = Instrument(
        channels=[InstrumentChannels.trade, InstrumentChannels.orderBook10])

    @ws.on('action')
    def action(message):
        if 'orderBook' in message['table']:
            for orderbook10 in message['data']:
                update_orderbook_data(orderbook10)
        else:
            for trade in message['data']:
                update_candlestick_data(trade)

    thread = Thread(target=ws.run_forever)
    thread.daemon = True
    thread.start()
    fplt.create_plot('Realtime Bitcoin/Dollar 1m (BitMEX websocket)',
                     init_zoom_periods=75,
                     maximize=False)
    update_plot()
    fplt.timer_callback(update_plot, 0.5)  # update in 2 Hz
    fplt.show()
Пример #11
0
    dft['text'] = dft['y'].apply(lambda v: str(round(v, 1)) if v > 0 else '')
    if labels_plot is None:
        labels_plot = dft.plot(kind='labels', ax=ax)
    else:
        labels_plot.update_data(dft)


def move_view(ax, df):
    global anim_counter
    x = -np.cos(anim_counter / 100) * (len(df) / 2 - 50) + len(df) / 2
    w = np.sin(anim_counter / 100)**4 * 50 + 50
    fplt.set_x_pos(df.index[int(x - w)], df.index[int(x + w)], ax=ax)
    anim_counter += 1


def animate(ax, ax2, df):
    gen_spots(ax, df)
    gen_labels(ax2, df)
    move_view(ax, df)


df = gen_dumb_price()
ax, ax2 = fplt.create_plot('Things move',
                           rows=2,
                           init_zoom_periods=100,
                           maximize=False)
df.plot(kind='candle', ax=ax)
df[['open', 'close', 'volume']].plot(kind='volume', ax=ax2)
fplt.timer_callback(lambda: animate(ax, ax2, df), 1 / FPS)
fplt.show()
Пример #12
0
    panel.darkmode.setText('Haxxor mode')
    panel.darkmode.setCheckState(2)
    panel.darkmode.toggled.connect(dark_mode_toggle)
    layout.addWidget(panel.darkmode, 0, 6)

    return panel


plots = {}
fplt.y_pad = 0.07  # pad some extra (for control panel)
fplt.max_zoom_points = 7
fplt.autoviewrestore()
ax, ax_rsi = fplt.create_plot('Complicated Binance Futures Example',
                              rows=2,
                              init_zoom_periods=1000)
axo = ax.overlay()

# use websocket for real-time
ws = BinanceFutureWebsocket()

# hide rsi chart to begin with; show x-axis of top plot
ax_rsi.hide()
ax_rsi.vb.setBackgroundColor(None)  # don't use odd background color
ax.set_visible(xaxis=True)

ctrl_panel = create_ctrl_panel(ax.vb.win)
dark_mode_toggle(True)
change_asset()
fplt.timer_callback(realtime_update_plot, 1)  # update every second
fplt.show()
Пример #13
0
    df['tddn'] = [('%i' % i if 0 < i < 10 else '') for i in tddn]

    # pick columns for our three data sources: candlesticks and the gree
    datasrc0 = fplt.PandasDataSource(df['time open close high low'.split()])
    datasrc1 = fplt.PandasDataSource(df['time high tdup'.split()])
    datasrc2 = fplt.PandasDataSource(df['time low tddn'.split()])
    if not plots:
        # first time we create the plots
        plots.append(fplt.candlestick_ochl(datasrc0, ax=ax))
        plots.append(fplt.labels_datasrc(datasrc1, color='#009900', ax=ax))
        plots.append(
            fplt.labels_datasrc(datasrc2,
                                color='#990000',
                                ax=ax,
                                anchor=(0.5, 0)))
    else:
        # every time after we just update the data sources on each plot
        plots[0].update_datasrc(datasrc0)
        plots[1].update_datasrc(datasrc1)
        plots[2].update_datasrc(datasrc2)


plots = []
ax = fplt.create_plot('Realtime Bitcoin/Dollar 1m (BitFinex)',
                      init_zoom_periods=100,
                      maximize=False)
update()
fplt.timer_callback(update, 20.0)  # update every N seconds

fplt.show()