Example #1
0
def print_linear(symbol, interval):
    """Plot line chart selected crypto and time interval from Binance API

    :param str symbol: crypto pair (e.g. BTCUSDT)
    :param str interval: time interval (e.g 1d, 1h, 1m.. more in README file)
    :return: html file with line chart created by plotly library
    """
    df = prepare_data(symbol, interval)
    trace = go.Ohlc(
        x=df.index[:],
        open=df['Open'],
        high=df['High'],
        low=df['Low'],
        close=df['Close'],
        name=symbol,
        increasing=dict(line=dict(color='blue')),
        decreasing=dict(line=dict(color='red')),
    )

    data = [trace]
    layout = {
        'title': symbol,
        'yaxis': {'title': 'Price'}
    }
    fig = dict(data=data, layout=layout)
    plot = py.plot(fig, filename=f'templates/{symbol}_{interval}.html', auto_open=False)
    return plot
Example #2
0
File: plots.py Project: lit26/ta
 def _main_plot(self):
     data = None
     if self._chart_type == "Candlestick":
         data = go.Candlestick(x=self._time,
                               open=self._open,
                               high=self._high,
                               low=self._low,
                               close=self._close,
                               name="Candlestick",
                               showlegend=self._showlegend)
     elif self._chart_type == "Line":
         data = go.Scatter(x=self._time,
                           y=self._close,
                           name="Close",
                           showlegend=self._showlegend)
     elif self._chart_type == "OHLC":
         data = go.Ohlc(x=self._time,
                        open=self._open,
                        high=self._high,
                        low=self._low,
                        close=self._close,
                        name="OHLC",
                        showlegend=self._showlegend)
     elif self._chart_type == 'Area':
         data = go.Scatter(x=self._time,
                           y=self._close,
                           name="Close",
                           showlegend=self._showlegend,
                           fill='tozeroy')
     self._fig.add_trace(data, row=1, col=1)
Example #3
0
def test_create_chart(data):
    date_y = datetime.date.today() - timedelta(days=60)
    df = nsepy.get_history(symbol=data, start=date_y, end=datetime.date.today())
    buy = []
    df.reset_index('Date', inplace=True)
    df['Date'] = df['Date'].astype(str)
    df['Date'] = df['Date'].apply(lambda x: datetime.datetime.strptime(x, '%Y-%m-%d'))
    df.set_index('Date', inplace=True)
    df = df['Close'].resample('1M').ohlc()
    df.reset_index('Date', inplace=True)
    fig = go.Figure(data=[go.Ohlc(x=df['Date'], open=df['open'], high=df['high'], low=df['low'], close=df['close'])])
    df['HA_Close'] = round((df['open'] + df['high'] + df['low'] + df['close']) / 4, 2)
    df['HA_Open'] = (df['open'].shift(1) + df['open'].shift(1)) / 2
    df.iloc[0, df.columns.get_loc("HA_Open")] = (df.iloc[0]['open'] + df.iloc[0]['close']) / 2
    df['HA_High'] = df[['high', 'low', 'HA_Open', 'HA_Close']].max(axis=1)
    df['HA_Low'] = df[['high', 'low', 'HA_Open', 'HA_Close']].min(axis=1)
    fig = go.Figure(data=[
        go.Candlestick(x=df['Date'], open=df['HA_Open'], high=df['HA_High'], low=df['HA_Low'], close=df['HA_Close'])])
    if (float(df.iloc[[-2]]['HA_High']) <= float(df.iloc[[-2]]['HA_Open'])):
        if (float(df.iloc[[-2]]['HA_Low']) <= float(df.iloc[[-2]]['HA_Close'])):
            print('Sell Recommanded Price for ' + data + ' :', round(float(df.iloc[[-2]]['HA_Low']) * 98 / 100, 2))
    elif (float(df.iloc[[-2]]['HA_Low']) >= float(df.iloc[[-2]]['HA_Open'])):
        if ((float(df.iloc[[-2]]['HA_High']) >= float(df.iloc[[-2]]['HA_Close']))):
            buy.append(data)
            buy.append(round(float(df.iloc[[-2]]['HA_High']) * 102 / 100, 2))
            print('Buy Recommanded Price for ' + data + ':', round(float(df.iloc[[-2]]['HA_High']) * 102 / 100, 2))
            os.chdir('/storage/emulated/0/recom')
            df[['Date', 'HA_Open', 'HA_High', 'HA_Low', 'HA_Close']].to_excel(data + '.xlsx')
            fig.write_html(data + '.html')
            buy_list.append(buy)
