Esempio n. 1
0
def plot_train_test(train_data, test_data, tickers, date_split):
    for i in range(len(tickers)):
        data = [
            go.Candlestick(x=train_data[i].index,
                           open=train_data[i]['Open'],
                           high=train_data[i]['High'],
                           low=train_data[i]['Low'],
                           close=train_data[i]['Close'],
                           name='train'),
            go.Candlestick(x=test_data[i].index,
                           open=test_data[i]['Open'],
                           high=test_data[i]['High'],
                           low=test_data[i]['Low'],
                           close=test_data[i]['Close'],
                           name='test')
        ]
        title = 'Stock data for {}'.format(tickers[i])
        layout = {
            'title':
            title,
            'showlegend':
            False,
            'shapes': [{
                'x0': date_split,
                'x1': date_split,
                'y0': 0,
                'y1': 1,
                'xref': 'x',
                'yref': 'paper',
                'line': {
                    'color': 'rgb(0,0,0)',
                    'width': 3
                }
            }],
            'annotations': [{
                'x': date_split,
                'y': 1.0,
                'xref': 'x',
                'yref': 'paper',
                'showarrow': False,
                'xanchor': 'left',
                'text': '         test data'
            }, {
                'x': date_split,
                'y': 1.0,
                'xref': 'x',
                'yref': 'paper',
                'showarrow': False,
                'xanchor': 'right',
                'text': 'train data         '
            }]
        }
        figure = go.Figure(data=data, layout=layout)
        plot(figure,
             filename='results/Stock_data_{}.html'.format(tickers[i]),
             auto_open=False)
Esempio n. 2
0
def get_points(my_data, symbol, right, selected_date):
    has_marker = {'color': f'{has_color}', 'size': 5, 'symbol': 'square'}
    hasnt_marker = {'color': f'{hasnt_color}', 'size': 5, 'symbol': 'square'}

    trace = [
        go.Candlestick(
            x=my_data.index,
            open=my_data.open,
            high=my_data.high,
            low=my_data.low,
            close=my_data.close,
            name='Daily Bars',
        ),
        go.Bar(x=my_data.index, y=my_data.volume, name='Daily Volume')
    ]

    return {
        'data':
        trace,
        'layout':
        go.Layout(
            title=
            f'Daily bars - {selected_date.strftime("%Y%M%d")} {symbol} {right} ',
            showlegend=True,
            legend=go.Legend(x=0, y=1.0),
            margin=go.Margin(l=100, r=40, t=40, b=30),
        )
    }
Esempio n. 3
0
def get_points(my_data, symbol, right, selected_date, strike):
    has_marker = {'color': f'{has_color}', 'size': 5, 'symbol': 'square'}
    hasnt_marker = {'color': f'{hasnt_color}', 'size': 5, 'symbol': 'square'}

    trace = [
        go.Candlestick(x=my_data.index,
                       open=my_data.open,
                       high=my_data.high,
                       low=my_data.low,
                       close=my_data.close,
                       name='Daily Bars',
                       xaxis='x1',
                       yaxis='y1'),
        go.Bar(x=my_data.index,
               y=my_data.volume,
               name='Daily Volume',
               xaxis='x1',
               yaxis='y2',
               marker=dict(color='rgb(158,202,225)',
                           line=dict(
                               color='rgb(8,48,107)',
                               width=1.5,
                           )),
               opacity=0.6),
    ]

    return {
        'data': trace,
    }
Esempio n. 4
0
def update_graph(stock_code):
    """ Callback for every change in Dropdown value"""
    df = get_stock_data(stock=stock_code)
    # trace_close = go.Scatter(x=df.index,
    #                          y=df.Close,
    #                          name='Close',
    #                          line={'color': "#4287f5"})

    trace_close = go.Candlestick(x=df.index,
                                 open=df.Open,
                                 close=df.Close,
                                 high=df.High,
                                 low=df.Low)

    data = [trace_close]  # You can add up more

    # Create plot layout
    layout = {
        'title':
        f'Stock price: {stock_code}',
        'showlegend':
        False,
        'xaxis':
        go.layout.XAxis(title=go.layout.xaxis.Title(text="Date"),
                        rangeslider=dict(visible=False)),
        'yaxis':
        go.layout.YAxis(title=go.layout.yaxis.Title(text="Price (USD)"))
    }

    # Create plot
    fig = dict(data=data, layout=layout)
    return fig
