Beispiel #1
0
    def update_graph(pair, interval):
        if pair is None: return
        if interval is None: return

        # candle_type = unique_pairs[pair.upper()]
        # data = candle_type.query.order_by(candle_type.time.desc()).limit(24 * 60).all()
        data = generate_intervals(pair, int(interval))

        time_periods = [datetime.fromtimestamp(x.time) for x in data]

        candle_data = go.Candlestick(
            x=time_periods,
            open=[x.open for x in data],
            high=[x.high for x in data],
            low=[x.low for x in data],
            close=[x.close for x in data],
            increasing=dict(fillcolor='rgb(65, 185, 137)', line=dict(color='rgb(65, 185, 137)')),
            decreasing=dict(fillcolor='rgb(244, 76, 95)', line=dict(color='rgb(244, 76, 95)')),
            name='Price',
            showlegend=False,
        )

        volumes = [x.volume for x in data]
        volume_data = go.Bar(
            x=time_periods,
            y=volumes,
            name='Volume',
        )

        vwap_data = go.Scatter(
            x=time_periods,
            y=list(map(lambda x: x.vwap if x.vwap > 0 else (x.open + x.close) / 2, data)),
            name='Vwap',
            fillcolor='orange',
            mode='markers',
            marker=dict(color='orange', size=3),
            showlegend=False,
        )

        fig = make_subplots(specs=[[{"secondary_y": True}]])
        fig.add_trace(volume_data, secondary_y=False)
        fig.add_trace(candle_data, secondary_y=True)
        fig.add_trace(vwap_data, secondary_y=True)

        update_layout(fig,
                      time_periods[min(120, len(time_periods) - 1)],
                      time_periods[0] + timedelta(minutes=int(interval) * 5),
                      max(volumes) * 3)

        return fig
Beispiel #2
0
def chart(df):
    candlestick = go.Candlestick(x=df['open_time'], open=df['open'], high=df['high'], low=df['low'], close=df['close'])
    upper_band = go.Scatter(x=df['open_time'], y=df['upper_band'], name='Upper Bollinger Band', line={'color': 'red'})
    lower_band = go.Scatter(x=df['open_time'], y=df['lower_band'], name='Lower Bollinger Band', line={'color': 'red'})

    upper_keltner = go.Scatter(x=df['open_time'], y=df['upper_keltner'], name='Upper Keltner Channel',
                               line={'color': 'blue'})
    lower_keltner = go.Scatter(x=df['open_time'], y=df['lower_keltner'], name='Lower Keltner Channel',
                               line={'color': 'blue'})

    fig = go.Figure(data=[candlestick, upper_band, lower_band, upper_keltner, lower_keltner])
    fig.layout.xaxis.type = 'category'
    fig.layout.xaxis.rangeslider.visible = False
    fig.show()
Beispiel #3
0
 def __init__(self, stock_data):
     self.data = [
         go.Candlestick(x=stock_data.index,
                        open=stock_data['open'],
                        high=stock_data['high'],
                        low=stock_data['low'],
                        close=stock_data['close'])
     ]
     self.indicators = []
     self.fig = go.Figure(data=self.data)
     self.annotations = []
     self.smallfont = dict(family="Courier New, monospace",
                           size=8,
                           color="#000000")