Example #4
0
def candles(yourTitle, xTitle, yTitle, dataFrame):
    """
    Function for building market figures, returning figure object
    :param yourTitle: Title of graph
    :param xTitle: Title of X axis
    :param yTitle: Title of Y axis
    :param dataFrame: source DataFrame with columns Date, Open, High, Low, Close
    :return: figure object
    """
    fig = go.Figure(data=go.Ohlc(x=dataFrame['Date'],
                                 open=dataFrame['Open'],
                                 high=dataFrame['High'],
                                 low=dataFrame['Low'],
                                 close=dataFrame['Close']))
    fig.update_layout(title_text=yourTitle,
                      title={
                          'y': 0.9,
                          'x': 0.5,
                          'xanchor': 'center',
                          'yanchor': 'top'
                      },
                      xaxis_rangeslider_visible=True,
                      xaxis_title=xTitle,
                      yaxis_title=yTitle)
    return fig
Example #5
0
def ohlcv(df, date, open, high, low, close, volume):
    rDf = df.reset_index()

    # Create subplots and mention plot grid size
    fig = make_subplots(rows=2,
                        cols=1,
                        shared_xaxes=True,
                        vertical_spacing=0.03,
                        subplot_titles=('OHLC', 'Volume'),
                        row_width=[0.2, 0.7])

    fig.add_trace(go.Ohlc(x=rDf[date],
                          open=rDf[open],
                          high=rDf[high],
                          low=rDf[low],
                          close=rDf[close],
                          name="OHLC"),
                  row=1,
                  col=1)

    # Bar trace for volumes on 2nd row without legend
    fig.add_trace(go.Bar(x=rDf[date], y=rDf[volume], showlegend=False),
                  row=2,
                  col=1)

    # Do not show OHLC's rangeslider plot
    fig.update(layout_xaxis_rangeslider_visible=False)

    fig.show()
Example #6
0
def plot_news(hourly_ohlc, all_sentis):
    fig = make_subplots(rows=3,
                        cols=1,
                        shared_xaxes=True,
                        vertical_spacing=0,
                        row_heights=[3, 1, 1])
    fig.add_trace(go.Ohlc(x=hourly_ohlc.index,
                          open=hourly_ohlc.open,
                          high=hourly_ohlc.high,
                          low=hourly_ohlc.low,
                          close=hourly_ohlc.close,
                          name="Stock OHLC"),
                  row=1,
                  col=1)

    fig.add_trace(go.Bar(x=all_sentis.index,
                         y=all_sentis.values,
                         name=f"Key Word Count",
                         marker_color="lightslategray"),
                  row=2,
                  col=1)

    fig.add_trace(go.Bar(x=hourly_ohlc.index,
                         y=hourly_ohlc.volume,
                         name=f"Stock Volume",
                         marker_color="green"),
                  row=3,
                  col=1)

    fig.update(layout_xaxis_rangeslider_visible=False)
    fig.update_layout(
        height=600,
        width=1200,
        title_text=f"News intraday twitter sentiment from mainstream media")
    fig.show()
Example #7
0
    def plotGraph(self, stock_data: str):
        graph_image_base64 = None

        try:
            df = pd.read_csv(stock_data, sep=";")
            fig = go.Figure(data=go.Ohlc(x=df['date'],
                                         open=df['open'],
                                         high=df['high'],
                                         low=df['low'],
                                         close=df['close']))

            graphFileName = os.path.join(os.getcwd(), 'libs', 'algonia', 'py',
                                         'graphs',
                                         str(uuid.uuid1()) + '.jpeg')
            fig.write_image(graphFileName)

            with open(graphFileName, "rb") as img_file:
                graph_image_base64 = base64.b64encode(img_file.read())

            return graph_image_base64
        except Exception as inst:
            print('error')
            print(type(inst))
            print(inst.args)
            print(inst)
            return 'error'