Esempio n. 5
0
    def uppdate_market_data(bot):
        market_data = get_market_data_via_haas(bot)
        fig = go.Figure(
            # data=[go.Scatter(x=market_data.T, y=market_data.high)])
            data=[
                go.Candlestick(x=market_data.date,
                               open=market_data.open,
                               high=market_data.high,
                               low=market_data.low,
                               close=market_data.close)
            ])
        trades = return_trades(bot)
        buy = trades[trades['orderType'] == 0]
        sell = trades[trades['orderType'] == 1]
        fig.add_trace(
            go.Scatter(x=buy.date,
                       y=buy.price,
                       mode='markers+text',
                       text=buy.price,
                       textposition='bottom center'))
        fig.add_trace(go.Scatter(x=sell.date, y=sell.price, mode='markers'))

        config = dict({'scrollZoom': True})
        fig.update_layout(
            autosize=True,
            height=1200,
            margin=dict(l=50, r=50, b=100, t=100, pad=4),
        )

        # sma = btalib.sma(market_data.high)
        # fig.add_trace(go.Scatter(x=market_data.data,y=sma))
        return fig
Esempio n. 6
0
    def plot_data(self):
        df = self.df

        kline = go.Candlestick(name="Candlestick",
                               x=df['time'],
                               open=df["open"],
                               high=df["high"],
                               low=df["low"],
                               close=df["close"])

        pc_upper = go.Scatter(x=df['time'],
                              y=df['pc_upper'],
                              line_shape='linear',
                              name="Price Channel(Upper)")

        pc_lower = go.Scatter(x=df['time'],
                              y=df['pc_lower'],
                              line_shape='linear',
                              name="Price Channel(Lower)")

        data = [kline, pc_upper, pc_lower]
        layout = go.Layout(title="Symbol:{}. Time frame:{}".format(
            self.symbol, self.interval))
        fig = go.Figure(data=data, layout=layout)

        plot(fig, filename=self.symbol)
def candles(df, open, high, low, close, time, title, base_currency):
    """
    Generates Candlesticks


    :param df:
    :param open:
    :param high:
    :param low:
    :param close:
    :param time:

    :return:
    """

    data = [
        go.Candlestick(x=df[time],
                       open=df[open],
                       high=df[high],
                       low=df[low],
                       close=df[close])
    ]

    layout = go.Layout(title=title,
                       yaxis=dict(title=base_currency),
                       xaxis=dict(title='Timestamp'))

    fig = go.Figure(data=data, layout=layout)

    return fig
Esempio n. 8
0
def history_view(id):
    if not session.get('logged_in'):
        return render_template('login.html')
    else:
        hist = bursData.history_pd(int(id))
        market = bursData.market_pd()
        symbol = market.loc[market['id'] == str(id)]['symbol'].values[0]
        name = market.loc[market['id'] == str(id)]['name'].values[0]

        hist['date'] = pd.to_datetime(
            hist['date']).apply(lambda x: jdatetime.datetime.fromgregorian(
                datetime=x).strftime('%Y-%m-%d'))

        Candlestick = go.Candlestick(x=hist['date'],
                                     open=hist['first_price'],
                                     high=hist['max_price'],
                                     low=hist['min_price'],
                                     close=hist['close_price'])
        data = [Candlestick]
        shapes = {"shapes": []}
        graphJSON = json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder)
        shapesJSON = json.dumps(shapes, cls=plotly.utils.PlotlyJSONEncoder)

        return render_template("history.html",
                               plot=graphJSON,
                               layout=shapesJSON,
                               hist=hist,
                               symbol=symbol,
                               name=name,
                               id=int(id))
