コード例 #1
0
        ' <Close>': 'close',
        ' <High>': 'high',
        ' <Low>': 'low',
        ' <Volume>': 'volume'
    })
for e in range(len(df['time'])):
    df['time'][e] = datetime.strptime(df['time'][e], "%m/%d/%Y %H:%M:%S")

df = df.astype({'time': 'datetime64[ns]'})
print(df)
# create three plots
ax, ax2, ax3 = fplt.create_plot(symbol, rows=3)

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

# put an MA in there
#fplt.plot(df['time'], df['close'].rolling(25).mean(), ax=ax, color='#00f', legend='ma-25')

# place some dumb markers
hi_wicks = df['high'] - df[['open', 'close']].T.max()
df.loc[(hi_wicks > hi_wicks.quantile(0.99)), 'marker'] = df['high']
#fplt.plot(df['time'], df['marker'], ax=ax, color='#f44', style='^', legend='dumb mark')

# draw some random crap on our second plot
fplt.plot(df['time'],
          np.random.normal(size=len(df)),
          ax=ax2,
          color='#927',
          legend='stuff')
コード例 #2
0
    'T': 'time',
    'O': 'open',
    'C': 'close',
    'H': 'high',
    'L': 'low',
    'V': 'volume'
})
df = df.astype({'time': 'datetime64[ns]'})

# create three plots
ax, ax2, ax3 = fplt.create_plot(symbol, rows=3)

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

# put an MA in there
fplt.plot(df['time'],
          df['close'].rolling(25).mean(),
          ax=ax,
          color='#0000ff',
          legend='ma-25')

# place some dumb markers
hi_wicks = df['high'] - df[['open', 'close']].T.max().T
df.loc[(hi_wicks > hi_wicks.quantile(0.99)), 'marker'] = df['close']
fplt.plot(df['time'],
          df['marker'],
          ax=ax,
          color='#000000',
コード例 #3
0
 def plotCandles(cls, df, ax):
     #return df[["Open", "Close", "High", "Low"]].plot(ax=ax, kind="candle")
     return fplt.candlestick_ochl(df[cls.cs_keys], ax=ax)
コード例 #4
0
ファイル: viz.py プロジェクト: ajmal017/pandas-polygon
import finplot as fplt
import pandas as pd

bars_df = pd.read_feather('bars.feather')
bars_df = bars_df.set_index('close_at')

fplt.candlestick_ochl(bars_df[['price_open','price_close','price_high','price_low']])
fplt.show()



def plot_bars(bars:pd.DataFrame):
    ax1, ax2 = fplt.create_plot('Prices+Vol', rows=2)
    fplt.candlestick_ochl(bars[['price_open','price_close','price_high','price_low']], ax=ax1)
    fplt.volume_ocv(bars[['price_open','price_close','volume_sum']], ax=ax2)
    fplt.show()


# candle stick example
from math import pi
import pandas as pd
from bokeh.plotting import figure, output_file, show
from bokeh.sampledata.stocks import MSFT

df = pd.DataFrame(MSFT)[:50]
df["date"] = pd.to_datetime(df["date"])

inc = df.close > df.open
dec = df.open > df.close
w = 12*60*60*1000 # half day in ms
コード例 #5
0
ファイル: viz.py プロジェクト: ajmal017/pandas-polygon
def plot_bars(bars:pd.DataFrame):
    ax1, ax2 = fplt.create_plot('Prices+Vol', rows=2)
    fplt.candlestick_ochl(bars[['price_open','price_close','price_high','price_low']], ax=ax1)
    fplt.volume_ocv(bars[['price_open','price_close','volume_sum']], ax=ax2)
    fplt.show()
コード例 #6
0
import datetime as dt

mt5.initialize()

#________Setting up Data_________#
symbol = input('Enter symbol: ').upper()

rate = pd.DataFrame(mt5.copy_rates_from_pos(symbol, mt5.TIMEFRAME_H1, 0, 200))

rate['time'] = pd.to_datetime(rate['time'], unit='s')

#________Settingup plot________#

# creating multiple windows
ax, ax2 = fplt.create_plot(title=symbol, rows=2)
fplt.candlestick_ochl(rate[['time', 'open', 'close', 'high', 'low']], ax=ax)

# creating volume overlay on 1st window
axo = ax.overlay()
fplt.volume_ocv(rate[['time', 'open', 'close', 'tick_volume']], ax=axo)

#_________plotting MACD on 2nd window__________#
# MACD line
macd = rate['close'].ewm(span=12).mean() - rate['close'].ewm(span=26).mean()

#signal line
signal = macd.ewm(span=9).mean()

rate['macd_diff'] = macd - signal

# plotting MACD histogram
コード例 #7
0
def plt_chart(fa_info, save_chart=False, interactive=False):
    global df
    global symbol
    global file_png
    # load data and convert date

    file_png = ""
    symbol,sector,industry,website,num_emp,profile,pct_shorts,book_value = fa_info

    return_result = (None, None)
    end_t = int(time()) 
    start_t = end_t - NUM_OF_MONTHS*30*24*60*60 
    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} - emp: {num_emp} - shorts: {pct_shorts}% - book: {book_value}          {last_date}"
        log_msg += title + "\n" + sanitize(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)

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

    # plot price 
    finplot.candlestick_ochl(df[['Date','Open','Close','High','Low']], ax=ax)
    hover_label = finplot.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()
    finplot.plot(ma15, ax=ax, color=COLOR_IDX["blue"], width=1)
    finplot.plot(ma50, ax=ax, color=COLOR_IDX["red"], width=2)
    finplot.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)

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

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


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

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

    if save_chart:

        # 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)

        finplot.timer_callback(save, 0.5, single_shot=True) # wait some until we're rendered

    # print(chart_info)
    return file_png, log_msg