Example #8
0
def build_graphs(chosen_volume):  # represents that which is assigned to the component property of the Input
    dff = df[df.Volume > chosen_volume]
    print(dff.head())

    fig_candle = go.Figure(
        go.Candlestick(x=dff['Date'],
                       open=dff['Open'],
                       high=dff['High'],
                       low=dff['Low'],
                       close=dff['Close'],
                       text=dff['Volume'])
    )
    fig_candle.update_layout(margin=dict(t=30, b=30))  # xaxis_rangeslider_visible=False,

    fig_ohlc = go.Figure(
        go.Ohlc(x=dff['Date'],
                open=dff['Open'],
                high=dff['High'],
                low=dff['Low'],
                close=dff['Close'],
                text=dff['Volume'])
    )
    fig_ohlc.update_layout(margin=dict(t=30, b=30))
    
    return fig_candle, fig_ohlc
    def plot_senti3(self,hourly_ohlc,all_sentis):
        # plot it with plotly
        fig = make_subplots(rows=4, cols=1,
                            shared_xaxes=True, 
                            vertical_spacing=0,row_heights=[1.5, 1, 1, 1])
        fig.add_trace(go.Ohlc(x=hourly_ohlc.index,
                                open=hourly_ohlc.open, high=hourly_ohlc.high,
                                low=hourly_ohlc.low, close=hourly_ohlc.close,name="Intraday stock price"),
                    row=1, col=1)
        fig.add_trace(go.Bar(x=hourly_ohlc.index, y=hourly_ohlc.volume,name="Intraday volume",marker_color="lightslategray"),
                    row=2, col=1)

        fig.add_trace(go.Bar(x=all_sentis.index, y=all_sentis.All_counts,name="Publication count",marker_color="orange"),
                    row=3, col=1)

        fig.add_trace(go.Bar(x=all_sentis.index, y=all_sentis.Positive,name="Positive score",marker_color="green"),
                    row=4, col=1)
        fig.add_trace(go.Bar(x=all_sentis.index, y=all_sentis.Negative,name="Negative score",marker_color="red"),
                    row=4, col=1)

        fig.update(layout_xaxis_rangeslider_visible=False)
        fig.update_layout(height=600, width=1200,
                        title_text="{0} intraday twitter sentiment and earnings info".format(self.key_word))

        fig.show()
        if not os.path.exists(self.saveaddr):os.mkdir(self.saveaddr)
        fig.write_image(f'{self.saveaddr}\\{self.key_word}.png')
Example #10
0
def plot(ohlc):
    fig = go.Figure(data=go.Ohlc(x=ohlc['Date'],
                    open=ohlc['Open'],
                    high=ohlc['High'],
                    low=ohlc['Low'],
                    close=ohlc['Close']))
    fig.show()
def create_chart():
    # dfx=pd.read_excel('c.xlsx',index_col=0,parse_dates=True)
    # print(dfx)
    # print(dfx.index)
    df = nsepy.get_history(symbol='CIPLA',
                           start=datetime.date(2006, 6, 1),
                           end=datetime.date.today())
    # print(df.index)
    df.reset_index('Date', inplace=True)
    # print(df.index)
    # print(df)
    df['Date'] = df['Date'].astype(str)
    import datetime as dt
    df['Date'] = df['Date'].apply(
        lambda x: dt.datetime.strptime(x, '%Y-%m-%d'))
    df.set_index('Date', inplace=True)
    # print(df.index)
    df = df['Close'].resample('1M').ohlc()
    df.reset_index('Date', inplace=True)
    print('After resampling')
    print(df)
    df.to_excel('monthly.xlsx')
    fig = go.Figure(data=[
        go.Ohlc(x=df['Date'],
                open=df['open'],
                high=df['high'],
                low=df['low'],
                close=df['close'])
    ])
    df['HA_Close'] = (df['open'] + df['high'] + df['low'] + df['close']) / 4
    df['HA_Open'] = (df['open'].shift(1) + df['open'].shift(1)) / 2
    df.iloc[0, df.columns.get_loc("HA_Open")] = (df.iloc[0]['open'] +
                                                 df.iloc[0]['close']) / 2
    df['HA_High'] = df[['high', 'low', 'HA_Open', 'HA_Close']].max(axis=1)
    df['HA_Low'] = df[['high', 'low', 'HA_Open', 'HA_Close']].min(axis=1)

    print(df[['Date', 'HA_Open', 'HA_High', 'HA_Low', 'HA_Close']])
    fig = go.Figure(data=[
        go.Candlestick(x=df['Date'],
                       open=df['HA_Open'],
                       high=df['HA_High'],
                       low=df['HA_Low'],
                       close=df['HA_Close'])
    ])

    if (float(df.iloc[[-2]]['HA_High']) <= float(df.iloc[[-2]]['HA_Open'])):
        if (float(df.iloc[[-2]]['HA_Low']) <= float(df.iloc[[-2
                                                             ]]['HA_Close'])):
            print('Sell Recommanded Price:',
                  float(df.iloc[[-2]]['HA_Low']) * 98 / 100)
    if (float(df.iloc[[-2]]['HA_Low']) >= float(df.iloc[[-2]]['HA_Open'])):
        if ((float(df.iloc[[-2]]['HA_High']) >= float(
                df.iloc[[-2]]['HA_Close']))):
            print('Buy Recommanded Price:',
                  float(df.iloc[[-2]]['HA_High']) * 102 / 100)
    fig.show()
    return df