Esempio n. 9
0
def get_strength_BBANDS(data):

    op = talib.BBANDS(data['Close'])
    tp = (data['High'] + data['Low'] + data['Close']) / 3.0

    list_traces = []
    list_traces.append(go.Scatter(x=data['Date'], y=op[0], name='macd'))
    list_traces.append(go.Scatter(x=data['Date'], y=op[1], name='signal line'))
    list_traces.append(
        go.Scatter(x=data['Date'], y=op[2], name='momentum histogram'))
    list_traces.append(
        go.Candlestick(x=data['Date'],
                       open=data['Open'],
                       high=data['High'],
                       low=data['Low'],
                       close=data['Close']))
    fig = go.Figure(data=list_traces)
    plot(fig)
    tp = np.array(tp)
    op = np.array(op)
    strength = 0
    if tp[-1] > op[1][-1]:
        strength = (op[1][-1] - tp[-1]) * 10 / (op[0][-1] - op[1][-1])
    else:
        strength = (tp[-1] - op[1][-1]) * 10 / (op[2][-1] - op[1][-1])
    print(strength)
    return strength, fig
Esempio n. 10
0
def update_figure(n1, n2, n3, n4, n5, click_cache, t1, t2, t3, t4, t5, r1, r2,
                  r3, r4, r5):
    click_cache = np.array(
        list(map(lambda n: int(n), click_cache[0].split(' '))))
    new_clicks = np.array([n1, n2, n3, n4, n5])
    idx = np.argmax(new_clicks - click_cache)
    t = np.array([t1, t2, t3, t4, t5])[idx]
    r = np.array([r1, r2, r3, r4, r5])[idx]
    df = load_ts(t, r)
    layout = go.Layout(title=t,
                       paper_bgcolor='rgb(0,0,0)',
                       plot_bgcolor='rgba(48, 48, 48, 0.3)',
                       margin={
                           'l': 25,
                           'b': 0,
                           't': 40,
                           'r': 0
                       },
                       font={'color': 'white'})
    data = [
        go.Candlestick(x=df.index,
                       open=df['Open'],
                       high=df['High'],
                       low=df['Low'],
                       close=df['Close'])
    ]

    return go.Figure(data, layout=layout)
Esempio n. 11
0
def candlestick(df, title="stock_candlestick"):
    """
  df : pandas.DataFrame
    OHLCV data
  title : str
     Title of the chart
  """
    #Configures traces for prices and volume
    ohlc = go.Candlestick(x=df["date"],
                          open=df["open"],
                          high=df["high"],
                          low=df["low"],
                          close=df["close"])
    volume = go.Bar(x=df.date, y=df["volume"])

    #configure subplot with a grid of 4 rows and 1 column. OHLC will take 3 rows heigh
    fig = make_subplots(rows=4,
                        cols=1,
                        shared_xaxes=True,
                        shared_yaxes=True,
                        specs=[[{
                            'rowspan': 3
                        }], [None], [None], [{}]])
    #Add the 2 subplots
    fig.append_trace(ohlc, 1, 1)
    fig.append_trace(volume, 4, 1)

    fig['layout'].update(title=f'{title}',
                         xaxis=dict(rangeslider=dict(visible=False)))

    fig.show()
Esempio n. 12
0
def g_velas(p0_de):
    """
    :param p0_de: data frame con datos a graficar
    :return fig:

    p0_de = datos_dd
    p1_pa = 'sell'
    datos_dd = pd.DataFrame({'timestamp': [], 'open': [], 'high': [], 'low': [], 'close': []}, index=[])
    """

    p0_de.columns = [
        list(p0_de.columns)[i].lower() for i in range(0, len(p0_de.columns))
    ]

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

    fig.update_layout(
        title=dict(x=0.5, text='Precios Historicos '),
        xaxis=dict(title_text='Hora del dia'),  # Etiquetas de eje x
        yaxis=dict(title_text='Precio del EurUsd'))

    return fig