Beispiel #4
0
def _vnquant_candle_stick_source(symbol,
                                 start_date,
                                 end_date,
                                 colors=['blue', 'red'],
                                 width=800,
                                 height=600,
                                 show_vol=True,
                                 data_source='VND',
                                 **kargs):
    loader = DataLoader.DataLoader(symbol,
                                   start_date,
                                   end_date,
                                   minimal=True,
                                   data_source=data_source)
    data = loader.download()
    symbol = list(data.columns.levels[1])[0]
    data.columns = ['high', 'low', 'open', 'close', 'adjust', 'volume']
    title = '{} stock price & volume from {} to {}'.format(
        symbol, start_date, end_date)
    fig = make_subplots(
        rows=2,
        cols=1,
        shared_xaxes=True,
        vertical_spacing=0.02,
        # subplot_titles=('Price', 'Volume'),
        row_heights=[0.6, 0.4])

    fig.append_trace(go.Candlestick(x=data.index,
                                    open=data['open'],
                                    high=data['high'],
                                    low=data['low'],
                                    close=data['close'],
                                    increasing_line_color=colors[0],
                                    decreasing_line_color=colors[1]),
                     row=1,
                     col=1)

    if show_vol:
        fig.append_trace(go.Bar(x=data.index, y=data['volume'], name='Volume'),
                         row=2,
                         col=1)

    fig.update_layout(title=title,
                      yaxis_title='Price',
                      xaxis_title='Date',
                      width=width,
                      height=height,
                      showlegend=False)

    fig.show()
Beispiel #5
0
def create_plot_financial(stock_name):
    df_y = pdr.DataReader(str(stock_name) + '.bk',
                          data_source='yahoo',
                          start='2018-01-01')
    # a = df_y.iloc[0]['High']
    set1 = go.Candlestick(x=df_y.index,
                          open=df_y['Open'],
                          high=df_y['High'],
                          low=df_y['Low'],
                          close=df_y['Close'])
    set2 = go.Scatter(x=df_y.index, y=df_y['High'] + df_y['High'])
    data = [set1, set2]
    graphJSON = json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder)
    return graphJSON
Beispiel #6
0
def quotes_chart(data):
    fig = go.Figure(data=[
        go.Candlestick(
            x=data['Date'],
            open=data['Open'],
            high=data['High'],
            low=data['Low'],
            close=data['Close'],
            increasing_line_color='green',
            decreasing_line_color='red',
        )
    ])
    fig.update_layout(title="Stock Quotes")
    st.plotly_chart(figure_or_data=fig)
Beispiel #7
0
def update_monthly(exchange, leverage, start_date, end_date):
    dff = filter_df(exchange, leverage, start_date, end_date)
    data = calc_returns_over_month(dff)
    btc_returns = calc_btc_returns(dff)
    strat_returns = calc_strat_returns(dff)
    strat_vs_market = strat_returns - btc_returns
    # for pnl graph
    shortval = dff[dff["Trade type"] == "Short"]["Pnl (incl fees)"]
    longval = dff[dff["Trade type"] == "Long"]["Pnl (incl fees)"]
    shortbar = go.Bar(x=dff["Entry time"], y=shortval, name="Short")
    longbar = go.Bar(x=dff["Entry time"], y=longval, name="Long")
    # line charts
    trace_btc = go.Scatter(x=dff["Entry time"],
                           y=dff["BTC Price"],
                           mode="lines")
    trace_portfolio = go.Scatter(x=dff["Entry time"],
                                 y=dff['Exit balance'] +
                                 dff['Pnl (incl fees)'],
                                 mode="lines")
    return (
        {
            "data": [
                go.Candlestick(
                    open=[each["entry"] for each in data],
                    close=[each["exit"] for each in data],
                    x=[each["month"] for each in data],
                    low=[each["entry"] for each in data],
                    high=[each["exit"] for each in data],
                )
            ],
            "layout": {
                "title": "Overview of Monthly performance"
            },
        },
        f"{btc_returns:0.2f}%",
        f"{strat_returns:0.2f}%",
        f"{strat_vs_market:0.2f}%",
        {
            "data": [shortbar, longbar],
            "layout": go.Layout(title="PnL vs Trade type")
        },
        {
            "data": [trace_btc],
            "layout": go.Layout(title="Daily BTC Price")
        },
        {
            "data": [trace_portfolio],
            "layout": go.Layout(title="Balance overtime")
        },
    )