Example #12
0
def plot_ohlc_binance(df, title=''):
    fig1 = go.Figure(data=go.Ohlc(x=df.index,
                                  open=df['Open_binance'],
                                  high=df['Hight_binance'],
                                  low=df['Low_binance'],
                                  close=df['Close_binance']))
    fig1.update_layout(title=title)
    fig1.show()
    return
Example #13
0
def create_chart():
    df = pd.read_csv('c.csv', names=['date', 'Close'], index_col=0, parse_dates=True)

    df = df['Close'].resample('1M').ohlc()
    df.reset_index('date', inplace=True)
    # print(df)
    fig = go.Figure(data=[go.Ohlc(x=df['date'], open=df['open'], high=df['high'], low=df['low'], close=df['close'])])
    # fig.show()
    return df
Example #14
0
def create_chart(df):
    df = df.head(30)
    fig = go.Figure(data=[
        go.Ohlc(x=df['Date'],
                open=df['Open'],
                high=df['High'],
                low=df['Low'],
                close=df['Close'])
    ])
    fig.show()
Example #15
0
def plot_crypto(symbol):
    'Plot the graph given a symbol name'
    df_symbol = df[df['crypto_id'] == f'{symbol}']
    fig = go.Figure(data=go.Ohlc(x=df_symbol['date'],
                                 open=df_symbol['open'],
                                 high=df_symbol['high'],
                                 low=df_symbol['low'],
                                 close=df_symbol['close']))
    fig.update_layout(title=f'{symbol} currency')
    return fig.show()
Example #16
0
def simple_stock_chart(daily, date, ticker):
    """
    Main stock chart with PSAR: Returns a plotly Dash figure object for the OHLC chart
    including PSAR.
    """

    # Create chart specific dataframe from df_daily
    df_stock = daily.loc[
        pd.IndexSlice[:date, ticker],
        ["open", "high", "low", "close", "psar_short", "psar_long"],
    ].droplevel(1)

    # Build chart
    fig_stock = {
        "data": [
            # Create OHLC.
            go.Ohlc(
                x=df_stock.index,
                open=df_stock["open"],
                high=df_stock["high"],
                low=df_stock["low"],
                close=df_stock["close"],
                name="OHLC",
                line={"width": 1.5},
                increasing_line_color=c5,
                decreasing_line_color=c1,
            ),
            # Add in PSAR one day.
            go.Scatter(
                x=df_stock.index,
                y=df_stock["psar_short"],
                name="PSAR Short",
                mode="markers",
                marker_size=4,
                marker_color=c4,
            ),
            # Add in PSAR weekly.
            go.Scatter(
                x=df_stock.index,
                y=df_stock["psar_long"],
                name="PSAR Long",
                mode="markers",
                marker_size=4,
                marker_color=c2,
            ),
        ],
        # Adjust layout properties.
        "layout":
        go.Layout(
            title="OHLC chart for {}".format(ticker),
            yaxis={"title": "Price in AU$"},
            xaxis={"rangeslider": dict(visible=False)},
        ),
    }
    return fig_stock