コード例 #8
0
def change_asset(*args, **kwargs):
    '''Resets and recalculates everything, and plots for the first time.'''
    # save window zoom position before resetting
    fplt._savewindata(fplt.windows[0])

    symbol = ctrl_panel.symbol.currentText()
    interval = ctrl_panel.interval.currentText()
    ws.df = None
    df = load_price_history(symbol, interval=interval)
    ws.reconnect(symbol, interval, df)

    # remove any previous plots
    ax.reset()
    axo.reset()
    ax_rsi.reset()

    # calculate plot data
    indicators = ctrl_panel.indicators.currentText().lower()
    data, price_data = calc_plot_data(df, indicators)

    # some space for legend
    ctrl_panel.move(100 if 'clean' in indicators else 200, 0)

    # plot data
    global plots
    plots = {}
    plots['price'] = fplt.candlestick_ochl(data['price'], ax=ax)
    plots['volume'] = fplt.volume_ocv(data['volume'], ax=axo)
    if data['ma50'] is not None:
        plots['ma50'] = fplt.plot(data['ma50'], legend='MA-50', ax=ax)
        plots['ma200'] = fplt.plot(data['ma200'], legend='MA-200', ax=ax)
        plots['vema24'] = fplt.plot(data['vema24'],
                                    color=4,
                                    legend='V-EMA-24',
                                    ax=axo)
    if data['rsi'] is not None:
        ax.set_visible(xaxis=False)
        ax_rsi.show()
        fplt.set_y_range(0, 100, ax=ax_rsi)
        fplt.add_band(30, 70, color='#6335', ax=ax_rsi)
        plots['sar'] = fplt.plot(data['sar'],
                                 color='#55a',
                                 style='+',
                                 width=0.6,
                                 legend='SAR',
                                 ax=ax)
        plots['rsi'] = fplt.plot(data['rsi'], legend='RSI', ax=ax_rsi)
        plots['stoch'] = fplt.plot(data['stoch'],
                                   color='#880',
                                   legend='Stoch',
                                   ax=ax_rsi)
        plots['stoch_s'] = fplt.plot(data['stoch_s'], color='#650', ax=ax_rsi)
    else:
        ax.set_visible(xaxis=True)
        ax_rsi.hide()

    # price line
    ax.price_line = pg.InfiniteLine(
        angle=0,
        movable=False,
        pen=fplt._makepen(fplt.candle_bull_body_color, style='.'))
    ax.price_line.setPos(price_data['last_close'])
    ax.price_line.pen.setColor(pg.mkColor(price_data['last_col']))
    ax.addItem(ax.price_line, ignoreBounds=True)

    # restores saved zoom position, if in range
    fplt.refresh()
コード例 #9
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')
コード例 #10
0
import finplot as fplt
import pandas as pd
import requests

# download, extract times and candles
url = 'https://www.tensorcharts.com/tensor/bitmex/XBTUSD/heatmapCandles/15min'
data = requests.get(url).json()
times = pd.to_datetime([e['T'] for e in data])
candles = [(e['open'], e['close'], e['high'], e['low']) for e in data]
df_candles = pd.DataFrame(index=times, data=candles)

