def add_direction_map(fig: Figure, mgrid, direction_map, freq=2, **kwargs):
    """Quiver plot of direction map
    
    http://bokeh.pydata.org/en/latest/docs/gallery/quiver.html
    
    Args:
        fig: 
        mgrid: 
        direction_map: 
        **kwargs: 
        
    """
    X, Y = mgrid.values
    U, V = direction_map

    x0 = X[::freq, ::freq].flatten()
    y0 = Y[::freq, ::freq].flatten()

    x1 = x0 + 0.9 * freq * mgrid.step * U[::freq, ::freq].flatten()
    y1 = y0 + 0.9 * freq * mgrid.step * V[::freq, ::freq].flatten()

    fig.segment(x0, y0, x1, y1, **kwargs)
    fig.triangle(x1,
                 y1,
                 size=4.0,
                 angle=np.arctan2(V[::freq, ::freq].flatten(),
                                  U[::freq, ::freq].flatten()) - np.pi / 2)
 def create_2d_plot(self) -> Figure:
     fig = Figure(width=300, height=300, x_range=(-2, 2), y_range=(-2, 2))
     fig.circle(x='x', y='y', color='color', source=self.data_source)
     fig.segment(x0='x',
                 y0='y',
                 x1='xn',
                 y1='yn',
                 color='color',
                 line_dash='dotted',
                 source=self.data_source)
     return fig
BUFSIZE = 200
MA12, MA26, EMA12, EMA26 = '12-tick Moving Avg', '26-tick Moving Avg', '12-tick EMA', '26-tick EMA'

source = ColumnDataSource(dict(
    time=[], average=[], low=[], high=[], open=[], close=[],
    ma=[], macd=[], macd9=[], macdh=[], color=[]
))

p = Figure(plot_height=600, tools="xpan,xwheel_zoom,xbox_zoom,reset", x_axis_type=None)
p.x_range.follow = "end"
p.x_range.follow_interval = 100

p.line(x='time', y='average', alpha=0.2, line_width=3, color='navy', source=source)
p.line(x='time', y='ma', alpha=0.8, line_width=2, color='orange', source=source)
p.segment(x0='time', y0='low', x1='time', y1='high', line_width=2, color='black', source=source)
p.segment(x0='time', y0='open', x1='time', y1='close', line_width=8, color='color', source=source)

p2 = Figure(plot_height=250, x_range=p.x_range, tools="xpan,xwheel_zoom,xbox_zoom,reset")
p2.line(x='time', y='macd', color='red', source=source)
p2.line(x='time', y='macd9', color='blue', source=source)
p2.segment(x0='time', y0=0, x1='time', y1='macdh', line_width=6, color='black', alpha=0.5, source=source)

mean = Slider(title="mean", value=0, start=-0.01, end=0.01, step=0.001)
stddev = Slider(title="stddev", value=0.04, start=0.01, end=0.1, step=0.01)
mavg = Select(value=MA12, options=[MA12, MA26, EMA12, EMA26])

curdoc().add_root(VBox(HBox(mean, stddev, mavg, width=800), GridPlot(children=[[p], [p2]])))


def create_random_corr_matrix(n):
Esempio n. 4
0
File: main.py Progetto: 0-T-0/bokeh
BUFSIZE = 200
MA12, MA26, EMA12, EMA26 = '12-tick Moving Avg', '26-tick Moving Avg', '12-tick EMA', '26-tick EMA'

source = ColumnDataSource(dict(
    time=[], average=[], low=[], high=[], open=[], close=[],
    ma=[], macd=[], macd9=[], macdh=[], color=[]
))

p = Figure(plot_height=600, tools="xpan,xwheel_zoom,xbox_zoom,reset", x_axis_type=None)
p.x_range.follow = "end"
p.x_range.follow_interval = 100
p.x_range.range_padding = 0

p.line(x='time', y='average', alpha=0.2, line_width=3, color='navy', source=source)
p.line(x='time', y='ma', alpha=0.8, line_width=2, color='orange', source=source)
p.segment(x0='time', y0='low', x1='time', y1='high', line_width=2, color='black', source=source)
p.segment(x0='time', y0='open', x1='time', y1='close', line_width=8, color='color', source=source)