Esempio n. 13
0
def plot():
    symbol = request.form["symbol"]
    duration = int(request.form["months"])

    data = yf.download(symbol)

    latest_date = data.iloc[-1].name
    start_date = latest_date - relativedelta(months=duration)
    df = data[start_date:latest_date]

    df.reset_index(inplace=True)

    fig = go.Figure(data=[
        go.Candlestick(x=df['Date'],
                       open=df['Open'],
                       high=df['High'],
                       low=df['Low'],
                       close=df['Close'])
    ])
    fig.update_layout(title="Chart for Stock : " + symbol,
                      width=1000,
                      height=700,
                      yaxis_title="Prices",
                      legend_title=symbol,
                      font=dict(family="Courier New, monospace",
                                size=18,
                                color="RebeccaPurple"))
    graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)
    return render_template('home.html', graphJSON=graphJSON)
Esempio n. 14
0
def plot_candlestick(index):
    data_layout = go.Figure(data=[
        go.Candlestick({
            u"x": indices_ohlcvs[index].index,
            u"open": indices_ohlcvs[index][col_o],
            u"high": indices_ohlcvs[index][col_h],
            u"low": indices_ohlcvs[index][col_l],
            u"close": indices_ohlcvs[index][col_c],
            u"name": index
        })
    ])

    data_layout.update_layout(std_layout(index=index))

    filename = os.path.join(DirectoryElements.plots_subdir,
                            index + u" candlestick.html")

    plotly.offline.plot(data_layout,
                        filename=filename,
                        auto_open=False,
                        image_filename=index + u" candlestick",
                        include_mathjax=u"cdn",
                        auto_play=False)

    return filename
Esempio n. 15
0
def candle_stick():

    sql2 = "Select * from dbo.BitcoinVal Order BY dateB ,dboTime "
    df2 = pd.read_sql(sql2, cnxn)

    X = df2.timeDate.values[-20:]
    open_data = df2.openingPrice.values[-20:]
    close_data = df2.closePrice.values[-20:]
    low_data = df2.lowPrice.values[-20:]
    high_data = df2.highPrice.values[-20:]

    data = go.Candlestick(
        x=(list(X)),
        open=list(open_data),
        high=list(high_data),
        low=list(low_data),
        close=list(close_data),

            )
    rangeslider= dict(
        visible=False
    )
    return {'data': [data],'layout' : go.Layout(xaxis=dict(rangeslider=dict(visible=False)),
                                                title="CandleStick",
                                                showlegend=False,
                                                font={'color': app_colors['text']},
                                                plot_bgcolor=app_colors['background'],
                                                paper_bgcolor=app_colors['background'],
                                                )}
Esempio n. 16
0
def build_candlestick(df, real_time):
    # create figure using 'OHLC' Tesla data
    fig = go.Figure(data=[
        go.Candlestick(
            x=real_time,
            open=df['o'],
            high=df['h'],
            low=df['l'],
            close=df['c'],
            increasing_line_color='#00FE35',
            decreasing_line_color='#fe0d00',
        )
    ])

    fig.update_layout(
        title=dict(text='Tesla (TSLA) Candlestick Chart',
                   font=dict(size=14, color='white')),
        margin=go.layout.Margin(
            l=25,  #left margin
            r=25,  #right margin
            b=20,  #bottom margin
            t=100,  #top margin
        ),
        height=500,
        title_x=0.025,
        title_y=.85,
        template='plotly_dark',
        modebar=dict(color='rgb(17, 17, 17)', activecolor='rgb(17, 17, 17)'),
    )

    chart = plotly.offline.plot(fig, include_plotlyjs=False, output_type="div")

    return chart
