Exemple #1
0
def plot_bokeh(df, ticker):
    p = figure(width=800, height=400, title=ticker.upper(), tools="")

    hover = HoverTool(tooltips="""
    <div>
    <table>
    <tr><td class="ttlab">Date:</td><td>@date_str</td></tr>
    <tr><td class="ttlab">Close:</td><td>@close_str</td></tr>
    </table>
    </div>
    """)

    hover.mode = 'vline'
    hover.line_policy = 'nearest'
    p.add_tools(hover)

    crosshair = CrosshairTool()
    crosshair.dimensions = 'height'
    crosshair.line_color = "#ffffff"
    p.add_tools(crosshair)

    dfcds = ColumnDataSource(df)
    p.line('date', 'close', source=dfcds, color="#44ddaa")

    p.xaxis.formatter = DatetimeTickFormatter(days=["%d %b"])
    p.x_range = Range1d(df['date'].min(), df['date'].max())

    p.toolbar.logo = None
    p.toolbar_location = None

    return p
def _add_vlinked_crosshairs(fig1, fig2, x_values):
    cross1 = CrosshairTool(dimensions="height")
    cross2 = CrosshairTool(dimensions="height")
    fig1.add_tools(cross1)
    fig2.add_tools(cross2)
    js_move = '''
        if(cb_obj.x >= fig.x_range.start && cb_obj.x <= fig.x_range.end &&
           cb_obj.y >= fig.y_range.start && cb_obj.y <= fig.y_range.end)
        {
            cross.spans.height.computed_location = cb_obj.sx
            
            // determine closest point in list of x_values in order to render 
            // the current position when hovering over time series plots
            var closest = x_values.reduce(function (prev, curr) {
                return (Math.abs(curr - cb_obj.x) < Math.abs(prev - cb_obj.x) ? curr : prev);
            });
            var index = x_values.indexOf(closest);
            
            // call rendering function, defined in activity_map.html
            render_position(index);
        }
        else
        {
            cross.spans.height.computed_location = null
        }
    '''
    js_leave = 'cross.spans.height.computed_location = null'
    args = {'cross': cross2, 'fig': fig1, "x_values": x_values}
    fig1.js_on_event('mousemove', CustomJS(args=args, code=js_move))
    fig1.js_on_event('mouseleave', CustomJS(args=args, code=js_leave))
    args = {'cross': cross1, 'fig': fig2, "x_values": x_values}
    fig2.js_on_event('mousemove', CustomJS(args=args, code=js_move))
    fig2.js_on_event('mouseleave', CustomJS(args=args, code=js_leave))
Exemple #3
0
def fn_main():
    df = pd.DataFrame(AAPL)[:2000]
    df["date"] = pd.to_datetime(df["date"])
    df['ToolTipDates'] = df.date.map(
        lambda x: x.strftime("%y-%m-%d"))  # Saves work with the tooltip later

    # print(df.head(3))

    TOOL_k = "pan,xwheel_zoom,ywheel_zoom,box_zoom,reset"
    TOOL_v = "pan,ywheel_zoom"
    TOOL_m = "pan,ywheel_zoom"

    p_k = figure(x_axis_type="datetime",
                 tools=TOOL_k,
                 plot_width=1504,
                 plot_height=600)  # title = "MSFT Candlestick") # hei 880
    p_v = figure(x_axis_type="datetime",
                 tools=TOOL_v,
                 plot_width=1504,
                 plot_height=160)  # title="volume"
    p_m = figure(x_axis_type="datetime",
                 tools=TOOL_m,
                 plot_width=1504,
                 plot_height=200)  # hei 880

    p_k.add_tools(CrosshairTool(line_color='#999999'))
    p_m.add_tools(CrosshairTool(line_color='#999999'))
    p_v.add_tools(CrosshairTool(line_color='#999999'))

    p_k.x_range = p_v.x_range = p_m.x_range  # 3 link must at one line
    p_k.xaxis.visible = p_v.yaxis.visible = p_v.xaxis.visible = False

    df['ma20'] = [0.0 for i in range(len(df))]
    fn_ma(df, 'ma20', 20)

    df['long'] = [0.0 for i in range(len(df))]
    df['short'] = [0.0 for i in range(len(df))]
    df['diff'] = fn_ema(df, 'close', 'short', 12) - fn_ema(
        df, 'close', 'long', 26)
    df['dea'] = fn_ema(df, 'diff', 'dea', 9)
    df['macd'] = 2 * (df['diff'] - df['dea'])

    all_source = ColumnDataSource(df)
    tbl_bi = pd.DataFrame(columns=('date', 'price'))

    fn_plot_kline(df, p_k, all_source)
    fn_plot_fenbi(df, p_k, tbl_bi)
    fn_plot_segmt(p_k, tbl_bi)
    fn_plot_volume(df, p_v)
    fn_plot_macd(df, p_m, all_source)

    output_file("chan.html", title="chan", mode='inline')
    grid = gridplot([[p_k], [p_v], [p_m]], merge_tools=False, responsive=True)
    grid.sizing_mode = 'stretch_both'
    show(grid)
    pass