def plot_candlestick_chart(ticker):
    df = pd.read_csv('~/Documents/project_ticker_data.csv')
    df.drop(columns=['Unnamed: 0'], inplace=True)
    df.set_index('ticker', inplace=True)
    ticker_df = df.loc[ticker]
    fig = go.Figure(data=[
        go.Candlestick(x=ticker_df['Date'],
                       open=ticker_df['Open'],
                       high=ticker_df['High'],
                       low=ticker_df['Low'],
                       close=ticker_df['Close'])
    ])
    #fig.show()
    return fig.show()
Beispiel #9
0
    def _create_figure(self, performance_keys: dict) -> None:
        fig = make_subplots(
            rows=4,
            cols=1,
            shared_xaxes=True,
            vertical_spacing=0.03,
            row_heights=[0.55, 0.15, 0.15, 0.15],
        )
        fig.add_trace(go.Candlestick(name='Price',
                                     xaxis='x1',
                                     yaxis='y1',
                                     showlegend=False),
                      row=1,
                      col=1)
        fig.update_layout(xaxis_rangeslider_visible=False)

        fig.add_trace(go.Bar(name='Volume',
                             showlegend=False,
                             marker={'color': 'DodgerBlue'}),
                      row=2,
                      col=1)

        for k in performance_keys:
            fig.add_trace(go.Scatter(mode='lines', name=k), row=3, col=1)

        fig.add_trace(go.Scatter(mode='lines',
                                 name='Net Worth',
                                 marker={'color': 'DarkGreen'}),
                      row=4,
                      col=1)

        fig.update_xaxes(linecolor='Grey', gridcolor='Gainsboro')
        fig.update_yaxes(linecolor='Grey', gridcolor='Gainsboro')
        fig.update_xaxes(title_text='Price', row=1)
        fig.update_xaxes(title_text='Volume', row=2)
        fig.update_xaxes(title_text='Performance', row=3)
        fig.update_xaxes(title_text='Net Worth', row=4)
        fig.update_xaxes(title_standoff=7, title_font=dict(size=12))

        self.fig = go.FigureWidget(fig)
        self._price_chart = self.fig.data[0]
        self._volume_chart = self.fig.data[1]
        self._performance_chart = self.fig.data[2]
        self._net_worth_chart = self.fig.data[-1]

        self.fig.update_annotations({'font': {'size': 12}})
        self.fig.update_layout(template='plotly_white',
                               height=self._height,
                               margin=dict(t=50))
        self._base_annotations = self.fig.layout.annotations
    def series_figure(self, records):
        rows = len(self.index_for_graph)
        fig = make_subplots(rows=rows,
                            cols=1,
                            shared_xaxes=True,
                            vertical_spacing=0.02)

        row = 1
        for i in self.index_for_graph:
            r = records[i]
            recorder = self.recorders[i]

            if isinstance(recorder, CandleRecorder):
                candle = go.Candlestick(x=r.index,
                                        open=r['open'],
                                        high=r['high'],
                                        low=r['low'],
                                        close=r['close'],
                                        name='S5')
                fig.add_trace(candle, row=row, col=1)

            if isinstance(recorder, MACDRecorder):
                macd = go.Scatter(x=r.index,
                                  y=r[recorder.macd_key],
                                  name=recorder.macd_key)
                signal = go.Scatter(x=r.index,
                                    y=r[recorder.signal_key],
                                    name=recorder.signal_key)
                fig.add_trace(macd, row=row, col=1)
                fig.add_trace(signal, row=row, col=1)

            if isinstance(recorder, ADXRecorder):
                adx = go.Scatter(x=r.index,
                                 y=r[recorder.adx_key],
                                 name=recorder.adx_key)
                plus_di = go.Scatter(x=r.index,
                                     y=r[recorder.plus_di_key],
                                     name=recorder.plus_di_key)
                minus_di = go.Scatter(x=r.index,
                                      y=r[recorder.minus_di_key],
                                      name=recorder.minus_di_key)
                fig.add_trace(adx, row=row, col=1)
                fig.add_trace(plus_di, row=row, col=1)
                fig.add_trace(minus_di, row=row, col=1)

            row += 1

        fig.update_layout(height=800, xaxis_rangeslider_visible=False)
        return fig