# extract volume heatmap as a PRICE x VOLUME matrix
orderbooks = [(e['heatmapOrderBook'] or []) for e in data]
prices = sorted(set(prc for ob in orderbooks for prc in ob[::2]))
vol_matrix = [[0] * len(prices) for _ in range(len(times))]
for i, orderbook in enumerate(orderbooks):
    for price, volume in zip(orderbook[::2], orderbook[1::2]):
        j = prices.index(price)
        vol_matrix[i][j] = volume
df_volume_heatmap = pd.DataFrame(index=times, columns=prices, data=vol_matrix)

# plot
fplt.create_plot('BitMEX BTC 15m orderbook heatmap')
fplt.candlestick_ochl(df_candles)
fplt.heatmap(df_volume_heatmap, filter_limit=0.2, whiteout=0.3)
fplt.show()
コード例 #11
0
ファイル: backtest.py プロジェクト: xujiexin/StockQuant
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()
コード例 #12
0
ファイル: btc-long-term.py プロジェクト: legavaz/finplot
import requests
import pandas as pd

now = date.today().strftime('%Y-%m-%d')
r = requests.get(
    'https://www.bitstamp.net/api-internal/tradeview/price-history/BTC/USD/?step=86400&start_datetime=2011-08-18T00:00:00.000Z&end_datetime=%sT00:00:00.000Z'
    % now)
df = pd.DataFrame(r.json()['data']).astype({
    'timestamp': int,
    'open': float,
    'close': float,
    'high': float,
    'low': float
}).set_index('timestamp')

# plot price
fplt.create_plot('Bitcoin 2011-%s' % now.split('-')[0], yscale='log')
fplt.candlestick_ochl(df['open close high low'.split()])

# monthly separator lines
months = pd.to_datetime(df.index, unit='s').strftime('%m')
last_month = ''
for x, (month, price) in enumerate(zip(months, df.close)):
    if month != last_month:
        fplt.add_line((x - 0.5, price * 0.5), (x - 0.5, price * 2),
                      color='#bbb',
                      style='--')
    last_month = month

fplt.show()
コード例 #13
0
ファイル: example-snp500.py プロジェクト: Alkor135/chart
macd = df.Close.ewm(span=12).mean() - df.Close.ewm(span=26).mean()
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' % (
コード例 #14
0
def plotter():
    """Takes the input value from widgets and creates a candlestick plot."""

    base = (symbolVar.get()).upper()
    quote = quoteCurrency.get()
    start_date = startDateCal.get_date()
    end_date = endDateCal.get_date()
    interval = intervalVar.get()

    #______If no symbol entered_______#
    if len(base) == 0:
        errorBox()
        return None
    else:
        pass

    base_ticker = yf.Ticker(base)

    #_____If symbol is invalid________#
    try:
        base_currency = base_ticker.info['currency']
    except ImportError:
        errorBox2()
        return None
    else:
        pass

    if quote == 'Select' or quote == base_currency:  # No currency is selected or base denomination = selected currency.
        base_ticker = yf.Ticker(base)
        base_quote = base_ticker.history(
            start=start_date, end=end_date, interval=interval).drop(
                columns=['Dividends', 'Stock Splits', 'Volume'])
    else:  # A currency is selected.
        base_quote = synthesize(base, quote, start_date, end_date, interval)

    base_quote.dropna(inplace=True)

    # print(base_quote)
    # Calculating Simple Moving averages
    base_quote['SMA 1'] = base_quote['Close'].rolling(sma1Var.get()).mean()
    base_quote['SMA 2'] = base_quote['Close'].rolling(sma2Var.get()).mean()

    # print(base_quote)
    # Calculating Standard-deviation.
    base_quote['pct_change'] = base_quote['Close'].pct_change() * 100
    base_quote['std-dev'] = base_quote['pct_change'].rolling(
        stdDevVar.get()).std()
    # print(base_quote)

    candle_stick_data = fplt.PandasDataSource(
        base_quote[['Open', 'Close', 'High', 'Low']])
    ax, ax2 = fplt.create_plot(title=f"{base}/{quote}", rows=2)
    candle_plot = fplt.candlestick_ochl(candle_stick_data, ax=ax)

    # Plotting SMAs
    sma1 = fplt.plot(base_quote['SMA 1'], legend=f'{sma1Var.get()} SMA', ax=ax)
    sma2 = fplt.plot(base_quote['SMA 2'], legend=f'{sma2Var.get()} SMA', ax=ax)
    # Ploting StdDev
    stdDevPlot = fplt.plot(base_quote['std-dev'],
                           legend=f'{stdDevVar.get()} period std-dev',
                           ax=ax2)
    fplt.add_text(pos=(base_quote.index[-1], base_quote['std-dev'].iloc[-1]),
                  s=f"{base_quote['std-dev'].iloc[-1].round(2)}%",
                  ax=ax2)

    fplt.show()