Exemple #4
0
 def _set_linked_crosshairs(self, figures):
     '''
     Link crosshairs across all figures
     src:
     https://stackoverflow.com/questions/37965669/how-do-i-link-the-crosshairtool-in-bokeh-over-several-plots
     '''
     crosshair_shared = CrosshairTool(dimensions='height')
     for f in figures:
         crosshair = CrosshairTool(dimensions='width')
         f.figure.add_tools(crosshair, crosshair_shared)
Exemple #5
0
def bokehplot(df_1, ticker):
    """Create a time-series line plot in Bokeh."""
    p = figure(width=600, height=300, title=ticker.upper(), tools="")

    hover = HoverTool(tooltips="""
    <div>
    <table>
    <tr><td class="ttlab">Date:</td><td>@date_str</td></tr>
    <tr><td class="ttlab">Close:</td><td>@close</td></tr>
    </table>
    </div>
    """)

    hover.mode = 'vline'
    hover.line_policy = 'nearest'
    p.add_tools(hover)

    crosshair = CrosshairTool()
    crosshair.dimensions = 'height'
    crosshair.line_color = "#ffffff"
    p.add_tools(crosshair)

    dfcds = ColumnDataSource(df_1)
    p.line('date', 'close', source=dfcds, color="#44ddaa")

    p.xaxis.formatter = DatetimeTickFormatter(days=["%d %b"])
    p.x_range = Range1d(df_1['date'].min(), df_1['date'].max())

    p.toolbar.logo = None
    p.toolbar_location = None

    # Style plot
    p.background_fill_color = "#234567"
    p.border_fill_color = "#234567"
    p.title.text_color = "#ffffff"
    p.title.text_font_size = "1.25em"
    p.axis.major_label_text_color = "#ffffff"
    p.axis.major_label_text_font_size = "0.875em"
    p.axis.axis_line_color = "#ffffff"
    p.axis.major_tick_line_color = "#ffffff"
    p.axis.minor_tick_line_color = "#ffffff"
    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_alpha = 0.5
    p.ygrid.grid_line_dash = [4, 6]
    p.outline_line_color = None
    p.yaxis.axis_label = "Closing price"
    p.yaxis.axis_label_text_color = "#ffffff"
    p.yaxis.axis_label_text_font_size = "1em"
    p.yaxis.axis_label_text_font_style = "normal"
    p.yaxis.axis_label_standoff = 12

    return p
Exemple #6
0
def make_plot(yname,
              line_color,
              tbs=True,
              above_axis=False,
              below_axis=True,
              left_axis=True,
              right_axis=False,
              border_fill_color="white",
              toolbar_location_index=0,
              plot_width=600,
              plot_height=300):
    plot = Plot(x_range=DataRange1d(),
                y_range=DataRange1d(),
                border_fill_color=border_fill_color,
                toolbar_location=toolbar_locations[toolbar_location_index],
                plot_width=plot_width,
                plot_height=plot_height,
                min_border=10,
                toolbar_sticky=tbs,
                sizing_mode='scale_width')
    plot.add_glyph(source, Line(x="x", y=yname, line_color=line_color))
    plot.add_tools(PanTool(), BoxSelectTool(), CrosshairTool(), ResetTool())
    plot = add_axes(plot,
                    below_axis=below_axis,
                    left_axis=left_axis,
                    right_axis=right_axis,
                    above_axis=above_axis)
    return plot
 def add_custom_tools(self):
     from bokeh.models import HoverTool, CrosshairTool
     hover = HoverTool(tooltips=[("x", "$x"), ("y", "$y")],
                       mode='vline',
                       renderers=self.lines)
     crosshair = CrosshairTool()
     self.plot.add_tools(hover, crosshair)
Exemple #8
0
def plotTraces(et,x='td',y = 'gx',query = '',showplot = True,width=1400,height=800):
    from bokeh.plotting import figure,show
    from bokeh.models import Span, CrosshairTool, HoverTool, ResetTool, PanTool, BoxZoomTool,WheelZoomTool
    from bokeh.transform import factor_cmap
    from bokeh.palettes import Spectral6


    TOOLS = [CrosshairTool(dimensions='both'),
             HoverTool(),PanTool(),BoxZoomTool(),
             ResetTool()]
    if type(et) != list:
        et = [et]
    p = figure()
    for ix,e in enumerate(et):
        #et[ix] = e.query(query) 
        et[ix]['group'] = str(ix)
        #et[ix] = et[ix][[field,'td','group']]

        
        
    tmp = pd.concat(et,ignore_index=True,)
    if len(query)>0:
        tmp = tmp.query(query)
     #   if figure:
            #plt.figure()
    if tmp.empty:
        raise 'Warning: No element left to plot'
    p = figure(width=width,tools=TOOLS,height=height)
    p.circle(x=x,y=y,source = tmp,legend='group',color=factor_cmap('group',factors=['0','1','2','3','4'], palette=Spectral6))
    if showplot:
        show(p)        
    return(p)