p2 = Figure(plot_height=250, x_range=p.x_range, tools="xpan,xwheel_zoom,xbox_zoom,reset")
p2.line(x='time', y='macd', color='red', source=source)
p2.line(x='time', y='macd9', color='blue', source=source)
p2.segment(x0='time', y0=0, x1='time', y1='macdh', line_width=6, color='black', alpha=0.5, source=source)

mean = Slider(title="mean", value=0, start=-0.01, end=0.01, step=0.001)
stddev = Slider(title="stddev", value=0.04, start=0.01, end=0.1, step=0.01)
mavg = Select(value=MA12, options=[MA12, MA26, EMA12, EMA26])

curdoc().add_root(VBox(HBox(mean, stddev, mavg, width=800), GridPlot(children=[[p], [p2]])))

def _create_prices(t):
    last_average = 100 if t==0 else source.data['average'][-1]
Esempio n. 5
0
def plot_bollinger_signals(data, signals, ticker=None, notebook=False):
    # create a new plot with a title and axis labels
    p = Figure(title=ticker + ' Bollinger Bands Strategy',
               x_axis_label='Date',
               x_axis_type='datetime',
               y_axis_label='Price in $',
               plot_height=500,
               plot_width=950,
               tools=['pan', 'wheel_zoom'],
               toolbar_location='below')

    inc = data['Close'] > data['Open']
    dec = data['Open'] > data['Close']
    w = 12 * 60 * 60 * 1000  # half day in ms

    p.segment(data.index, data['High'], data.index, data['Low'], color="black")
    p.vbar(data.index[inc],
           w,
           data['Open'][inc],
           data['Close'][inc],
           fill_color="#D5E1DD",
           line_color="black")
    p.vbar(data.index[dec],
           w,
           data['Open'][dec],
           data['Close'][dec],
           fill_color="#F2583E",
           line_color="black")

    # configure so that Bokeh chooses what (if any) scroll tool is active
    p.toolbar.active_scroll = "auto"

    # add a line renderer with legend and line thickness
    p.line(signals.index,
           signals['mediumband'],
           line_width=2,
           legend='Mediumband',
           line_color='black')
    p.line(signals.index,
           signals['upperband'],
           line_width=2,
           legend='Upperband',
           line_color='orange')
    p.line(signals.index,
           signals['lowerband'],
           line_width=2,
           legend='Lowerband',
           line_color='blue')

    p.triangle(signals.loc[signals.positions == 1.0].index,
               signals.lowerband[signals.positions == 1.0],
               size=15,
               fill_color='green',
               legend='Buy')
    p.inverted_triangle(signals.loc[signals.positions == -1.0].index,
                        signals.upperband[signals.positions == -1.0],
                        size=15,
                        fill_color='red',
                        legend='Sell')

    p.legend.location = "top_left"
    p.legend.click_policy = "hide"

    if notebook:
        # show the results
        show(p, notebook_handle=True)
        push_notebook()
    else:
        # output the results
        output_file('%s Bollinger Bands Strategy.html' % ticker)
        save(p)
toolset = "crosshair,pan,reset,resize,save,wheel_zoom"
# Generate a figure container for the field
plot_field = Figure(plot_height=400,
                    plot_width=400,
                    tools=toolset,
                    title="Vector valued function",
                    x_range=[curveintegral_settings.x_min, curveintegral_settings.x_max],
                    y_range=[curveintegral_settings.y_min, curveintegral_settings.y_max]
                    )

# remove grid from plot
plot_field.grid[0].grid_line_alpha = 0.0
plot_field.grid[1].grid_line_alpha = 0.0

# Plot the direction field
plot_field.segment('x0', 'y0', 'x1', 'y1', source=source_segments)
plot_field.patches('xs', 'ys', source=source_patches)
plot_field.circle('x', 'y', source=source_basept, color='blue', size=1.5)
# Plot curve
plot_field.line('x', 'y', source=source_curve, color='black', legend='curve')
# Plot parameter point
plot_field.scatter('x', 'y', source=source_param, color='black', legend='c(t)')
# Plot corresponding tangent vector
plot_field.segment('x0', 'y0', 'x1', 'y1', source=source_param, color='black')
plot_field.patches('xs', 'ys', source=source_param, color='black')