Esempio n. 17
0
def stosk_view(id):
    if not session.get('logged_in'):
        return render_template('login.html')
    else:
        market = bursData.market_pd()
        symbol = market.loc[market['id'] == str(id)]['symbol'].values[0]
        name = market.loc[market['id'] == str(id)]['name'].values[0]
        groupid = market.loc[market['id'] == str(id)]['group_id'].values[0]
        group_list = market.loc[market['group_id'] == groupid]
        day_price_list = bursData.dayprice_pd(int(id))
        general = bursData.general_dayinfo_pd(id)
        saf = bursData.saf_pd(id)

        Candlestick = go.Candlestick(x=day_price_list['time'],
                                     open=day_price_list['open_price'],
                                     high=day_price_list['high_price'],
                                     low=day_price_list['low_price'],
                                     close=day_price_list['close_price'])
        data = [Candlestick]
        shapes = {"shapes": []}
        graphJSON = json.dumps(data, cls=plotly.utils.PlotlyJSONEncoder)
        shapesJSON = json.dumps(shapes, cls=plotly.utils.PlotlyJSONEncoder)

        return render_template("stock.html",
                               plot=graphJSON,
                               layout=shapesJSON,
                               id=id,
                               name=name,
                               symbol=symbol,
                               group_list=group_list,
                               saf=saf,
                               general=general,
                               day_price_list=day_price_list)
Esempio n. 18
0
def get_plot_candles(candles, price_type='mid'):
    quotes = {
        'open': [],
        'high': [],
        'low': [],
        'close': [],
        'time': [],
        'volume': []
    }

    for i, candle in enumerate(candles):
        quotes['open'].append(float(candle[0]))
        quotes['close'].append(float(candle[1]))
        quotes['high'].append(float(candle[2]))
        quotes['low'].append(float(candle[3]))
        quotes['time'].append(i)
        quotes['volume'].append(float(candle[6]))

    trace = go.Candlestick(x=quotes['time'],
                           open=quotes['open'],
                           high=quotes['high'],
                           low=quotes['low'],
                           close=quotes['close'])

    return trace
Esempio n. 19
0
def get_candlestick_subplot(df, indicator=[]):
    '''
    Input1: df ตารางข้อมูลของหุ้นที่สนใจ
    Input2: list ชื่อของ column/indicator ที่ต้องการตีเส้นไปบนกราฟใหม่เลย เช่น ['indicator1','indicator2']
    Output: กราฟ candlestick 
    Description: นำตารางมาสร้างกราฟ candlestick และกราฟ indicator แบบบนล่างตามแนวนอน ซึ่งแต่ละเส้น indicator จะมีสีจาก function ของการกำหนดสีของเส้นให้ต่างกัน
    '''
    # สร้าง layout ของกราฟ โดยกำหนดให้มี 2 rows กับ 1 column ใช้แกนเวลาร่วมกัน และทำให้กราฟสองกราฟติดกัน
    fig = make_subplots(rows=2,
                        cols=1,
                        shared_xaxes=True,
                        vertical_spacing=0.02)

    # กราฟแท่งเทียนหลัก โดยกำหนดให้อยู่ row ล่างสุด
    fig.append_trace(
        go.Candlestick(x=df['Date'],
                       open=df['Open'],
                       high=df['High'],
                       low=df['Low'],
                       close=df['Close'],
                       name="Price"), 2, 1)

    # กราฟของ indicator โดยกำหนดให้อยู่ row บนกราฟแท่งเทียนหลัก
    for i in range(len(indicator)):
        fig.add_trace(
            go.Scatter(x=df["Date"],
                       y=df[indicator[i]],
                       name=indicator[i],
                       line=dict(color=color_list()[i], width=1)), 1, 1)

    fig.show()
Esempio n. 20
0
def plot_candles(candles, price_type='mid'):
    quotes = {
        'open': [],
        'high': [],
        'low': [],
        'close': [],
        'time': [],
        'volume': []
    }

    for candle in candles:
        quotes['open'].append(float(candle[price_type]['o']))
        quotes['high'].append(float(candle[price_type]['h']))
        quotes['low'].append(float(candle[price_type]['l']))
        quotes['close'].append(float(candle[price_type]['c']))
        quotes['time'].append(candle['time'][:19])
        quotes['volume'].append(int(candle['volume']))

    trace = go.Candlestick(x=quotes['time'],
                           open=quotes['open'],
                           high=quotes['high'],
                           low=quotes['low'],
                           close=quotes['close'])

    data = [trace]

    plotly.offline.plot(data, filename="candles_{}.html")