Exemple #9
0
def addLinkedCrosshairs(plots,dimensions='both'):
	"""
	plots: list of figures
	"""
	js_move = '''	start = fig.x_range.start;
					end = fig.x_range.end;
					if(cross.dimensions==="both" || cross.dimensions==="height"){
						if(cb_obj.x>=start && cb_obj.x<=end && cb_obj.y>=start && cb_obj.y<=end)
							{ cross.spans.height.computed_location=cb_obj.sx }
						else { cross.spans.height.computed_location = null }
					}
					if(cross.dimensions==="both" || cross.dimensions==="width"){
						if(cb_obj.y>=start && cb_obj.y<=end && cb_obj.x>=start && cb_obj.x<=end)
							{ cross.spans.width.computed_location=fig.plot_height-cb_obj.sy  }
						else { cross.spans.width.computed_location=null }
					}'''
	js_leave = '''	if(cross.dimensions==="both" || cross.dimensions==="height"){cross.spans.height.computed_location=null}; 
					if(cross.dimensions==="both" || cross.dimensions==="width"){cross.spans.width.computed_location=null}'''

	figures = plots[:]
	for plot in plots:
		crosshair = CrosshairTool(dimensions=dimensions)
		plot.add_tools(crosshair)
		for figure in figures:
			if figure != plot:
				args = {'cross': crosshair, 'fig': figure}
				figure.js_on_event('mousemove', CustomJS(args = args, code = js_move))
				figure.js_on_event('mouseleave', CustomJS(args = args, code = js_leave))
Exemple #10
0
def graphtraceoverlay(trace, new_trace):
    x_range = range(0, len(new_trace))
    p = figure()
    p.add_tools(CrosshairTool())
    p.line(x_range, new_trace)
    p.line(x_range, trace, line_color='red')
    show(p)
Exemple #11
0
 def _set_linked_crosshairs(self, figures):
     '''
     Link crosshairs across all figures
     src:
     https://stackoverflow.com/questions/37965669/how-do-i-link-the-crosshairtool-in-bokeh-over-several-plots
     '''
     js_leave = ''
     js_move = 'if(cross.spans.height.location){\n'
     for i in range(len(figures) - 1):
         js_move += '\t\t\tother%d.spans.height.location = cb_obj.sx\n' % i
     js_move += '}else{\n'
     for i in range(len(figures) - 1):
         js_move += '\t\t\tother%d.spans.height.location = null\n' % i
         js_leave += '\t\t\tother%d.spans.height.location = null\n' % i
     js_move += '}'
     crosses = [CrosshairTool() for fig in figures]
     for i, fig in enumerate(figures):
         fig.figure.add_tools(crosses[i])
         args = {'fig': fig.figure, 'cross': crosses[i]}
         k = 0
         for j in range(len(figures)):
             if i != j:
                 args['other%d' % k] = crosses[j]
                 k += 1
         fig.figure.js_on_event('mousemove',
                                CustomJS(args=args, code=js_move))
         fig.figure.js_on_event('mouseleave',
                                CustomJS(args=args, code=js_leave))
    def build_week_figure(self, week_cds_list):
        week_figure = figure(width_policy='max',
                             height_policy='max',
                             title='Last Week',
                             tools='pan,wheel_zoom',
                             active_scroll='wheel_zoom',
                             x_axis_type='datetime')

        hover_tool = HoverTool(tooltips=TOOLTIPS,
                               formatters=FORMATTERS,
                               mode='vline')
        cross_hair_tool = CrosshairTool(dimensions='height')
        week_figure.add_tools(hover_tool, cross_hair_tool)
        weekday_palette = brewer['Blues'][9]
        weekend_palette = brewer['OrRd'][5]

        for i, (legend_label,
                day_cds) in enumerate(zip(WEEK_DAYS, week_cds_list)):
            color = weekday_palette[i] if i < 5 else weekend_palette[i - 5]
            week_figure.line(x='index',
                             y=INTEREST_COLUMNS[0],
                             source=day_cds,
                             line_width=2,
                             color=color,
                             legend_label=legend_label)

        week_figure.legend.location = 'top_right'
        week_figure.legend.orientation = 'horizontal'
        week_figure.legend.click_policy = 'hide'

        return week_figure
Exemple #13
0
    def event_chart():
        factors = ["a","b","c,","d"]
        x = [24.3, -22.3, -25, 6]
        
        LineColor=["green" if a>=0 else "red" for a in x]
        
        Tooltips = [
            ("index", "$index"),
            ("(x,y)", "($x, $y)")
#            ("radius", "@radius"),
#            ("fill color", "$color[hex, swatch]:fill_color"),
#            ("x", "@x"),
#            ("bar", "@bar"),
        ]
        dots_fig = figure(title="exapmple", y_range = factors, x_range = [-30,30], toolbar_location="below",  toolbar_sticky=False, \
                          tools='lasso_select, poly_select, undo, redo, reset')
#                          , \
#                          tooltips=Tooltips)
        
        dots_fig.segment(0, factors, x, factors, line_width=2, line_color=LineColor)
        c1 = dots_fig.circle(x, factors, size=15, fill_color="orange", line_width=3, line_color=LineColor)
        