Beispiel #11
0
def Stock_Select(request): 
   if request.method == 'POST':
    stock = request.form.get('symb') 
    stockstdate = request.form.get('start')
    stockedate = request.form.get('end')

    stockv = yf.Ticker(stock)
    sdate = (stockstdate)
    edate = (stockedate)

    data_df = yf.download(stock, start=sdate, end=edate)
    data_df2 = data_df.reset_index(drop=False)
    #data_df.index = [x for x in range(1, len(data_df.values)+1)]
    #data_df.index.name = 'id'
    #data_df.index = data_df.index.map(str)

    data_df2.columns = [ "Date", "OPEN", "HIGH", "LOW", "CLOSE", "ADJ Close", "Volume"]
    data_df2 = data_df2.round({"OPEN": 2, "HIGH": 2, "LOW": 2, "CLOSE": 2})
#     prof = pr(data_df2)
#     prof.to_file(output_file='templates/profile.html')



    fig = go.Figure(data=[go.Candlestick(x=data_df2["Date"],
                open=data_df2['OPEN'], high=data_df2['HIGH'],
                low=data_df2['LOW'], close=data_df2['CLOSE'])
                      ])

    fig.update_layout(
     title="Requested Stock Info",
     yaxis_title=f"{stock}",
     paper_bgcolor='rgba(0,0,0,0)',
     plot_bgcolor='rgba(0,0,0,0)'
     )
    fig.update_xaxes(showgrid=False)
    fig.update_yaxes(showgrid=False)

    fig.update_layout(autosize=False, width=800, height=500)

    fig.write_html('templates/StockETL.html')

    data_df2.to_csv('../data/StockETL.csv', index = True)
   

    stock_json = data_df2.to_json(orient="records", date_format='iso')
    final_json = json.loads(stock_json)
   json.dumps(stock_json, indent=0) 
   with open('../data/Searchedstock.json', 'w') as json_file:
    json.dump(final_json, json_file)
Beispiel #12
0
def tplot_candle(transactions, absval=False, dt='day', key='bal', log=False, statistic='median', title=None):
    '''
    Produces a candlestick plot of the specified list of transactions.
    '''
    if statistic == 'median':
        statfunc = statistics.median
    else:
        statfunc = statistics.mean
    fig = go.Figure()
    dopen = []
    dhigh = []
    dlow = []
    dclose = []
    dates = sorted(list(set([t['date'] for t in transactions])))
    for d in dates:
        data = [t[key] for t in transactions if t['date'] == d]
        if absval:
            data = list(map(abs, data))
        dhigh.append(max(data))
        dlow.append(min(data))
        if len(data) == 1:
            dopen.append(data[0])
            dclose.append(data[0])
        elif len(data) == 2:
            dopen.append(max(data))
            dclose.append(min(data))
        else:
            data_avg = statfunc(data)
            data_stdev = statistics.stdev(data)
            dopen.append(data_avg + (data_stdev / 2))
            dclose.append(data_avg - (data_stdev / 2))
    fig.add_trace(go.Candlestick(
        x = dates,
        high = dhigh,
        open = dopen,
        close = dclose,
        low = dlow
    ))
    if key == 'amount':
        yt = 'Transaction Amount ($)'
    elif key == 'bal':
        yt = 'Account Balance ($)'
    fig.update_layout(
        title = title,
        xaxis_title = 'Date',
        yaxis_title = yt,
        yaxis_type = 'log' if log else 'linear'
    )
    return fig