# Generate a figure container for the integral value
plot_integral = Figure(title_text_font_size="12pt",
                       plot_height=200,
                       plot_width=400,
                       title="Integral along curve",
Esempio n. 7
0
snr_plot.line('lam',
              'Fo',
              source=theobject,
              line_width=2.0,
              color="darkgreen",
              alpha=0.7)
snr_plot.circle('lam',
                'spec',
                source=theobject,
                fill_color='lightgreen',
                line_color='black',
                size=8)
snr_plot.segment('lam',
                 'downerr',
                 'lam',
                 'uperr',
                 source=theobject,
                 line_width=1,
                 line_color='grey',
                 line_alpha=0.5)

#text on plot
glyph = Text(x=0.25,
             y=-0.19,
             text="label",
             text_font_size='9pt',
             text_font_style='bold',
             text_color='blue')
#attempting to outline the text here for ease of visibility...
glyph2 = Text(x=0.245,
              y=-0.19,
              text="label",
toolset = "crosshair,pan,reset,resize,save,wheel_zoom"
# Generate a figure container for the field
plot_field = Figure(
    plot_height=400,
    plot_width=400,
    tools=toolset,
    title="Vector valued function",
    x_range=[curveintegral_settings.x_min, curveintegral_settings.x_max],
    y_range=[curveintegral_settings.y_min, curveintegral_settings.y_max])

# remove grid from plot
plot_field.grid[0].grid_line_alpha = 0.0
plot_field.grid[1].grid_line_alpha = 0.0

# Plot the direction field
plot_field.segment('x0', 'y0', 'x1', 'y1', source=source_segments)
plot_field.patches('xs', 'ys', source=source_patches)
plot_field.circle('x', 'y', source=source_basept, color='blue', size=1.5)
# Plot curve
plot_field.line('x', 'y', source=source_curve, color='black', legend='curve')
# Plot parameter point
plot_field.scatter('x', 'y', source=source_param, color='black', legend='c(t)')
# Plot corresponding tangent vector
plot_field.segment('x0', 'y0', 'x1', 'y1', source=source_param, color='black')
plot_field.patches('xs', 'ys', source=source_param, color='black')

# Generate a figure container for the integral value
plot_integral = Figure(title_text_font_size="12pt",
                       plot_height=200,
                       plot_width=400,
                       title="Integral along curve",
Esempio n. 9
0
# BOKEH PLOTTING
################################

snr_plot = Figure(plot_height=400, plot_width=750, 
              tools="crosshair,pan,reset,resize,save,box_zoom,wheel_zoom",
              x_range=[0.3, 2.7], y_range=[0, 1], toolbar_location='right')
snr_plot.x_range = Range1d(0.3, 2.7, bounds=(0.3, 2.7)) 
snr_plot.y_range = Range1d(0.0, 1.2, bounds=(0.3, 5.0)) 
snr_plot.background_fill_color = "beige"
snr_plot.background_fill_alpha = 0.5
snr_plot.yaxis.axis_label='F_p/F_s (x10^9)' 
snr_plot.xaxis.axis_label='Wavelength [micron]' 

snr_plot.line('lam','cratio',source=planet,line_width=2.0, color="green", alpha=0.7)
snr_plot.circle('lam', 'spec', source=planet, fill_color='red', line_color='black', size=8) 
snr_plot.segment('lam', 'downerr', 'lam', 'uperr', source=planet, line_width=1, line_color='grey', line_alpha=0.5) 

def change_filename(attrname, old, new): 
   format_button_group.active = None 


instruction0 = Div(text="""Choose a file rootname here 
                           (no special characters):""", width=300, height=15)
text_input = TextInput(value="filename", title=" ", width=100)
instruction1 = Div(text="""Then choose a format here:""", width=300, height=15)
format_button_group = RadioButtonGroup(labels=["txt", "fits"])
instruction2 = Div(text="""Your file will be linked here:""", width=300, height=15)
link_box  = Div(text=""" """, width=300, height=15)


def i_clicked_a_button(new): 
Esempio n. 10
0
def run(stock):
    # Get stock
    quote = get(stock, "quote")
    stock_quote = {
        "companyName": quote['companyName'],
        "latestPrice": quote['latestPrice'],
        "symbol": quote['symbol'],
        "change": "{0:.2%}".format(quote['changePercent']),
        "volume": "{:,}".format(quote['latestVolume']),
        "logo": get(stock, 'logo')['url']
    }

    # Get stock related news
    news = get(stock, "news/last/5")
    stock_news = []
    for article in news:
        stock_news.append({
            "headline": article['headline'],
            "url": article['url']
        })

    # Get stock related company data
    company = get(stock, "company")
    company_data = {
        "website": company['website'],
        "CEO": company['CEO'],
        "description": company['description']
    }

    # Get stock key stats
    stats = get(stock, "stats")
    key_stats = {
        "latestEPS": stats['latestEPS'],
        "day5Change": "{0:.2%}".format(stats['day5ChangePercent']),
        "month3Change": "{0:.2%}".format(stats['month3ChangePercent']),
        "year1Change": "{0:.2%}".format(stats['year1ChangePercent']),
    }

    # Get chart stats and make bokeh
    chart = get(stock, "chart/5y")
    chart_cds_df = get(stock, 'chart/1m')
    chart = pd.DataFrame(chart)
    chart = chart.set_index(pd.to_datetime(chart.date))

    chart_cds = ColumnDataSource(chart)

    p = Figure(x_axis_label="Date",
               y_axis_label="Price",
               x_axis_type="datetime",
               title="{} - 5Y Graph".format(stock),
               sizing_mode='scale_width')
    # p.background_fill_color = '#8FBC8F'
    # p.background_fill_alpha = 0.2
    p.grid.grid_line_alpha = 0.3

    p.line(x='date',
           y='close',
           source=chart_cds,
           line_width=1,
           color='#F2583E')

    hover = HoverTool(mode='vline')
    hover.tooltips = [('Date', '@label'), ('Open', '$@open{%0.2f}'),
                      ('High', '$@high{%0.2f}'), ('Low', '$@low{%0.2f}'),
                      ('Close', '$@close{%0.2f}')]
    hover.formatters = {
        'open': 'printf',
        'high': 'printf',
        'low': 'printf',
        'close': 'printf'
    }
    p.add_tools(hover)

    cdl = Figure(x_axis_label="Date",
                 y_axis_label="Price",
                 x_axis_type="datetime",
                 title="{} - Candlestick".format(stock),
                 sizing_mode='scale_width')

    chart_cds_df = pd.DataFrame(chart_cds_df)
    chart_cds_df = chart_cds_df.set_index(pd.to_datetime(chart_cds_df.date))

    inc = chart_cds_df.close > chart_cds_df.open
    dec = chart_cds_df.open > chart_cds_df.close
    w = 12 * 60 * 60 * 1000

    cdl.segment(chart_cds_df.index,
                chart_cds_df.high,
                chart_cds_df.index,
                chart_cds_df.low,
                color='black')
    cdl.vbar(chart_cds_df.index[inc],
             w,
             chart_cds_df.open[inc],
             chart_cds_df.close[inc],
             fill_color='#D5E1DD',
             line_color='black')
    cdl.vbar(chart_cds_df.index[dec],
             w,
             chart_cds_df.open[dec],
             chart_cds_df.close[dec],
             fill_color='#F2583E',
             line_color='black')

    cdl.grid.grid_line_alpha = 0.3

    cdl_s, cdl_div = components(cdl)

    script, div = components(p)

    return {
        "stock_quote": stock_quote,
        "stock_news": stock_news,
        "company_data": company_data,
        "key_stats": key_stats,
        "chart_script": script,
        "chart_div": div,
        "s": cdl_s,
        "d": cdl_div
    }
Esempio n. 11
0
                              source=shutter_positions,
                              size=15,
                              color='grey',
                              line_color=None,
                              fill_alpha=0.1)
cluster_points.selection_glyph = Square(fill_alpha=0.5,
                                        fill_color="green",
                                        line_color='green',
                                        line_width=3)
cluster_points.nonselection_glyph = Square(fill_alpha=0.1,
                                           fill_color="grey",
                                           line_color=None)
cluster_errors = plot2.segment('mass',
                               'vmax_up_error',
                               'mass',
                               'vmax_down_error',
                               source=shutter_positions,
                               line_width=2,
                               line_color='grey',
                               line_alpha=0.1)
cluster_errors.selection_glyph = Segment(line_alpha=0.5,
                                         line_color='green',
                                         line_width=3)
cluster_errors.nonselection_glyph = Segment(line_alpha=0.1,
                                            line_color='grey',
                                            line_width=1)

# Set up control widgets
aperture = Slider(title="Aperture (meters)",
                  value=12.,
                  start=4.,
                  end=20.0,