#        tool = BoxEditTool(renderers=[c1])
        tool2 = BoxSelectTool(dimensions="width") # To make a multiple selection, press the SHIFT key. To clear the selection, press the ESC key
        
#        dots_fig.add_tools(tool) # disappears the points..
        dots_fig.add_tools(tool2)
        dots_fig.add_tools(CrosshairTool(dimensions='height'))
        
        return dots_fig
Exemple #14
0
    def __init__(self,**kwargs):
        super(WeatherPlot,self).__init__(**kwargs)

    # def __init__(self,
    #              data,
    #              column_names=cs.column_names_weewx,
    #              column_time=cs.time_column_name_weewx,
    #              plot_height=300,
    #              plot_width=800,
    #              border_left=150,
    #              **kwargs):
    #     if "tool_events" not in kwargs:
    #         kwargs["tool_events"] = ToolEvents()
    #     super(WeatherPlot,self).__init__(x_range=DataRange1d(),
    #                                      y_range=DataRange1d(),
    #                                      plot_width=800,
    #                                      plot_height=500,
    #                                      min_border_left=150,
    #                                      **kwargs)

        time_int = 3600
        t_max = int(time.time())
        t_min = t_max - 3600 * 24
        data = sql_con.get_data_ws(time_int=time_int,
                                           t_max=t_max,
                                           t_min=t_min)
        self._data = data
        column_names=cs.column_names_weewx
        column_time=cs.time_column_name_weewx
        data_seconds = data
        data_seconds.iloc[:, 0] = data_seconds.iloc[:, 0] * 1000
        add_glyphs_to_plot(column_names, column_time, data_seconds, self)
        self.add_layout(DatetimeAxis(), 'below')
        self.add_tools(PanTool(), WheelZoomTool(), ResizeTool(), CrosshairTool())
Exemple #15
0
def heatmap3(cs3):
    from bkcharts import HeatMap, show, output_file
    from bokeh.palettes import RdGy11 as palette  # @UnresolvedImport
    from bokeh.models import HoverTool
    from bokeh.models import CrosshairTool

    crosshair = CrosshairTool()


    hover = HoverTool(tooltips=[
        ("index", "$index"),
        ("(x,y)", "(@x,@y)"),
        ("score", "@values")
    ])

    print (type(cs3))

    score = []
    for x in c3.apply(tuple):
        score.extend(x)

    data = {
        'utterance1': list(cs3.index) * len(cs3.columns),
        'utterance2': [item for item in list(cs3.columns) for i in range(len(c3.index))],
        'score': score,
    }


    output_file('utterance_heatmap.html')
    hm = HeatMap(data, x='utterance1', y='utterance2', values='score', title='Cosine Similarity', tools=[hover,crosshair], stat=None, palette=palette)
    #show(hm)
    return hm
Exemple #16
0
def plot_ticker(ticker):
    # Retrieve and process data:
    
    url = urlhead + ticker + urltail
    page = requests.get(url)
    json = page.json()
    df = pd.DataFrame(json['Time Series (Daily)'])
    
    # New DataFrame to append values:
    df_1 = pd.DataFrame()
    close = np.asarray(df.iloc[3])
    
    df_1['date'] = pd.to_datetime(list(df))
    df_1['close'] = close
    
    # Last 30 days:
    df_1 = df_1[0:30]
    
    # Create a new column with dates as string:
    df_1['date_str'] = df_1['date'].map(lambda x: x.strftime("%Y-%m-%d"))
    dfcds = ColumnDataSource(df_1)
    
    # Create Bokeh plot:
    p = figure(width=600, height=300, title=ticker.upper(), tools="")

    hover = HoverTool(tooltips = [
        ('Date', '@date_str'),
        ('Close', '@close')])
    
    hover.mode = 'vline'
    hover.line_policy = 'nearest'
    p.add_tools(hover)

    crosshair = CrosshairTool()
    crosshair.dimensions = 'height'
    p.add_tools(crosshair)

    p.line('date', 'close', source =  dfcds)

    p.xaxis.formatter=DatetimeTickFormatter(days=["%d %b"])
    p.x_range=Range1d(df_1['date'].min(), df_1['date'].max())

    p.toolbar.logo = None
    p.toolbar_location = None

    return p
Exemple #17
0
def add_vlinked_crosshairs(fig1, fig2):
    js_move = '''if(cb_obj.x >= fig.x_range.start && cb_obj.x <= fig.x_range.end && cb_obj.y >= fig.y_range.start && cb_obj.y <= fig.y_range.end)
					{ cross.spans.height.computed_location = cb_obj.sx }
				else 
					{ cross.spans.height.computed_location = null }'''
    js_leave = 'cross.spans.height.computed_location = null'

    cross1 = CrosshairTool()
    cross2 = CrosshairTool()
    fig1.add_tools(cross1)
    fig2.add_tools(cross2)
    args = {'cross': cross2, 'fig': fig1}
    fig1.js_on_event('mousemove', CustomJS(args=args, code=js_move))
    fig1.js_on_event('mouseleave', CustomJS(args=args, code=js_leave))
    args = {'cross': cross1, 'fig': fig2}
    fig2.js_on_event('mousemove', CustomJS(args=args, code=js_move))
    fig2.js_on_event('mouseleave', CustomJS(args=args, code=js_leave))
