def create_objects(cls, securities): ranks = utils.get_pumps_rank() quotient_metrics = utils.get_quotient_metrics() ranks['quotient'] = quotient_metrics['quotient'] foo = lambda x: utils.spam_counts.get(x, 0) ranks['spams'] = map(foo, ranks['symbol']) ranks = ranks.sort('quotient', ascending=False) cls._pre_filtered_ranks = { 'All': {k: ranks[k] for k in ranks.columns}, 'Stocks with Spam': dict(ranks[ranks['symbol'].isin(plugins.spam_counts.keys())].sort( 'quotient', ascending=False)), 'Stocks without Spam': dict(ranks[~ranks['symbol'].isin(plugins.spam_counts.keys())].sort( 'quotient', ascending=False)), } source_stocks_rank = ColumnDataSource( cls._pre_filtered_ranks['Stocks with Spam']) table_stocks_rank = DataTable(source=source_stocks_rank, width=785, height=400, selectable=True, editable=True, columns=[ TableColumn(field='symbol', title='symbol', editor=StringEditor()), TableColumn(field='quotient', title='quotient', editor=StringEditor()), TableColumn(field='rank', title='rank', editor=StringEditor()), TableColumn(field='spams', title='spams', editor=StringEditor()), ]) callback = Callback(args={ 'tr': table_stocks_rank, 'sr': source_stocks_rank }, code=callbacks.source_stocks_rank) source_stocks_rank.callback = callback return locals()
def _get_columns(self, element, data): columns = [] for d in element.dimensions(): col = dimension_sanitizer(d.name) kind = data[col].dtype.kind if kind == 'i': formatter = NumberFormatter() editor = IntEditor() elif kind == 'f': formatter = NumberFormatter(format='0,0.0[00000]') editor = NumberEditor() elif kind == 'M' or (kind == 'O' and len(data[col]) and type(data[col][0]) in datetime_types): dimtype = element.get_dimension_type(0) dformat = Dimension.type_formatters.get( dimtype, '%Y-%m-%d %H:%M:%S') formatter = DateFormatter(format=dformat) editor = DateEditor() else: formatter = StringFormatter() editor = StringEditor() column = TableColumn(field=dimension_sanitizer(d.name), title=d.pprint_label, editor=editor, formatter=formatter) columns.append(column) return columns
def initialize_plot(self, ranges=None, plot=None, plots=None, source=None): """ Initializes a new plot object with the last available frame. """ # Get element key and ranges for frame element = self.hmap.last key = self.keys[-1] self.current_frame = element self.current_key = key style = self.lookup_options(element, 'style')[self.cyclic_index] data, _, style = self.get_data(element, ranges, style) if source is None: source = self._init_datasource(data) self.handles['source'] = source columns = [] dims = element.dimensions() for d in dims: col = dimension_sanitizer(d.name) kind = data[col].dtype.kind if kind == 'i': formatter = NumberFormatter() editor = IntEditor() elif kind == 'f': formatter = NumberFormatter(format='0,0.0[00000]') editor = NumberEditor() elif kind == 'M' or (kind == 'O' and len(data[col]) and type(data[col][0]) in datetime_types): dimtype = element.get_dimension_type(0) dformat = Dimension.type_formatters.get( dimtype, '%Y-%m-%d %H:%M:%S') formatter = DateFormatter(format=dformat) editor = DateEditor() else: formatter = StringFormatter() editor = StringEditor() column = TableColumn(field=d.name, title=d.pprint_label, editor=editor, formatter=formatter) columns.append(column) style['reorderable'] = False table = DataTable(source=source, columns=columns, height=self.height, width=self.width, **style) self.handles['plot'] = table self.handles['glyph_renderer'] = table self._execute_hooks(element) self.drawn = True for cb in self.callbacks: cb.initialize() return table
def _get_columns(self): if self.value is None: return [] index = [self.value.index.name or 'index'] col_names = index + list(self.value.columns) columns = [] for col in col_names: if col in self.value.columns: data = self.value[col] else: data = self.value.index kind = data.dtype.kind if kind == 'i': formatter = NumberFormatter() editor = IntEditor() elif kind == 'f': formatter = NumberFormatter(format='0,0.0[00000]') editor = NumberEditor() elif isdatetime(data) or kind == 'M': formatter = DateFormatter(format='%Y-%m-%d %H:%M:%S') editor = DateEditor() else: formatter = StringFormatter() editor = StringEditor() if col in self.editors: editor = self.editors[col] if col in self.formatters: formatter = self.formatters[col] if str(col) != col: self._renamed_cols[str(col)] = col width = self.widths.get(str(col)) column = TableColumn(field=str(col), title=str(col), editor=editor, formatter=formatter, width=width) columns.append(column) return columns
BoxSelectTool(), LassoSelectTool(), ResetTool() ]) p.circle("x", "y", size=20, line_color="color", fill_color="color", fill_alpha=0.5, source=source) formatter = HTMLTemplateFormatter(template="<div><%= value %></div>") table_source = ColumnDataSource(data=table_data) columns = [TableColumn(field='IMGS', title='Structure', width=300, formatter=formatter), TableColumn(field='SMILES', title='SMILES', width=300, editor=StringEditor())] + \ [TableColumn(field=prop, title=prop, width=150) for prop in properties.keys()] table = HighTable(source=table_source, columns=columns, editable=True, width=1200, height=1200) button = Button(label="Download", button_type="warning") button.callback = CustomJS(args=dict(source=table_source), code=open( os.path.join(os.path.dirname(__file__), "download.js")).read()) def colors_from_data(data):
from bokeh.embed import file_html from bokeh.resources import INLINE from bokeh.util.browser import view from bokeh.sampledata.autompg2 import autompg2 as mpg source = ColumnDataSource(mpg) manufacturers = sorted(mpg["manufacturer"].unique()) models = sorted(mpg["model"].unique()) transmissions = sorted(mpg["trans"].unique()) drives = sorted(mpg["drv"].unique()) classes = sorted(mpg["class"].unique()) columns = [ TableColumn(field="manufacturer", title="Manufacturer", editor=SelectEditor(options=manufacturers), formatter=StringFormatter(font_style="bold")), TableColumn(field="model", title="Model", editor=StringEditor(completions=models)), TableColumn(field="displ", title="Displacement", editor=NumberEditor(step=0.1), formatter=NumberFormatter(format="0.0")), TableColumn(field="year", title="Year", editor=IntEditor()), TableColumn(field="cyl", title="Cylinders", editor=IntEditor()), TableColumn(field="trans", title="Transmission", editor=SelectEditor(options=transmissions)), TableColumn(field="drv", title="Drive", editor=SelectEditor(options=drives)), TableColumn(field="class", title="Class", editor=SelectEditor(options=classes)), TableColumn(field="cty", title="City MPG", editor=IntEditor()), TableColumn(field="hwy", title="Highway MPG", editor=IntEditor()), ] data_table = DataTable(source=source, columns=columns, editable=True, width=1000, index_position=-1, index_header="row index", index_width=60) plot = Plot(title=None, plot_width=1000, plot_height=300) # Set up x & y axis
def create(self): print("running create...") manufacturers = sorted(mpg["manufacturer"].unique()) models = sorted(mpg["model"].unique()) transmissions = sorted(mpg["trans"].unique()) drives = sorted(mpg["drv"].unique()) classes = sorted(mpg["class"].unique()) manufacturer_select = Select(title="Manufacturer:", value="All", options=["All"] + manufacturers) manufacturer_select.on_change('value', self.on_manufacturer_change) model_select = Select(title="Model:", value="All", options=["All"] + models) model_select.on_change('value', self.on_model_change) transmission_select = Select(title="Transmission:", value="All", options=["All"] + transmissions) transmission_select.on_change('value', self.on_transmission_change) drive_select = Select(title="Drive:", value="All", options=["All"] + drives) drive_select.on_change('value', self.on_drive_change) class_select = Select(title="Class:", value="All", options=["All"] + classes) class_select.on_change('value', self.on_class_change) columns = [ TableColumn(field="manufacturer", title="Manufacturer", editor=SelectEditor(options=manufacturers), formatter=StringFormatter(font_style="bold")), TableColumn(field="model", title="Model", editor=StringEditor(completions=models)), TableColumn(field="displ", title="Displacement", editor=NumberEditor(step=0.1), formatter=NumberFormatter(format="0.0")), TableColumn(field="year", title="Year", editor=IntEditor()), TableColumn(field="cyl", title="Cylinders", editor=IntEditor()), TableColumn(field="trans", title="Transmission", editor=SelectEditor(options=transmissions)), TableColumn(field="drv", title="Drive", editor=SelectEditor(options=drives)), TableColumn(field="class", title="Class", editor=SelectEditor(options=classes)), TableColumn(field="cty", title="City MPG", editor=IntEditor()), TableColumn(field="hwy", title="Highway MPG", editor=IntEditor()), ] data_table = DataTable(source=self.source, columns=columns, editable=True, width=1300) plot = Plot(title=None, x_range=DataRange1d(), y_range=DataRange1d(), plot_width=1000, plot_height=300) # Set up x & y axis plot.add_layout(LinearAxis(), 'below') yaxis = LinearAxis() plot.add_layout(yaxis, 'left') plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) # Add Glyphs cty_glyph = Circle(x="index", y="cty", fill_color="#396285", size=8, fill_alpha=0.5, line_alpha=0.5) hwy_glyph = Circle(x="index", y="hwy", fill_color="#CE603D", size=8, fill_alpha=0.5, line_alpha=0.5) cty = plot.add_glyph(self.source, cty_glyph) hwy = plot.add_glyph(self.source, hwy_glyph) # Add the tools tooltips = [ ("Manufacturer", "@manufacturer"), ("Model", "@model"), ("Displacement", "@displ"), ("Year", "@year"), ("Cylinders", "@cyl"), ("Transmission", "@trans"), ("Drive", "@drv"), ("Class", "@class"), ] cty_hover_tool = HoverTool(renderers=[cty], tooltips=tooltips + [("City MPG", "@cty")]) hwy_hover_tool = HoverTool(renderers=[hwy], tooltips=tooltips + [("Highway MPG", "@hwy")]) select_tool = BoxSelectTool(renderers=[cty, hwy], dimensions='width') plot.add_tools(cty_hover_tool, hwy_hover_tool, select_tool) controls = WidgetBox(manufacturer_select, model_select, transmission_select, drive_select, class_select) top_panel = Row(controls, plot) layout = Column(top_panel, data_table) return layout
def create(self): manufacturers = sorted(mpg["manufacturer"].unique()) models = sorted(mpg["model"].unique()) transmissions = sorted(mpg["trans"].unique()) drives = sorted(mpg["drv"].unique()) classes = sorted(mpg["class"].unique()) manufacturer_select = Select(title="Manufacturer:", value="All", options=["All"] + manufacturers) manufacturer_select.on_change('value', self.on_manufacturer_change) model_select = Select(title="Model:", value="All", options=["All"] + models) model_select.on_change('value', self.on_model_change) transmission_select = Select(title="Transmission:", value="All", options=["All"] + transmissions) transmission_select.on_change('value', self.on_transmission_change) drive_select = Select(title="Drive:", value="All", options=["All"] + drives) drive_select.on_change('value', self.on_drive_change) class_select = Select(title="Class:", value="All", options=["All"] + classes) class_select.on_change('value', self.on_class_change) columns = [ TableColumn(field="manufacturer", title="Manufacturer", editor=SelectEditor(options=manufacturers), formatter=StringFormatter(font_style="bold")), TableColumn(field="model", title="Model", editor=StringEditor(completions=models)), TableColumn(field="displ", title="Displacement", editor=NumberEditor(step=0.1), formatter=NumberFormatter(format="0.0")), TableColumn(field="year", title="Year", editor=IntEditor()), TableColumn(field="cyl", title="Cylinders", editor=IntEditor()), TableColumn(field="trans", title="Transmission", editor=SelectEditor(options=transmissions)), TableColumn(field="drv", title="Drive", editor=SelectEditor(options=drives)), TableColumn(field="class", title="Class", editor=SelectEditor(options=classes)), TableColumn(field="cty", title="City MPG", editor=IntEditor()), TableColumn(field="hwy", title="Highway MPG", editor=IntEditor()), ] data_table = DataTable(source=self.source, columns=columns, editable=True) xdr = DataRange1d() ydr = DataRange1d() plot = Plot(title=None, x_range=xdr, y_range=ydr, plot_width=800, plot_height=300) xaxis = LinearAxis(plot=plot) plot.below.append(xaxis) yaxis = LinearAxis(plot=plot) ygrid = Grid(plot=plot, dimension=1, ticker=yaxis.ticker) plot.left.append(yaxis) cty_glyph = Circle(x="index", y="cty", fill_color="#396285", size=8, fill_alpha=0.5, line_alpha=0.5) hwy_glyph = Circle(x="index", y="hwy", fill_color="#CE603D", size=8, fill_alpha=0.5, line_alpha=0.5) cty = GlyphRenderer(data_source=self.source, glyph=cty_glyph) hwy = GlyphRenderer(data_source=self.source, glyph=hwy_glyph) tooltips = [ ("Manufacturer", "@manufacturer"), ("Model", "@model"), ("Displacement", "@displ"), ("Year", "@year"), ("Cylinders", "@cyl"), ("Transmission", "@trans"), ("Drive", "@drv"), ("Class", "@class"), ] cty_hover_tool = HoverTool(plot=plot, renderers=[cty], tooltips=tooltips + [("City MPG", "@cty")]) hwy_hover_tool = HoverTool(plot=plot, renderers=[hwy], tooltips=tooltips + [("Highway MPG", "@hwy")]) select_tool = BoxSelectTool(plot=plot, renderers=[cty, hwy], dimensions=['width']) plot.tools.extend([cty_hover_tool, hwy_hover_tool, select_tool]) plot.renderers.extend([cty, hwy, ygrid]) controls = VBox(children=[ manufacturer_select, model_select, transmission_select, drive_select, class_select ], width=200) top_panel = HBox(children=[controls, plot]) layout = VBox(children=[top_panel, data_table]) return layout
source = ColumnDataSource(mpg) manufacturers = sorted(mpg["manufacturer"].unique()) models = sorted(mpg["model"].unique()) transmissions = sorted(mpg["trans"].unique()) drives = sorted(mpg["drv"].unique()) classes = sorted(mpg["class"].unique()) columns = [ TableColumn(field="manufacturer", title="Manufacturer", editor=SelectEditor(options=manufacturers), formatter=StringFormatter(font_style="bold")), TableColumn(field="model", title="Model", editor=StringEditor(completions=models)), TableColumn(field="displ", title="Displacement", editor=NumberEditor(step=0.1), formatter=NumberFormatter(format="0.0")), TableColumn(field="year", title="Year", editor=IntEditor()), TableColumn(field="cyl", title="Cylinders", editor=IntEditor()), TableColumn(field="trans", title="Transmission", editor=SelectEditor(options=transmissions)), TableColumn(field="drv", title="Drive", editor=SelectEditor(options=drives)), TableColumn(field="class", title="Class", editor=SelectEditor(options=classes)),
def mk_tab(color): plot = figure(plot_width=300, plot_height=300) plot.scatter(flowers["petal_length"], flowers["petal_width"], color=color, fill_alpha=0.2, size=12) return Panel(title="Tab 1: %s" % color.capitalize(), child=plot) tabs = Tabs(tabs=[mk_tab("red"), mk_tab("green"), mk_tab("blue")]) source = ColumnDataSource(data=mpg) columns = [ TableColumn(field="manufacturer", title="Manufacturer", editor=SelectEditor(options=sorted(mpg["manufacturer"].unique())), formatter=StringFormatter(font_style="bold")), TableColumn(field="model", title="Model", editor=StringEditor(completions=sorted(mpg["model"].unique()))), TableColumn(field="displ", title="Displacement", editor=NumberEditor(step=0.1), formatter=NumberFormatter(format="0.0")), TableColumn(field="year", title="Year", editor=IntEditor()), TableColumn(field="cyl", title="Cylinders", editor=IntEditor()), TableColumn(field="trans", title="Transmission", editor=SelectEditor(options=sorted(mpg["trans"].unique()))), TableColumn(field="drv", title="Drive",
def make_example_datatable(): source = ColumnDataSource(mpg) print(source.column_names) manufacturers = sorted(mpg["manufacturer"].unique()) models = sorted(mpg["model"].unique()) transmissions = sorted(mpg["trans"].unique()) drives = sorted(mpg["drv"].unique()) classes = sorted(mpg["class"].unique()) columns = [ TableColumn(field="manufacturer", title="Manufacturer", editor=SelectEditor(options=manufacturers), formatter=StringFormatter(font_style="bold")), TableColumn(field="model", title="Model", editor=StringEditor(completions=models)), TableColumn(field="displ", title="Displacement", editor=NumberEditor(step=0.1), formatter=NumberFormatter(format="0.0")), TableColumn(field="year", title="Year", editor=IntEditor()), TableColumn(field="cyl", title="Cylinders", editor=IntEditor()), TableColumn(field="trans", title="Transmission", editor=SelectEditor(options=transmissions)), TableColumn(field="drv", title="Drive", editor=SelectEditor(options=drives)), TableColumn(field="class", title="Class", editor=SelectEditor(options=classes)), TableColumn(field="cty", title="City MPG", editor=IntEditor()), TableColumn(field="hwy", title="Highway MPG", editor=IntEditor()), ] data_table = DataTable(source=source, columns=columns, editable=True, width=1000) plot = Plot(title=None, x_range=DataRange1d(), y_range=DataRange1d(), plot_width=1000, plot_height=300) # Set up x & y axis plot.add_layout(LinearAxis(), 'below') yaxis = LinearAxis() plot.add_layout(yaxis, 'left') plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker)) # Add Glyphs cty_glyph = Circle(x="index", y="cty", fill_color="#396285", size=8, fill_alpha=0.5, line_alpha=0.5) hwy_glyph = Circle(x="index", y="hwy", fill_color="#CE603D", size=8, fill_alpha=0.5, line_alpha=0.5) cty = plot.add_glyph(source, cty_glyph) hwy = plot.add_glyph(source, hwy_glyph) # Add the tools tooltips = [ ("Manufacturer", "@manufacturer"), ("Model", "@model"), ("Displacement", "@displ"), ("Year", "@year"), ("Cylinders", "@cyl"), ("Transmission", "@trans"), ("Drive", "@drv"), ("Class", "@class"), ] cty_hover_tool = HoverTool(renderers=[cty], tooltips=tooltips + [("City MPG", "@cty")]) hwy_hover_tool = HoverTool(renderers=[hwy], tooltips=tooltips + [("Highway MPG", "@hwy")]) select_tool = BoxSelectTool(renderers=[cty, hwy], dimensions='width') plot.add_tools(cty_hover_tool, hwy_hover_tool, select_tool) layout = Column(plot, data_table) doc = Document() doc.add_root(layout) return doc
def create_objects(cls, symbol, df, securities): descr_box = Paragraph(text='content loading...') btn_close_loading = Button(label='Close Loading') dialog_loading = Dialog(title='loading', content=vplot(descr_box), name='loading_dialog', buttons=[btn_close_loading], visible=False) source_data = dict(df) main_source = ColumnDataSource(dict(df)) source = ColumnDataSource(source_data) # TODO: REMOVE THIS COMMENTED CODE! IT'S JUST THE PREVIOUS # VERSION USED BEFORE NEW P&D Cached results and algorithm # get the cached results of the P&D algorithm computed with the # "default" configuration # intervals = utils.cached_pumps.get(symbol, pumps.to_dicts(((),(),(),(),(),()))) # intervals['bottom'] = [0] * len(intervals['start']) # intervals['values'] = [max(df['price'])] * len(intervals['start']) # # intervals = pd.DataFrame(intervals) # new version stats = utils.get_symbols_cached_stats()[symbol] intervals = pd.DataFrame(stats) intervals['bottom'] = [0] * len(intervals['start']) intervals['values'] = [max(df['price'])] * len(intervals['start']) conv = lambda x: utils.to_seconds(pd.to_datetime(x)) intervals = intervals[ (pd.to_datetime(intervals['start']) > conv(config.date_range[0])) & (pd.to_datetime(intervals['start']) < conv(config.date_range[1]))] # Create P&Ds intervals DataSource intervals_source = ColumnDataSource(intervals) source.tags = ['main_source'] trends = utils.load_trends_data(symbol, start_date=min(df['dt'])) trends_source = ColumnDataSource(trends) trades = Slider(title="trades", name='trades', value=0, start=0, end=124, step=1) # Selectors symbol = Select.create(options=securities, value=symbol, name='symbol', title="") window_selector = Select.create(options=['---'], name='period_selector', title="Search intervals with:") symbol_filter = Select.create( options=['All', 'Stocks with Spam', 'Stocks without Spam'], name='symbol_filter', title="Filter Symbols:", value='Stocks with Spam') callback = Callback(args={ 'symbol_filter': symbol_filter, 'dialog_loading': dialog_loading }, code=callbacks.symbol_filter) symbol_filter.callback = callback btn_detect_pumps = Button(label='Configure P&D Detection', name='config_pumps') main_tab = Panel(title="Main") tabs = Tabs() # Create STOCKS TABLE ranks = utils.get_pumps_rank() # quotient_metrics = utils.get_quotient_metrics() # ranks['quotient'] = quotient_metrics['quotient'] foo = lambda x: utils.spams_count.get(x, 0) ranks['spams'] = map(foo, ranks['symbol']) ranks = ranks.sort(['spams', 'vol_quotient'], ascending=False) cls._pre_filtered_ranks = { 'All': {k: ranks[k] for k in ranks.columns}, 'Stocks with Spam': dict(ranks[ranks['spams'] > 0].sort('vol_quotient', ascending=False)), 'Stocks without Spam': dict(ranks[ranks['spams'] == 0].sort('vol_quotient', ascending=False)), } source_stocks_rank = ColumnDataSource(cls._pre_filtered_ranks['All']) table_stocks_rank = DataTable( source=source_stocks_rank, width=560, height=450, selectable=True, editable=True, columns=[ TableColumn(field='symbol', title='symbol', width=130, editor=StringEditor()), TableColumn(field='vol_quotient', title='volume ratio', editor=StringEditor(), default_sort='descending'), TableColumn(field='risk_score', title='risk', width=100, editor=StringEditor(), default_sort='descending'), TableColumn(field='spams', title='spams', width=130, editor=StringEditor(), default_sort='descending'), ]) callback = Callback(args={ 'tr': table_stocks_rank, 'sr': source_stocks_rank, 'symb': symbol, 'dialog_loading': dialog_loading }, code=callbacks.source_stocks_rank) source_stocks_rank.callback = callback return locals()