Esempio n. 21
0
def longShortPositionRatio(select_time,select_code):
    # 多空比
    # figure_dict = figure_dict
    ndf = read_mongo(collection=select_time,query = {'code':f'{select_code}'})
    ndf = ndf.sort_values('time_key' )
    # yield_result[2].reverse()
    trace = go.Scatter(
        x=list(ndf['time_key']),
        y=list(ndf['ratios']),
        name='比率',
        yaxis='y2'

    )
    trace_kline = go.Candlestick(x=list(ndf['time_key']),
                           open=ndf['open'],
                           high=ndf['high'],
                           low=ndf['low'],
                           close=ndf['close'],
                            hovertext = ndf['str_time'],
                           name='kline')



    return {
        'data': [trace_kline,trace],
        'layout': dict(
            title="多空比",

            height=800,
            yaxis2=dict(anchor='x', overlaying='y', side='right')  #
        )
    }
Esempio n. 22
0
def g_velas(p0_de):
    """
    :param p0_de: data frame con datos a graficar
    :return fig:

    p0_de = datos_dd
    p1_pa = 'sell'
    datos_dd = pd.DataFrame({'timestamp': [], 'open': [], 'high': [], 'low': [], 'close': []}, index=[])
    """

    p0_de.columns = [
        list(p0_de.columns)[i].lower() for i in range(0, len(p0_de.columns))
    ]

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

    fig.update_layout(margin=go.layout.Margin(l=50, r=50, b=20, t=50, pad=0),
                      title=dict(x=0.5, y=1, text='Precios Historicos OHLC'),
                      xaxis=dict(title_text='Hora del dia',
                                 rangeslider=dict(visible=False)),
                      yaxis=dict(title_text='Precio del EurUsd'))

    fig.layout.autosize = False
    fig.layout.width = 940
    fig.layout.height = 520

    return fig
Esempio n. 23
0
    def plotData(self):
        df = self.df

        candle = go.Candlestick(x=df['time'],
                                open=df['open'],
                                close=df['close'],
                                high=df['low'],
                                low=df['low'],
                                name="Candlesticks")
        #plot MAs
        fsma = go.Scatter(x=df['time'],
                          y=df['fast_sma'],
                          name="Fast SMA",
                          line=dict(color=('rgba(102, 207, 255, 50)')))
        ssma = go.Scatter(x=df['time'],
                          y=df['slow_sma'],
                          name="Slow SMA",
                          line=dict(color=('rgba(255, 207, 102, 50)')))

        data = [candle, ssma, fsma]

        #display
        layout = go.Layout(title=self.symbol)
        fig = go.Figure(data=data, layout=layout)

        plot(fig, filename=self.symbol)
Esempio n. 24
0
    def draw_kline(self, plotly_layout=None, annotation_df=None, render='html', file_name=None, width=None, height=None,
                   title=None, keep_ui_state=True, indicators=[], property_map=None, **kwargs):
        data = []
        for entity_id, df in self.normal_data.entity_map_df.items():
            entity_type, _, code = decode_entity_id(entity_id)

            trace_name = '{}_kdata'.format(code)

            if entity_type == 'stock':
                open = df.loc[:, 'qfq_open']
                close = df.loc[:, 'qfq_close']
                high = df.loc[:, 'qfq_high']
                low = df.loc[:, 'qfq_low']
            else:
                open = df.loc[:, 'open']
                close = df.loc[:, 'close']
                high = df.loc[:, 'high']
                low = df.loc[:, 'low']

            data.append(
                go.Candlestick(x=df.index, open=open, close=close, low=low, high=high, name=trace_name, **kwargs))

            # append indicators
            for indicator in indicators:
                if indicator in df.columns:
                    trace_name = '{}_{}'.format(code, indicator)
                    ydata = df.loc[:, indicator].values.tolist()
                    data.append(go.Scatter(x=df.index, y=ydata, mode='lines', name=trace_name))

        return self.show(plotly_data=data, plotly_layout=plotly_layout, annotation_df=annotation_df, render=render,
                         file_name=file_name, width=width,
                         height=height, title=title, keep_ui_state=keep_ui_state)