Example #17
0
def update_grafico_principal(n_clicks, sensor, ejes):
    if len(ejes) < 1:
        ejes.append('x')
    # fecha = datos.fecha_inicial()
    #Se inicializan variables
    df = pd.DataFrame()
    fig_principal = go.Figure()
    #Listas que conteneran cada trace generado por cada dataframe creado para poder visualizarlos en una grafica
    trace_principal = []
    if n_clicks >= 0:
        #Dependiendo del tipo de sensor se crean visualizaciones distintas
        if tipo_sensor == 'Acelerometro':
            if cantidad_sensores == '1-sensor':
                # La variable df contiene el dataframe que se utiliza para generar los graficos OHLC e histograma

                new_df = pd.DataFrame()
                list_df = []

                colors = [
                    '#e6194b', '#3cb44b', '#ffe119', '#4363d8', '#f58231',
                    '#911eb4'
                ]
                count = 0
                new_count_de = 0
                new_count_in = 1

                for e in ejes:
                    start_time = time()
                    df = datos.datos_ace(sensor, e)

                    elapsed_time = time() - start_time
                    print("Tiempo Transcurrido crear DF: %0.1f seconds." %
                          elapsed_time)
                    # Aqui se crea el grafico OHLC
                    start_time = time()
                    trace_principal.append(
                        go.Ohlc(x=df.index,
                                open=df['open'],
                                high=df['max'],
                                low=df['min'],
                                close=df['close'],
                                increasing_line_color=colors[new_count_in],
                                decreasing_line_color=colors[new_count_de],
                                name=str(sensor) + ' eje: ' + str(e),
                                showlegend=True))
                    count = count + 1
                    new_count_in = new_count_in + 2
                    new_count_de = new_count_de + 2
                    new_df = df

                    #lista de dataframe para generar los indicadores resumen
                    list_df.append(df)
                df = pd.concat(list_df, axis=0, ignore_index=True)
                fig_principal = go.Figure(data=trace_principal)
        return fig_principal
Example #18
0
 def plot_returns(self, start="2019-01-01", end="2020-01-01"):
     if self.expected_returns is None:
         self.expected_return()
     temp = self.historical.reset_index()
     fig = go.Figure(data=go.Ohlc(x=temp['Date'],
                 open=temp['Open'],
                 high=temp['High'],
                 low=temp['Low'],
                 close=temp['Close']))
     fig.show()
     del temp
Example #19
0
def colored_bar_trace(df):
    return go.Ohlc(
        x=df.index,
        open=df["open"],
        high=df["high"],
        low=df["low"],
        close=df["close"],
        showlegend=True,
        name="Colored bar",
        line=dict(width=0.6),
    )
 def get_ohlc(self, price_data, ticker):
     '''return go.Ohlc object '''
     return go.Ohlc(
         x=price_data.index,
         open=price_data.Open,
         high=price_data.High,
         close=price_data.Close,
         low=price_data.Low,
         increasing_line_color="Black",
         decreasing_line_color="Black",
         name=f"{ticker.upper()}",
     )
Example #21
0
def bar_trace(df):
    return go.Ohlc(
        x=df.index,
        open=df["open"],
        high=df["high"],
        low=df["low"],
        close=df["close"],
        increasing=dict(line=dict(color="#888888")),
        decreasing=dict(line=dict(color="#888888")),
        showlegend=True,
        name="Bar",
        line=dict(width=0.6),
    )
Example #22
0
 def wrapper(df):
     fig1 = go.Figure(data=go.Ohlc(x=df.index,
                                   open=df['Open_okex'],
                                   high=df['Hight_okex'],
                                   low=df['Low_okex'],
                                   close=df['Close_okex']))
     fig1.update_layout(title='before')
     fig1.show()
     df = func(df)
     fig1 = go.Figure(data=go.Ohlc(x=df.index,
                                   open=df['Open_okex'],
                                   high=df['Hight_okex'],
                                   low=df['Low_okex'],
                                   close=df['Close_okex']))
     fig1.update_layout(title='after')
     fig1.show()
     fig2 = go.Figure(data=go.Ohlc(x=df.index,
                                   open=df['Open_binance'],
                                   high=df['Hight_binance'],
                                   low=df['Low_binance'],
                                   close=df['Close_binance']))
     fig2.update_layout(title='binance')
     fig2.show()