def get_candlestick_chart(**kwargs):

    data2plot = kwargs['data2plot']

    if 'num_panels' in kwargs.keys():
        num_panels = kwargs['num_panels']
    else:
        num_panels = 1

    if 'open_price' in data2plot.columns:
        data2plot.rename(columns={'open_price': 'open'}, inplace=True)

    if 'high_price' in data2plot.columns:
        data2plot.rename(columns={'high_price': 'high'}, inplace=True)

    if 'low_price' in data2plot.columns:
        data2plot.rename(columns={'low_price': 'low'}, inplace=True)

    if 'close_price' in data2plot.columns:
        data2plot.rename(columns={'close_price': 'close'}, inplace=True)

    fig = make_subplots(rows=num_panels, cols=1)
    fig.add_trace(go.Candlestick(x=data2plot.index,
                                 open=data2plot['open'],
                                 high=data2plot['high'],
                                 low=data2plot['low'],
                                 close=data2plot['close'],
                                 name='underlying'),
                  row=1,
                  col=1)
    fig.update(layout_xaxis_rangeslider_visible=False)

    if 'main_panel_indicator_list' in kwargs.keys():
        main_panel_indicator_list = kwargs['main_panel_indicator_list']
        color_list = ['black', 'purple', 'blue']
        for i in range(len(main_panel_indicator_list)):
            fig.add_trace(go.Scatter(x=data2plot.index,
                                     y=data2plot[main_panel_indicator_list[i]],
                                     line=dict(color=color_list[i]),
                                     name=main_panel_indicator_list[i]),
                          row=1,
                          col=1)

    if 'rsi_14' in data2plot.columns:
        fig.add_trace(go.Scatter(x=data2plot.index, y=data2plot['rsi_14']),
                      row=2,
                      col=1)
        fig.update(layout_xaxis_rangeslider_visible=False)
    fig.show()
Beispiel #14
0
def plotCandlesticks():
    df = pd.read_csv('datasets/LTC.csv', parse_dates=['Date'])

    fig = go.Figure()
    fig.add_trace(
        go.Candlestick(x=df['Date'],
                       open=df['Open'],
                       high=df['High'],
                       low=df['Low'],
                       close=df['Close'],
                       name='LTC'))
    fig.update_layout(title="LTC/USDT",
                      xaxis_title="Time",
                      yaxis_title="Price")
    fig.show()
Beispiel #15
0
 def display_candle(self):
     df = pd.DataFrame(self.histo_data.values,
                       columns=['open', 'high', 'low', 'last_price'])
     df['Date'] = self.histo_data.axes[0]
     fig = go.Figure(data=[
         go.Candlestick(x=df['Date'],
                        open=df['open'],
                        high=df['high'],
                        low=df['low'],
                        close=df['last_price'])
     ])
     fig.update_layout(
         title=self.tick,
         xaxis_rangeslider_visible=False)  # Remove to add range slider
     fig.show()
    def make_plot(self):
        #Extracting data
        df = get_data("{ticker}".format(ticker=self.e1.get()),
                        start_date = self.e2.get(), end_date = self.e3.get())
        

        df.index = pd.to_datetime(df.index)

        fig = go.Figure(data=[go.Candlestick(x=df.index,
                open=df['open'],
                high=df['high'],
                low=df['low'],
                close=df['close'])])

        fig.show()
def get_candlestick_data(ticker, startdate, enddate):

    # Pull Stock Data
    stock_data = pd.DataFrame()
    stock_data = wb.DataReader(ticker,
                               data_source="yahoo",
                               start=startdate,
                               end=enddate)

    candlestick = go.Candlestick(x=stock_data.index,
                                 open=stock_data['Open'],
                                 high=stock_data['High'],
                                 low=stock_data['Low'],
                                 close=stock_data['Close'])
    save_fig(candlestick, ticker)
Beispiel #18
0
    def _plot_stock_data(df: pd.DataFrame, head: int):
        if head:
            df = df.tail(head)

        stock_data = go.Candlestick(
            x=df["day"],
            open=df["open"],
            high=df["high"],
            low=df["low"],
            close=df["close"],
            increasing_line_color="red",
            decreasing_line_color="green",
            name="stock price",
        )
        return stock_data