Exemple #18
0
 def plot_assets(self):
     TOOLS = 'box_select,crosshair,reset'
     #       output_file("stocks.html", title="Performance tracker")
     p = figure(plot_width=700,
                plot_height=250,
                tools=TOOLS,
                toolbar_location=None)
     p.line(self.dates,
            self.closeprice,
            line_width=2,
            line_color="greenyellow")
     # Title
     #p.add_layout(Title(text='last price: ' + str(self.closeprice[-1]) + '€;   yield: ' + str(self.ly) + '%;   fall from max:' + str(self.loss) +'%', text_font_style="bold", text_font_size="13pt", text_font='Cantarell'), 'above')
     p.add_layout(
         Title(text=self.label,
               text_font_style="bold",
               text_font_size="16pt",
               text_font='Cantarell'), 'above')
     # Axes
     p.xaxis.minor_tick_line_color = None
     p.yaxis.minor_tick_line_color = None
     p.xaxis.ticker.desired_num_ticks = 7
     p.xaxis.major_label_text_font_size = "11pt"
     p.xaxis.major_label_text_font = "Cantarell"
     p.xaxis.major_label_text_font_style = "bold"
     p.yaxis.major_label_text_font_size = "11pt"
     p.yaxis.major_label_text_font = "Cantarell"
     p.yaxis.major_label_text_font_style = "bold"
     p.xaxis.formatter = DatetimeTickFormatter(
         hours=["%d-%m-%Y"],
         days=["%d-%m-%Y"],
         months=["%d-%m-%Y"],
         years=["%d-%m-%Y"],
     )
     # Grid
     p.grid.grid_line_color = 'gray'
     p.grid.grid_line_alpha = 0.5
     # Background
     p.background_fill_color = "black"
     # Horizontal line
     hline = Span(location=self.buyprice,
                  dimension='width',
                  line_color='red',
                  line_width=3)
     p.renderers.extend([hline])
     # Tools: hover and crosshair
     p.add_tools(CrosshairTool(line_color="red"))
     p.add_tools(
         HoverTool(tooltips=[
             ('date', '@x{%F}'),
             ('price', '@{y}{%0.2f}'),
         ],
                   formatters={
                       'x': 'datetime',
                       'y': 'printf',
                   },
                   mode='vline'))
     return p
Exemple #19
0
    def _init_figure(self):
        # plot height will be set later
        f = figure(tools=Figure._tools, plot_width=self._scheme.plot_width, logo=None, sizing_mode='scale_width', x_axis_type='linear')
        # TODO: backend webgl (output_backend="webgl") removed due to this bug:
        # https://github.com/bokeh/bokeh/issues/7568

        f.border_fill_color = convert_color(self._scheme.border_fill)

        f.xaxis.axis_line_color = convert_color(self._scheme.axis_line_color)
        f.yaxis.axis_line_color = convert_color(self._scheme.axis_line_color)
        f.xaxis.minor_tick_line_color = convert_color(self._scheme.tick_line_color)
        f.yaxis.minor_tick_line_color = convert_color(self._scheme.tick_line_color)
        f.xaxis.major_tick_line_color = convert_color(self._scheme.tick_line_color)
        f.yaxis.major_tick_line_color = convert_color(self._scheme.tick_line_color)

        f.xaxis.major_label_text_color = convert_color(self._scheme.axis_label_text_color)
        f.yaxis.major_label_text_color = convert_color(self._scheme.axis_label_text_color)

        f.xgrid.grid_line_color = convert_color(self._scheme.grid_line_color)
        f.ygrid.grid_line_color = convert_color(self._scheme.grid_line_color)
        f.title.text_color = convert_color(self._scheme.plot_title_text_color)

        f.left[0].formatter.use_scientific = False
        f.background_fill_color = convert_color(self._scheme.background_fill)

        # mechanism for proper date axis without gaps, thanks!
        # https://groups.google.com/a/continuum.io/forum/#!topic/bokeh/t3HkalO4TGA
        f.xaxis.formatter = FuncTickFormatter(
            args=dict(
                axis=f.xaxis[0],
                formatter=DatetimeTickFormatter(days=['%d %b', '%a %d'],
                                                months=['%m/%Y', "%b %y"]),
                source=self._cds,
            ),
            code="""
                axis.formatter.doFormat = function (ticks) {
                    const dates = ticks.map(i => source.data.datetime[i]),
                          valid = t => t !== undefined,
                          labels = formatter.doFormat(dates.filter(valid));
                    let i = 0;
                    return dates.map(t => valid(t) ? labels[i++] : '');
                };
                const axisticks = axis.tick_coords.major[0],
                      labels = axis.formatter.doFormat(ticks);
                return labels[axisticks.indexOf(tick)];
        """)

        ch = CrosshairTool(line_color=self._scheme.crosshair_line_color)
        f.tools.append(ch)

        h = HoverTool(tooltips=[('Time', '@datetime{%x %X}')],
                      mode="vline",
                      formatters={'datetime': 'datetime'}
                      )
        f.tools.append(h)

        self._hover = h
        self.figure = f