Example #23
0
def update_timeline_graph(mode, n_clicks, ticker):

    TICKER_PERIOD = "2y"  # valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max
    GOOGLE_TIME_PERIOD = "today 12-m"
    KWD_LIST = [ticker, "bitcoin", "stimulus check"]
    TA_TIMEFRAME = "week"

    df = my_ticker(ticker, TICKER_PERIOD)
    # add moving average
    df["ma50"] = df["Close"].rolling(window=50).mean()
    df["ma200"] = df["Close"].rolling(window=200).mean()
    
    df_btc = my_ticker("BTC-USD", TICKER_PERIOD)
    df_google = google_trend(KWD_LIST, GOOGLE_TIME_PERIOD)
    
    # Create figure with secondary y-axis
    fig = make_subplots(specs=[[{"secondary_y": True}]])
    fig.add_trace(go.Ohlc(x=df.index,
                open=df['Open'],
                high=df['High'],
                low=df['Low'],
                close=df['Close'],
                increasing_line_color= 'green', decreasing_line_color= 'orange', name=ticker)
                 , secondary_y=True)
    
    fig.add_trace(go.Scatter(x=df.index, y=df["ma200"], name=f"{ticker} ma200",
                             line = dict(width=1, color="pink")), secondary_y=True)
    fig.add_trace(go.Scatter(x=df.index, y=df["ma50"], name=f"{ticker} ma50",
                             line = dict(width=1, color="lightgreen")), secondary_y=True)
    
    if mode == "ticker_vs_btc":
        fig.add_trace(go.Scatter(x=df_btc.index, y=df_btc["Close"], name="Bitcoin",
                             line = dict(width=1, color="lightblue")), secondary_y=False)
        fig.update_yaxes(title_text="Price BTC (USD)", secondary_y=False, color="lightblue")
    
    elif mode == "ticker_vs_google_search":
        for i, kwd in enumerate(KWD_LIST):
            fig.add_trace(go.Scatter(x=df_google.index, y=df_google[KWD_LIST[i]], name=f"search {str(KWD_LIST[i])}",
                                 line = dict(width=1, dash='dot')), secondary_y=False)
        fig.update_yaxes(title_text="Google search index", secondary_y=False, color="grey")
    
    fig.update_yaxes(title_text=f"Price {ticker} (USD)", secondary_y=True)
    fig.update_xaxes(title_text="Date")
    #fig.update(layout_xaxis_rangeslider_visible=False)
    fig.update_layout(template="plotly_white",
                      title=f"Ticker: {ticker}, Company: {get_company_name(ticker)} <br>TA {TA_TIMEFRAME}: {tradingview_rec(ticker, TA_TIMEFRAME)}")

    return fig
Example #24
0
    def priceHistoryOLHCChart(self, ticker=False, period=8):
        """Function to generate ohlc history price chart

        Args:
            ticker (str): Name of the ticker. Defaults to False.
            period (int): Number of years to get history. Defaults to 8.
        """
        # Check arguments
        if not ticker:
            return

        elif ticker=='IBOV':
            # Data Frame with Price Data
            Plot_DF = pd.DataFrame({"Open": self.Ibov_Data["Open"]
                ,"Close": self.Ibov_Data["Close"]
                ,"High": self.Ibov_Data["High"]
                ,"Low": self.Ibov_Data["Low"]
                ,"Volume": self.Ibov_Data["Volume"]
            }, self.Ibov_Data.index).dropna()

        else:
            # Data Frame with Price Data
            Plot_DF = pd.DataFrame({"Open": self.Price_Data["Open"][ticker]
                ,"Close": self.Price_Data["Close"][ticker]
                ,"High": self.Price_Data["High"][ticker]
                ,"Low": self.Price_Data["Low"][ticker]
                ,"Volume": self.Price_Data["Volume"][ticker]
            }, self.Price_Data.index).dropna()

        Plot_DF = Plot_DF.iloc[-252*period:]

        # Plotly object
        fig = go.Figure(data=go.Ohlc(
            x=Plot_DF.index
            ,open=Plot_DF['Open']
            ,high=Plot_DF['High']
            ,low=Plot_DF['Low']
            ,close=Plot_DF['Close']
        ))
        fig.update_layout(
            title=f"Price History OHLC"
            ,yaxis_title=f"{ticker}"
        )
        fig.update(layout_xaxis_rangeslider_visible=False)
        fig.show()