Beispiel #19
0
    def get_ytd_chart(self):
        """ Gets a one year candlestick chart of stock

        :return:
            Plotly chart: one year candlestick chart
        """
        df = self.get_one_year_historical_prices()
        for table in df:
            df = table[0].loc[::-1]  # reverse order of column values
            fig = go.Figure(data=[go.Candlestick(x=df['Date'],
                            open=df['Open'],
                            high=df['High'],
                            low=df['Low'],
                            close=df['Close*'])])
            fig.show()
Beispiel #20
0
def update_candlestick_plot(data):

    fig = go.Figure(data=[
        go.Candlestick(x=data['fecha'],
                       open=data['open'],
                       high=data['high'],
                       low=data['low'],
                       close=data['close'])
    ])

    fig.update_layout(xaxis_rangeslider_visible=False,
                      margin=dict(t=0, l=55, r=50, b=30),
                      template='plotly_white',
                      height=400)
    return fig
Beispiel #21
0
async def stock(ctx, symbol: str):
    symbol = symbol.upper()
    try:
        price = stocks.latest_price(symbol)
    except:
        embed = add_embed(f'Could\'t find information for "{symbol}"',
                          'check spelling and symbol!')
        await ctx.send(embed=embed)
        return
    open, high, low = stocks.get_stats(symbol)
    trend = rnd(price - open)
    trend_perc = rnd((price - open) / open * 100)
    if trend > 0:
        trend = f'+${trend}'
        trend_perc = f'+{trend_perc}%'
    else:
        trend = f'-${abs(trend)}'
        trend_perc = f'-{abs(trend_perc)}%'
    fields = [
        ('Current Price', f'${price}'),
        ('Open Price', f'${open}'),
        ('High Price', f'${high}'),
        ('Low Price', f'${low}'),
        ('Trend Today', trend),
        ('Trend Today %', trend_perc),
    ]
    o, h, l, c = stocks.get_aggregate(symbol)
    layout = go.Layout(paper_bgcolor='rgba(0,0,0,0)',
                       plot_bgcolor='rgba(0,0,0,0)',
                       width=1200,
                       height=800,
                       xaxis=go.layout.XAxis(showticklabels=False),
                       yaxis=go.layout.YAxis(color="white"))
    fig = go.Figure(data=[go.Candlestick(open=o, high=h, low=l, close=c)],
                    layout=layout)
    fig.update_layout(xaxis_rangeslider_visible=False)
    if not os.path.exists('images'):
        os.mkdir('images')
    fig.write_image("images/" + symbol + ".png")
    file = discord.File("images/" + symbol + ".png", filename='image.png')
    embed = add_embed(title=symbol,
                      description=f'Stats as of ({sdate()})',
                      fields=fields,
                      author=ctx.author,
                      inline=True,
                      image='attachment://image.png')
    await ctx.send(file=file, embed=embed)
    os.remove('images/' + symbol + '.png')
def get_candlestick_plot(df, symbol):
    #get company name
    company = st.sidebar.text_input("Company", company_name)

    # select  time using buttons on top of chart
    st.subheader('Choose date range for chart')
    #Display the close price
    st.header(company_name + ' Stock price \n')
    st.subheader(listed_at + ': ' + symbol.upper())
    fig = go.Figure(data=[
        go.Candlestick(x=df['Date'],
                       open=df['Open'],
                       high=df['High'],
                       low=df['Low'],
                       close=df['Close'])
    ])
    fig.update_xaxes(
        rangeslider_visible=True,
        rangeselector=dict(buttons=list([
            dict(count=1, label="1m", step="month", stepmode="backward"),
            dict(count=6, label="6m", step="month", stepmode="backward"),
            dict(count=1, label="YTD", step="year", stepmode="todate"),
            dict(count=1, label="1y", step="year", stepmode="backward"),
            dict(step="all")
        ])))
    fig.update_layout(title='Candlestick graph',
                      yaxis_title=symbol.upper() + ' Stock',
                      width=1150,
                      height=500,
                      shapes=[
                          dict(x0='2016-12-09',
                               x1='2016-12-09',
                               y0=0,
                               y1=1,
                               xref='x',
                               yref='paper',
                               line_width=2)
                      ],
                      annotations=[
                          dict(x='2016-12-09',
                               y=0.05,
                               xref='x',
                               yref='paper',
                               showarrow=False,
                               xanchor='left',
                               text='Increase Period Begins')
                      ])
    return fig