Esempio n. 25
0
def get_simple_candlestick():
    data = get_data()
    x, y, z, w, k = [], [], [], [], []

    for item in data:
        x.append(item['date']),
        y.append(item['open']),
        z.append(item['high']),
        w.append(item['low']),
        k.append(item['close'])

    trace1 = go.Candlestick(x=x, open=y, high=z, low=w, close=k)
    # trace = go.Ohlc(
    #     x=data['date'],
    #     open = data['open'],
    #     high = data['high'],
    #     low = data['low'],
    #     close = data['close']
    # )

    layout = go.Layout(
        # autosize=True,
        # width = 800,
        # height=900,
        xaxis=dict(autorange=True),
        yaxis=dict(autorange=True))
    plot_data = [trace1]
    figure = go.Figure(data=plot_data, layout=layout)
    plot_div = plot(figure, output_type='div', include_plotlyjs=False)
    return plot_div
Esempio n. 26
0
def get_graph(search, start):
    try:
        sid = search
        sd = start
        ed = datetime.datetime.now()
        df = yf.download(sid, start, ed)
        df.columns = ['high', 'low', 'open', 'close', 'volume', 'adj close']
        SMA5 = df['close'].rolling(5).mean()
        SMA10 = df['close'].rolling(10).mean()
        SMA20 = df['close'].rolling(20).mean()
        SMA60 = df['close'].rolling(60).mean()
        trace = go.Candlestick(x=df.index,
                               open=df['open'],
                               high=df['high'],
                               low=df['low'],
                               close=df['close'],
                               name='K')
        s5 = go.Scatter(x=SMA5.index, y=SMA5.values, name='5MA')
        s10 = go.Scatter(x=SMA10.index, y=SMA10.values, name='10MA')
        s20 = go.Scatter(x=SMA20.index, y=SMA20.values, name='20MA')
        s60 = go.Scatter(x=SMA60.index, y=SMA60.values, name='60MA')
        data = [trace, s5, s10, s20, s60]
        layout = {'title': sid}
        fig = dict(data=data, layout=layout)
        po.plot(fig,
                filename='templates/StockMarket_page.html',
                auto_open=False)
        return True
    except:
        print("Failure")
        return False
Esempio n. 27
0
def plotly_candlestick_single_currency(symbol, df_candle, ema_list):
    """Uses plotly library to plot candlestick for each currency
    """
    pio.renderers.default = 'browser'

    data = [
        go.Candlestick(x=df_candle['Date'],
                       open=df_candle['Open'],
                       high=df_candle['High'],
                       low=df_candle['Low'],
                       close=df_candle['Close']),
        go.Scatter(x=(ema_list[0]['ema8']).loc[:, 'Date'],
                   y=(ema_list[0]['ema8']).loc[:, 'Close'],
                   line=dict(color='orange', width=1),
                   name='EMA8'),
        go.Scatter(x=(ema_list[1]['ema13']).loc[:, 'Date'],
                   y=(ema_list[1]['ema13']).loc[:, 'Close'],
                   line=dict(color='red', width=1),
                   name='EMA13'),
        go.Scatter(x=(ema_list[2]['ema21']).loc[:, 'Date'],
                   y=(ema_list[2]['ema21']).loc[:, 'Close'],
                   line=dict(color='blue', width=1),
                   name='EMA21')
    ]

    layout = {'title': symbol}
    figSignal = go.Figure(data=data, layout=layout)
    rangebreaks = [dict(enabled=True)]
    figSignal.update_layout(title=symbol)
    figSignal.update_xaxes(rangebreaks=rangebreaks)
    figSignal.show()