Exemple #20
0
def create_candlesctick(df, ticker):
    title = ticker

    df['mid'] = df.apply(lambda x: (x['open'] + x['close']) / 2, axis=1)
    df['height'] = df.apply(lambda x: abs(x['close'] - x['open'])
                            if x['close'] != x['open'] else 0.001,
                            axis=1)

    inc = df.close > df.open
    dec = df.open > df.close
    width = 0.3

    source_inc = ColumnDataSource(df.loc[inc])
    source_dec = ColumnDataSource(df.loc[dec])
    hover_tools = HoverTool(tooltips=[
        ('date', '@date'),
        ('open', '@open'),
        ('close', '@close'),
    ])

    tools = (CrosshairTool(), hover_tools)

    p = figure(plot_width=800,
               plot_height=300,
               tools=tools,
               x_axis_type='datetime',
               title=title)

    # Style candlesticks:
    p.segment(df.timestamp[inc],
              df.high[inc],
              df.timestamp[inc],
              df.low[inc],
              color='green')  # Positive return
    p.segment(df.timestamp[dec],
              df.high[dec],
              df.timestamp[dec],
              df.low[dec],
              color='green')  # Negative return
    p.rect(x='timestamp',
           y='mid',
           width=width,
           height=height,
           fill_color='green',
           source=source_inc)  # Positive return
    p.rect(x='timestamp',
           y='mid',
           width=width,
           height=height,
           fill_color='red',
           source=source_dec)  # Positive return
    p.yaxis[0].formatter = NumeralTickFormatter(format="$0.00")
    p.grid.grid_line_color = None

    script, div = components(p)

    return script, div
Exemple #21
0
def get_figure_1():
    p = figure(x_axis_type='datetime',
               sizing_mode='scale_width',
               plot_height=50)
    p.add_tools(CrosshairTool())
    p.xaxis.major_label_orientation = pi / 4
    p.grid.grid_line_alpha = 0.6

    return p
Exemple #22
0
 def add_custom_tools(self):
     # N.B. Max hold comes from a different CDS so can't be shown in the same tooltip :(
     hover = HoverTool(tooltips=[
         ("freq", "$x{0,0.00} MHz"),
         ("power", "@y0 zW / Hz"),
     ],
                       mode='vline',
                       renderers=self.lines)
     crosshair = CrosshairTool()
     self.plot.add_tools(hover, crosshair)
Exemple #23
0
def plot_k(df):
    i_src = ColumnDataSource(df[df.open < df.close])
    d_src = ColumnDataSource(df[df.open >= df.close])
    w = 16 * 60 * 60 * 1000  # half day in ms

    TOOLS = "pan,xwheel_zoom,ywheel_zoom,box_zoom,reset,save"

    p = figure(x_axis_type="datetime",
               tools=TOOLS,
               plot_width=1500,
               plot_height=640,
               title="MSFT Candlestick")  # hei 880
    p.toolbar.active_scroll = "auto"
    p.xaxis.major_label_orientation = pi / 4
    p.grid.grid_line_alpha = 0.3
    p.background_fill_color = "black"

    p.segment('date', 'high', 'date', 'low', source=i_src, color="red")
    p.segment('date', 'high', 'date', 'low', source=d_src, color="green")

    p.vbar('date',
           w,
           'open',
           'close',
           source=i_src,
           name="kline",
           fill_color="red",
           line_color="red")
    p.vbar('date',
           w,
           'open',
           'close',
           source=d_src,
           name="kline",
           fill_color="green",
           line_color="green")

    p.add_tools(
        HoverTool(
            tooltips=[("date", "@ToolTipDates"), ("close", "@close{0,0.00}"),
                      ("high", "@high{0,0.00}"), ("low", "@low{0,0.00}")],
            names=[
                "kline",
            ],
        ))
    p.add_tools(CrosshairTool(line_color='grey'))

    inc_process(df, p)

    output_file("candlestick.html",
                title="candlestick.py example",
                mode='inline')
    gridplot()
    show(p)  # open a browser
def make_vaccine_effectiveness_plot():
    """
    This makes the plot that introduces vaccine effectiveness.
    """
    # Download and preprocess data.
    starttime = datetime.now()
    cdc_tables = pd.read_html(
        "https://www.cdc.gov/flu/vaccines-work/past-seasons-estimates.html"
    )  # noqa
    cdc_ve = cdc_tables[0]
    cdc_ve.columns = cdc_ve.loc[0, :]
    cdc_ve = cdc_ve.drop(0).reset_index(drop=True)
    cdc_ve.columns = [
        "season",
        "reference",
        "study_sites",
        "num_patients",
        "overall_ve",
        "CI",
    ]
    cdc_ve["season_start"] = (
        cdc_ve["season"].str.split("-").str[0].apply(lambda x: str(x)))

    # Configure Bokeh Plot
    cdc_src = ColumnDataSource(cdc_ve)
    hover_tool = HoverTool()
    hover_tool.tooltips = [
        ("Year", "@season_start"),
        ("Effectiveness (%)", "@overall_ve"),
    ]
    tools = [PanTool(), CrosshairTool(), hover_tool, ResetTool(), SaveTool()]

    # Make Bokeh Plot
    p = figure(
        title="Yearly Vaccine Effectiveness",
        plot_height=300,
        plot_width=350,
        tools=tools,
    )
    p.xaxis.axis_label = "Year"
    p.yaxis.axis_label = "Vaccine Effectiveness (%)"
    p.y_range = Range1d(0, 100)
    p.line(x="season_start", y="overall_ve", source=cdc_src, line_width=2)
    p.circle(
        x="season_start",
        y="overall_ve",
        source=cdc_src,
        radius=5,
        radius_units="screen",
    )
    endtime = datetime.now()
    elapsed = endtime - starttime
    print(f"make_vaccine_effectiveness_plot() took {elapsed} seconds")
    return components(p)