Beispiel #23
0
    def get_plot(self, dfp, symbol, hband, lband, atrmh, atrml):
        ''' plotly candlestick chart '''
        fig = go.Figure()
        trace1 = go.Candlestick(x=dfp.index,
                                open=dfp['Open'],
                                high=dfp['High'],
                                low=dfp['Low'],
                                close=dfp['Close'],
                                name=symbol)
        trace2 = go.Scatter(x=hband.index,
                            y=hband.values,
                            mode='lines',
                            line_color='blue',
                            name='high band')
        trace3 = go.Scatter(x=lband.index,
                            y=lband.values,
                            mode='lines',
                            line_color='blue',
                            name='low band')
        trace4 = go.Scatter(x=pd.Series(dfp.index[-1]),
                            y=[atrmh],
                            name='long_alert_value',
                            mode='markers+text',
                            marker_size=10,
                            marker_color='black',
                            marker_symbol='triangle-up',
                            text=['alert_threshold'],
                            textposition='middle right')
        trace5 = go.Scatter(x=pd.Series(dfp.index[-1]),
                            y=[atrml],
                            name='short_alert_value',
                            mode='markers+text',
                            marker_size=10,
                            marker_color='black',
                            marker_symbol='triangle-down',
                            text=['alert_threshold'],
                            textposition='middle right')
        fig.add_trace(trace1)
        fig.add_trace(trace2)
        fig.add_trace(trace3)
        fig.add_trace(trace4)
        fig.add_trace(trace5)

        fig.update(layout_xaxis_rangeslider_visible=False)
        fig.update_layout(title='Breakout Analysis: ' + symbol,
                          xaxis_title="Date",
                          yaxis_title="Price")
        return fig
Beispiel #24
0
    def parse(self, response):
        chart = []
        for i in range(
                238):  #21 useless info before + 30 days * 7 info per day
            chart.append(
                response.xpath('//span/text()')[i].get())  #get the i-th text

        open_data = []
        high_data = []
        low_data = []
        close_data = []
        month_dict = {
            "Jan": 1,
            "Feb": 2,
            "Mar": 3,
            "Apr": 4,
            "May": 5,
            "Jun": 6,
            "Jul": 7,
            "Aug": 8,
            "Sep": 9,
            "Oct": 10,
            "Nov": 11,
            "Dec": 12
        }
        dates = []
        for i in range(28, 238, 7):
            #date example: "Sep 09, 2019"
            dates.append(
                datetime(year=int(chart[i][8:]),
                         month=month_dict[chart[i][:3]],
                         day=int(chart[i][4:6])))
            open_data.append(float(chart[i + 1].replace(",", "")))
            high_data.append(float(chart[i + 2].replace(",", "")))
            low_data.append(float(chart[i + 3].replace(",", "")))
            close_data.append(float(chart[i + 4].replace(",", "")))

        fig = go.Figure(data=[
            go.Candlestick(x=dates,
                           open=open_data,
                           high=high_data,
                           low=low_data,
                           close=close_data)
        ])
        #add title, disable bottom rangeslider
        fig.update_layout(title=self.target + " Prices",
                          xaxis_rangeslider_visible=False)
        fig.show()