Example #25
0
def simple_stock_chart(df_stock, fig_stock_title):
    """Simple stock chart"""
    fig_stock = {
        "data": [
            go.Ohlc(
                x=df_stock.index,
                open=df_stock["Open"],
                high=df_stock["High"],
                low=df_stock["Low"],
                close=df_stock["Close"],
            )
        ],
        "layout": go.Layout(
            title="OHLC chart for {}".format(fig_stock_title),
            yaxis={"title": "Price in US$"},
        ),
    }
    return fig_stock
Example #26
0
def plot_ohlc(fin_data, user_input):

    fig = make_subplots(rows=2,
                        cols=1,
                        row_heights=[0.8, 0.2],
                        shared_xaxes=True,
                        vertical_spacing=0.02)
    fig.add_trace(go.Ohlc(x=fin_data.index,
                          open=fin_data['Open'],
                          high=fin_data['High'],
                          low=fin_data['Low'],
                          close=fin_data['Close']),
                  row=1,
                  col=1)

    fig.add_trace(go.Bar(x=fin_data.index,
                         y=fin_data["Volume"],
                         marker_color="black"),
                  row=2,
                  col=1)
    fig.update(layout_xaxis_rangeslider_visible=False)

    fig.update_layout(
        title=user_input.upper(),
        plot_bgcolor="#FFFFFF",
        hovermode="x",
        hoverdistance=100,  # Distance to show hover label of data point
        spikedistance=-1,  # Distance to show spike
        xaxis=dict(
            #         title="time",
            linecolor="#BCCCDC",
            #         showspikes=True, # Show spike line for X-axis
            # Format spike
            spikethickness=2,
            spikedash="dot",
            spikecolor="#999999",
            spikemode="toaxis+across",
        ),
        yaxis=dict(title="Price", linecolor="#BCCCDC"),
        yaxis2=dict(title="Volume", linecolor="#BCCCDC"))
    return fig
Example #27
0
def draw_price_and_volume_candle_chart(
    df: pandas.DataFrame,
    symbol: str,
    sma_column: str = None,
    export_picture: bool = False,
):
    """
    Draw Price & Volume Candle Chart for OHLC data with an optional SMA line using Plotly.
    """

    t1 = go.Ohlc(
        name="OHLC",
        x=df.index,
        yaxis="y2",
        open=df["Open"],
        high=df["High"],
        low=df["Low"],
        close=df["Close"],
    )

    t2 = go.Bar(name="Volume", x=df.index, y=df["Volume"], yaxis="y",)

    if sma_column:
        t3 = go.Scatter(name=sma_column, x=df.index, yaxis="y2", y=df[sma_column],)
        fig = Figure([t1, t2, t3])
    else:
        fig = Figure([t1, t2])

    layout_params = {
        "title_text": f"{symbol} - Price & Volume",
        "height": 800,
        "yaxis": {"domain": [0, 0.2], "showticklabels": True},
        "yaxis2": {"domain": [0.2, 1]},
    }

    if export_picture:
        layout_params["width"] = 1200

    fig.update_layout(layout_params)

    fig.show()
Example #28
0
def live_quote(ticker="NEA"):

    end = datetime.datetime.now()
    start = end - datetime.timedelta(days=3)

    if ticker == "XJO":
        ticker_quote = "^AXJO"
    elif ticker == "XVI":
        ticker_quote = "^AXVI"
    else:
        ticker_quote = ticker + ".AX"

    df_stock = yf.download(ticker_quote, start=start, end=end, interval="1m")
    df_stock = df_stock.loc[df_stock.index[-1].strftime("%Y-%m-%d"):, :]

    fig_stock = {
        "data": [
            # Create OHLC.
            go.Ohlc(
                x=df_stock.index,
                open=df_stock["Open"],
                high=df_stock["High"],
                low=df_stock["Low"],
                close=df_stock["Close"],
                name="Live",
                line={"width": 1.5},
                increasing_line_color=c5,
                decreasing_line_color=c1,
            )
        ],
        # Adjust layout properties.
        "layout":
        go.Layout(
            title="Live chart for {}".format(ticker),
            yaxis={"title": "Price in AU$"},
            xaxis={"rangeslider": dict(visible=True)},
        ),
    }

    return fig_stock