コード例 #15
0
def plot_price(df):
    df = df.set_index('time')
    fplt.candlestick_ochl(df[['open', 'close', 'high', 'low']])
    fplt.show()
コード例 #16
0
    def show_day_plot(self, instance):
        aux = int(instance.text.split('-')[0])
        #print ('fechaaa')
        #print (aux)
        '''TERMINA TUS WEADAS ACA'''
        #print (self.marketdata)
        #temp = pd.date_range(start=temp['time'][self.fechas[0]], end=temp['time'][self.fechas[1]], freq='D')
        #print (self.fechas[0])
        #print (self.fechas[0],self.fechas[1])
        #datex = self.fechas[3]
        #print (rt.Singleton.getInstance().result)
        try:
            self.marcadores = pd.read_pickle('estrategia1.pkl')
            self.marketdata['marker'] = self.marcadores['marker']
        except:
            print('mierda')

        desde = self.fechas[aux] + timedelta(hours=5)
        hasta = desde + timedelta(hours=24)
        temp = self.marketdata[(self.marketdata.time > desde)
                               & (self.marketdata.time <= hasta)]
        #print (temp)
        #print (temp['time'][self.fecha])
        #temp = self.get_frac_df(temp,)
        #print ('actualizado')

        #print ('SELECCIONADO')
        #print (temp)
        #print (temp.dtypes)
        '''TODO :MEJORA EL FFT que agrege en la ventana izquierda en matplotlib'''
        #self.plot_fft(temp,'filtered')

        ax, ax2 = fplt.create_plot('NASDAQ', rows=2)  #,maximize=True)
        try:
            '''CANDLESTICK CHARTS'''

            candle_src = fplt.PandasDataSource(
                temp[['time', 'open', 'close', 'high', 'low']])
            fplt.candlestick_ochl(candle_src,
                                  ax=ax,
                                  draw_body=True,
                                  draw_shadow=True)
            fplt.plot(temp['time'],
                      temp['sma200'],
                      ax=ax,
                      color='#0000ff',
                      legend='ma-200')
            fplt.plot(temp['time'],
                      temp['filtered'],
                      ax=ax,
                      color='#ff00ff',
                      legend='filtrado',
                      width=2)

            try:
                '''OBTIENE LAS ORDENES DE COMPRA-VENTA'''
                buys = pd.read_pickle("book_buy.pkl")
                #sell = pd.read_pickle("book_sell.pkl")
                '''PROCEDE A PLOTEAR'''
                print('compras')
                print(buys)
                pass
            except:
                print("[ ERROR ] Fallo al obtener las ordenes de compra/venta")
                pass
            '''VOLUMEN CHARTS'''
            volume_src = fplt.PandasDataSource(
                temp[['time', 'open', 'close', 'volume']])
            fplt.volume_ocv(volume_src, ax=ax2)

            # place some dumb markers
            #hi_wicks = df['high'] - df[['open','close']].T.max().T
            #df.loc[(hi_wicks>hi_wicks.quantile(0.99)), 'marker'] = df['close']

            fplt.plot(temp['time'],
                      temp['marker'],
                      ax=ax,
                      color='#000000',
                      style='^',
                      legend='dumb mark')
            #with pd.option_context('display.max_rows', None, 'display.max_columns', None):  # more options can be specified also
            #    print (self.marcadores)
            '''INTERMEDIOS'''
            #te = np.random.normal(size=len(temp))
            #fplt.plot(temp['time'], te, ax=ax2, color='#001177', legend='vortex pos')
            #fplt.plot(temp['time'], temp['vortex_n'], ax=ax2, color='#ff0000', legend='vortex neg')
            #fplt.set_y_range(ax2, -4.4, +4.4) # fix y-axis range
            # draw some random crap on our second plot
            #temp['rnd'] = np.random.normal(size=len(temp))
            #print (temp.vortexn)
            #fplt.plot(temp['time'], temp['vortexn'], ax=ax3, color='#992277', legend='stuff')
            #fplt.set_y_range(ax3, -10.4, +10.7) # fix y-axis range
            # finally a volume bar chart in our third plot

            fplt.show()
            #pass
        except Exception as e:
            print(e)
        pass