Beispiel #25
0
def updatePlot(securityValue, indicatorValues):
    df = (dfPool[dfPool['security'] == securityValue])
    rowWidth = [0.2 / len(indicators) for x in indicators]
    rowWidth.append(0.8)
    # rowWidth.append(0.6)
    # specs =  [[{"rowspan": 2}], [None], [{}], [{}], [{}]]
    fig = make_subplots(
        rows=len(indicators) + 1,
        cols=1,
        shared_xaxes=True,
        vertical_spacing=0.1,
        row_width=rowWidth,
        # specs=specs,
    )

    fig.add_trace(go.Candlestick(x=df['datetime'],
                                 open=df['open'],
                                 high=df['high'],
                                 low=df['low'],
                                 close=df['close'],
                                 name=securityValue),
                  row=1,
                  col=1)

    fig.update_layout(
        xaxis_rangeslider_visible=False,
        yaxis=dict(autorange=True, fixedrange=False),
        xaxis={
            'type': 'category',
            'categoryorder': 'category ascending'
        },
        # yaxis2_domain = [0, 1]
    )

    rowIndex = 2
    if (indicatorValues):  #rendering indicator plots based on dropdown
        for i in indicatorValues:
            fig.add_trace(go.Scatter(x=df['datetime'],
                                     y=df[i],
                                     mode='lines',
                                     name=i),
                          row=rowIndex,
                          col=1)
            rowIndex += 1

    figure = Currentfig = fig

    return figure
Beispiel #26
0
def plot_historical_price_chart(ticker, api_key):
    p = get_historical_prices(ticker, api_key)

    fig = go.Figure(data=[
        go.Candlestick(x=p.index,
                       open=p['open'],
                       high=p['high'],
                       low=p['low'],
                       close=p['close'])
    ])

    fig.update_layout(title="{} Stock Chart".format(ticker),
                      xaxis_title="Year",
                      yaxis_title="Price")

    fig.show()
Beispiel #27
0
def display_candlestick(value):
    df = next(gen(df))
    df2 = df.copy()
    fig = go.Figure(go.Candlestick(
        x=df['Date'],
        open=df['AAPL.Open'],
        high=df['AAPL.High'],
        low=df['AAPL.Low'],
        close=df['AAPL.Close']
    ))

    # fig.update_layout(
    #     xaxis_rangeslider_visible='slider' in value
    # )

    return fig
Beispiel #28
0
def historic_model(df):
    """
    Returns a plotly visualization of the historic stock price
    """

    fig = go.Figure(data=[
        go.Candlestick(x=df["Date"],
                       open=df["Open"],
                       high=df["High"],
                       low=df["Low"],
                       close=df["Close"])
    ],
                    layout=fig_layout)
    graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)

    return graphJSON
Beispiel #29
0
    def graph_daily_candle(empresa):
        query = f"select a.* from (select *,max(id) over (partition by ticker,date) mx_version from acoesdiario where ticker = '{empresa}')as a where mx_version = id"
        data = ServerManager().SelectAllData(query=query)

        df = pd.DataFrame.from_dict(data)

        grafico = [
            go.Candlestick(x=df['date'],
                           open=df['open'],
                           high=df['high'],
                           low=df['low'],
                           close=df['close'])
        ]
        graficoJson = json.dumps(grafico, cls=plotly.utils.PlotlyJSONEncoder
                                 )  #Transformando o grafico em json
        return graficoJson
Beispiel #30
0
    def plot(self):  # pragma: no cover
        """Item or slice

        Usage:
        >>> from rndqts.quotes.synthetic import Synthetic
        >>> quotes = Synthetic(seed=42, cached=False)[:60]
        >>> quotes.plot()  # doctest: +SKIP
        """
        df = self.data
        cndstick = go.Candlestick(x=df.index,
                                  open=df['Open'],
                                  high=df['High'],
                                  low=df['Low'],
                                  close=df['Close'])
        fig = go.Figure(data=[cndstick])
        fig.show()