Exemple #25
0
def get_ceil_plot(time_int=None, t_min=None, t_max=None):
    if time_int == None:
        time_int = cs.time_int
    plot_height = cs.plot_height
    plot_width = cs.plot_width
    border_left = cs.border_left

    if t_min == None or t_max == None:
        t_max, t_min = get_first_time_interval()

    t_span = t_max - t_min

    data = sql_con.get_data_bs(time_int=time_int, t_min=t_min, t_max=t_max)
    # print data

    ll = len(data)
    toolset = [CrosshairTool(), WheelZoomTool(), PreviewSaveTool(), PanTool()]
    plot = figure(x_range=DataRange1d(start=(t_min - t_span * .1) * 1000,
                                      end=(t_max + t_span * .1) * 1000),
                  y_range=[0, 250 * 15],
                  plot_height=plot_height,
                  plot_width=plot_width,
                  x_axis_type="datetime",
                  min_border_left=border_left,
                  toolbar_location="right",
                  tools=toolset)
    plot.yaxis.axis_label = "meters above ground"
    dd = []
    tt = []
    y = []
    dw = []
    dh = []

    for i in range(ll):
        dd.append(data.iloc[i:i + 1, 1:].T.values)
        tt.append(int(data.iloc[i, 0]) * 1000 - time_int * 1000 / 2)
        y.append(0)
        dw.append(time_int * 1000)
        dh.append(250 * 15)

    plot.image(image=dd,
               x=tt,
               y=y,
               dw=dw,
               dh=dh,
               palette="Spectral11",
               dilate=True)

    plot.title = cs.plot_title_ceil + ' averaged to {} seconds'.format(
        time_int)

    return plot
Exemple #26
0
def get_weather_plot(time_int=None, t_min=None, t_max=None):
    plot_height = cs.plot_height
    plot_width = cs.plot_width
    border_left = cs.border_left
    column_names = cs.column_names_weewx
    column_time = cs.time_column_name_weewx
    if t_max == None or t_min == None:
        t_max, t_min = get_first_time_interval()
    t_span = t_max - t_min
    if time_int == None:
        time_int = cs.time_int
    data_seconds = sql_con.get_data_ws(time_int=time_int,
                                       t_min=t_min,
                                       t_max=t_max)
    data_seconds.iloc[:, 0] = data_seconds.iloc[:, 0] * 1000

    plot = Plot(
        x_range=DataRange1d(start=(t_min - t_span * .1) * 1000,
                            end=(t_max + t_span * .1) * 1000),
        y_range=DataRange1d(),
        plot_width=plot_width,
        plot_height=plot_height,
        # x_axis_type="datetime",
        min_border_left=border_left,
        toolbar_location="right")

    add_glyphs_to_plot(column_names, column_time, data_seconds, plot,
                       'source_weather')

    plot.add_layout(DatetimeAxis(name="date_time_axis"), 'below')

    plot.add_tools(
        PanTool(),
        WheelZoomTool(),
        # ResizeTool(),
        CrosshairTool(),
        PreviewSaveTool())
    Grid(plot=plot,
         dimension=0,
         ticker=plot.select('date_time_axis')[0].ticker)

    Grid(plot=plot,
         dimension=1,
         ticker=plot.select(type=LinearAxis, name=column_names[0])[0].ticker)

    set_legends(plot)

    plot.title = cs.plot_title_weewx + ' averaged to {} seconds'.format(
        time_int)

    return plot
def make_num_sequences_per_year_plot():
    starttime = datetime.now()
    # Download and Preprocess Data
    sequences, metadata = load_sequence_and_metadata()
    metadata["Year"] = metadata["Collection Date"].apply(lambda x: x.year)
    metadata = metadata[metadata["Host Species"] == "IRD:Human"]
    gb = metadata.groupby("Year").count().reset_index()

    # Configure Bokeh Plot
    seqperyear_src = ColumnDataSource(gb)
    hover_tool = HoverTool()
    hover_tool.tooltips = [("Year", "@Year"), ("Num. Sequences", "@Name")]
    tools = [PanTool(), CrosshairTool(), hover_tool, ResetTool(), SaveTool()]

    # Make figure
    p = figure(
        plot_height=300,
        plot_width=350,
        tools=tools,
        title="Num. Sequences Per Year",
    )

    p.line(x="Year", y="Name", source=seqperyear_src, line_width=2)

    p.circle(
        x="Year",
        y="Name",
        source=seqperyear_src,
        radius=5,
        radius_units="screen",
    )

    p.xaxis.axis_label = "Year"
    p.yaxis.axis_label = "Number of Sequences"

    # Collate metadata dictionary.
    meta = dict()
    meta["n_seqs"] = len(metadata)
    meta["min_year"] = min(metadata["Year"])
    meta["max_year"] = max(metadata["Year"])
    endtime = datetime.now()
    elapsed = endtime - starttime
    print(f"make_num_sequences_per_year_plot() took {elapsed} seconds.")
    return components(p), meta