Example #29
0
def ohlc(df: pd.DataFrame,
         timestamp=None,
         ohlc_key=None,
         symbol=None,
         increasing_line_color=None,
         decreasing_line_color=None,
         strftime_str='%Y/%m/%d %H:%M:%S'):
    if ohlc_key is None:
        ohlc_key = ['open', 'high', 'low', 'close']
    if timestamp is None:
        timestamp = df.index
        timestamp = timestamp.strftime(strftime_str)
    if isinstance(timestamp, pd.Series):
        timestamp = timestamp.apply(
            lambda x: pd.Timestamp.strftime(x, strftime_str))
    return go.Ohlc(x=timestamp,
                   open=df[ohlc_key[0]],
                   high=df[ohlc_key[1]],
                   low=df[ohlc_key[2]],
                   close=df[ohlc_key[3]],
                   name=symbol,
                   increasing_line_color=increasing_line_color,
                   decreasing_line_color=decreasing_line_color)
Example #30
0
def price_plot_with_plotly(price, show_hours=True, **kwargs):
    """Use plotly for interactive plot.

    Parameters
    ----------
    price : pd.DataFrame
        price data frame
    """
    has_ohlc, ohlc = get_ohlc(price)  # Get ohlc for
    config = _process_kwargs(kwargs, _valid_plot_kwargs())
    config['type'] = config['type'].lower()  # Relax the spelling.
    # style = config['style']

    if show_hours:
        timeline_str = [
            p.strftime("%y-%m-%d (%H:%M:%S)") for p in price.index.to_list()
        ]
    else:
        timeline_str = [p.strftime("%y-%m-%d") for p in price.index.to_list()]

    fig = go.Figure()
    if config['type'] == 'line':
        fig.add_trace(
            go.Scatter(x=timeline_str,
                       y=price.Close,
                       line=dict(color='royalblue'),
                       name='Price'))
    elif config['type'] == 'candle' or config['type'] == 'candlestick':
        if has_ohlc:
            fig.add_trace(
                go.Candlestick(x=timeline_str,
                               open=ohlc[0],
                               high=ohlc[1],
                               low=ohlc[2],
                               close=ohlc[3],
                               name='Price'))
        else:
            raise AttributeError(
                'Try to plot candlestick but the data has no ohlc columns')
    elif config['type'] == 'ohlc' or config['type'] == 'bars':
        if has_ohlc:
            fig.add_trace(
                go.Ohlc(x=timeline_str,
                        open=ohlc[0],
                        high=ohlc[1],
                        low=ohlc[2],
                        close=ohlc[3],
                        name='Price'))
        else:
            raise AttributeError(
                'Try to plot ohlc but the data has no ohlc columns')

    mavgs = config['mav']
    if mavgs is not None:
        # Overlay moving average
        if isinstance(mavgs, int):
            mavgs = mavgs,  # convert to tuple
        if len(mavgs) > 7:
            mavgs = mavgs[0:7]  # take at most 7
        #
        # if style['mavcolors'] is not None:
        #     mavc = cycle(style['mavcolors'])
        # else:
        #     mavc = None

        for mav in mavgs:

            mavprices = price.Close.rolling(mav).mean().values
            # if mavc:
            #     ax1.plot(timeline_str, mavprices, color=next(mavc))
            # else:
            #     ax1.plot(timeline_str, mavprices)
            fig.add_trace(
                go.Scatter(x=timeline_str,
                           y=mavprices,
                           line=dict(color='royalblue'),
                           name="MAvg " + str(mav)))

    fig.update_layout(title={
        'text': config['title'],
        'xanchor': 'auto'
    },
                      yaxis_title='Price',
                      xaxis=dict(tickangle=-90))
    fig.show()