Esempio n. 28
0
def adjust_ranges(ticker, xSliderValue):
    global data
    global layout
    global tickPadding

    df = get_price_data(ticker, PERIODICITY)

    firstTrace = go.Candlestick(x=df.index,
                                open=df.Open,
                                high=df.High,
                                low=df.Low,
                                close=df.Close)

    data = [firstTrace]

    xMinAdjusted = keepInXAxisBounds(xSliderValue[0])
    xMaxAdjusted = keepInXAxisBounds(xSliderValue[1])

    xminDate = utc_milleseconds_to_date(xMinAdjusted)
    xmaxDate = utc_milleseconds_to_date(xMaxAdjusted)

    xminChartValue = to_unix_microseconds(xminDate) + chartShift
    xmaxChartValue = to_unix_microseconds(xmaxDate) + chartShift

    newYRange = findPriceExtreme(df, xminDate, xmaxDate)
    newRangeLow = round(newYRange[0], 4) - tickPadding
    newRangeHigh = round(newYRange[1], 4) + tickPadding

    layout['xaxis']['range'] = [xminChartValue, xmaxChartValue]
    layout['yaxis']['range'] = [newRangeLow, newRangeHigh]

    figure = go.Figure(data=data, layout=layout)

    return figure
def velas_japonesas(df_final):
    companies = [
        "acciona", "acerinox", "acs", "atresmedia", "banco_sabadell",
        "bankinter", "bbva", "bme", "caixabank", "colonial", "enagas", "fcc",
        "ferrovial", "grifols", "iberdrola", "inditex", "indra", "mapfre",
        "mediaset", "naturgy", "red_electrica", "repsol", "sacyr", "santander",
        "siemens_gamesa", "telefonica", "bitcoin"
    ]
    comp = input(
        "\nIntroduce the name of the company you would like to plot: ")
    comp = comp.lower()
    if comp in companies:
        df_subset = df_final[df_final["company"] == comp]
        print("\nrange: {0}  -  {1}".format(df_subset["Date"].values[0],
                                            df_subset["Date"].values[-1]))
        start_date = input("\nIntroduce start date: ")
        end_date = input("\nIntroduce end date: ")
        df_subset5 = df_subset[(df_subset['Date'] > start_date)
                               & (df_subset['Date'] <= end_date)]

    else:
        print("Error, the selected company is not included.")

    trace = go.Candlestick(x=df_subset5['Date'],
                           open=df_subset5['Open'],
                           high=df_subset5['High'],
                           low=df_subset5['Low'],
                           close=df_subset5['Close'])
    data = [trace]
    py.iplot(data, filename='simple_candlestick')
    import webbrowser
    url = "https://plot.ly/~lgarciaco1/0"
    webbrowser.open(url)
Esempio n. 30
0
    def candle_stick(self, period="day"):  #日K线图
        #默认获取日k,如果period不为日k,则获取对应值
        if period == "周k":
            self.stock1 = pro.weekly(ts_code=self.stock1_code,
                                     start_date=self.start_date,
                                     end_date=self.end_date)
        elif period == "月k":
            self.stock1 = pro.monthly(ts_code=self.stock1_code,
                                      start_date=self.start_date,
                                      end_date=self.end_date)

        strdate = self.stock1['trade_date'].tolist()
        #日期字符串转时间序列
        date = []
        for i in strdate:
            X = datetime.strptime(i, '%Y%m%d')
            date.append(X)
        candle_trace = go.Candlestick(
            x=date,
            open=self.stock1.open,
            high=self.stock1.high,
            low=self.stock1.low,
            close=self.stock1.close,
            increasing=dict(line=dict(color='#ff0000')),
            decreasing=dict(line=dict(color='#00ff00')),
            name=self.name1)
        candle_data = [candle_trace]
        candle_layout = {'title': self.name1, 'yaxis': {'title': '价格'}}
        candle_fig = dict(data=candle_data, layout=candle_layout)
        div = pyplt(candle_fig,
                    output_type='div',
                    include_plotlyjs=False,
                    auto_open=False,
                    show_link=False)
        return div