Exemple #28
0
def make_vaccine_effectiveness_plot():
    """
    This makes the plot that introduces vaccine effectiveness.
    """
    # Download and preprocess data.
    starttime = datetime.now()
    cdc_tables = pd.read_html(
        'https://www.cdc.gov/flu/professionals/vaccination/effectiveness-studies.htm'
    )  # noqa
    cdc_ve = cdc_tables[0]
    cdc_ve.columns = cdc_ve.loc[0, :]
    cdc_ve = cdc_ve.drop(0).reset_index(drop=True)
    cdc_ve.columns = [
        'season', 'reference', 'study_sites', 'num_patients', 'overall_ve',
        'CI'
    ]
    cdc_ve['season_start'] = cdc_ve['season'].str.split('-').str[0]\
        .apply(lambda x: str(x))

    # Configure Bokeh Plot
    cdc_src = ColumnDataSource(cdc_ve)
    hover_tool = HoverTool()
    hover_tool.tooltips = [("Year", "@season_start"),
                           ("Effectiveness (%)", "@overall_ve")]
    tools = [PanTool(), CrosshairTool(), hover_tool, ResetTool(), SaveTool()]

    # Make Bokeh Plot
    p = figure(title='Yearly Vaccine Effectiveness',
               plot_height=300,
               plot_width=350,
               tools=tools)
    p.xaxis.axis_label = 'Year'
    p.yaxis.axis_label = 'Vaccine Effectiveness (%)'
    p.y_range = Range1d(0, 100)
    p.line(x='season_start', y='overall_ve', source=cdc_src, line_width=2)
    p.circle(x='season_start',
             y='overall_ve',
             source=cdc_src,
             radius=5,
             radius_units='screen')
    endtime = datetime.now()
    elapsed = endtime - starttime
    print(f'make_vaccine_effectiveness_plot() took {elapsed} seconds')
    return components(p)
    def build_live_figure(self, cds):
        live_figure = figure(width_policy='max',
                             height_policy='max',
                             tools='pan,wheel_zoom',
                             active_scroll='wheel_zoom',
                             title='Live',
                             x_axis_type='datetime')

        live_figure.line(x='index',
                         y=INTEREST_COLUMNS[0],
                         source=cds,
                         line_color='green',
                         line_width=2)
        hover_tool = HoverTool(tooltips=TOOLTIPS,
                               formatters=FORMATTERS,
                               mode='vline')
        cross_hair_tool = CrosshairTool(dimensions='height')
        live_figure.add_tools(hover_tool, cross_hair_tool)
        return live_figure
Exemple #30
0
    def _init_figure(self):
        # plot height will be set later
        f = figure(tools=Figure._tools,
                   plot_width=self._scheme.plot_width,
                   logo=None,
                   sizing_mode='scale_width',
                   x_axis_type='datetime',
                   output_backend="webgl")
        f.border_fill_color = convert_color(self._scheme.border_fill)

        f.xaxis.axis_line_color = convert_color(self._scheme.axis_line_color)
        f.yaxis.axis_line_color = convert_color(self._scheme.axis_line_color)
        f.xaxis.minor_tick_line_color = convert_color(
            self._scheme.tick_line_color)
        f.yaxis.minor_tick_line_color = convert_color(
            self._scheme.tick_line_color)
        f.xaxis.major_tick_line_color = convert_color(
            self._scheme.tick_line_color)
        f.yaxis.major_tick_line_color = convert_color(
            self._scheme.tick_line_color)

        f.xaxis.major_label_text_color = convert_color(
            self._scheme.axis_label_text_color)
        f.yaxis.major_label_text_color = convert_color(
            self._scheme.axis_label_text_color)

        f.xgrid.grid_line_color = convert_color(self._scheme.grid_line_color)
        f.ygrid.grid_line_color = convert_color(self._scheme.grid_line_color)
        f.title.text_color = convert_color(self._scheme.plot_title_text_color)

        f.left[0].formatter.use_scientific = False
        f.background_fill_color = convert_color(self._scheme.background_fill)

        ch = CrosshairTool(line_color=self._scheme.crosshair_line_color)
        f.tools.append(ch)

        h = HoverTool(tooltips=[('Time', '@datetime{%x %X}')],
                      mode="vline",
                      formatters={'datetime': 'datetime'})
        f.tools.append(h)

        self._hover = h
        self.figure = f