def fdectree(X,Y): name = Paragraph(text=" DecisionTree method applied") start_time = time.time() X_train, X_test, y_train, y_test = train_test_split(X, Y, train_size=0.8) tree_para = {'criterion':['gini','entropy'],'max_depth':[4,5,6,7,8,9,10,11,12,15,20,30,40,50,70,90,120,150]} clf = GridSearchCV(DecisionTreeClassifier(), tree_para, cv=5) clf.fit(X_train,y_train) y_pred = clf.predict(X_test) end_time = time.time() exec_time = round(end_time - start_time, 2) #Graphique categ = y_test.astype("category") dico_tmp = dict(enumerate(categ.cat.categories)) dico = dict((v, k) for k, v in dico_tmp.items()) #on converti les categories en entier y_test_int = y_test.map(dico) y_pred_int = pd.Series(y_pred).map(dico) dico_bokeh = Paragraph(text=" Dictionnaire des correspondances (clef, valeur) : \n "+str(dico), width= 1000) p7 = figure(title="Prediction de la variable : %s " % select_cible.value, x_axis_label = "x" , y_axis_label = "y") p7.circle(range(len(y_pred)), y_pred_int , fill_alpha=0.8 , color = 'red', legend_label = "Prédiction")#,source=source) p7.circle(range(len(y_test)), y_test_int , fill_alpha=0.4 , color = 'blue', legend_label = "Echantillon test") #données réelles p7.plot_width = 900 resu4 = row(column(p7, dico_bokeh),Classification_metrics(clf,X_train,y_train,X_test,y_test, exec_time, name)) return resu4
def create_plots(): t0 = time.time() timer = Paragraph() test_names = [x for x in test_select.value.split(',') if x] logging.info('test_names: `{}`'.format(test_names)) metric_names = [x for x in metric_select.value.split(',') if x] logging.info('metric_names: `{}`'.format(metric_names)) if not test_names or not metric_names: timer.text = 'Neither test_names nor metric_names can be blank.' draw_base_ui(timer, test_select, metric_select) return data = metric_compare.fetch_data(test_names, metric_names) if data.empty: timer.text = 'No data found. Double check metric/test names.' draw_base_ui(timer, test_select, metric_select) return plots = metric_compare.make_plots(test_names, metric_names, data) plot_rows = [row(p) for p in plots] if plots else [] base_rows = [row(timer), row(test_select), row(metric_select)] curdoc().clear() curdoc().add_root( column( children=base_rows + plot_rows, ) ) t1 = time.time() timer.text = '(Execution time: %s seconds)' % round(t1 - t0, 4)
def forecast_tab(data, ticker): pg_title = Paragraph() pg_title.text = '[ ' + ticker + ' ] CLOSE PRICE FORECAST' # Create a row layout layout = row(pg_title) # Make a tab with the layout tab = Panel(child=layout, title='Forecast') return tab
def update(attr, old, new): if old == new: return t0 = time.time() timer = Paragraph() timer.text = '(Executing query...)' test_name_para = Paragraph() test_name_para.text = 'Metrics for: {}'.format(test_select.value) curdoc().clear() base_rows = [row(test_name_para), row(test_select, metric_select, timer)] curdoc().add_root(column(children=base_rows, )) test_name = test_select.value if test_name not in test_names: timer.text = 'Invalid test_name: {}'.format(test_name) return metric_substr = metric_select.value cutoff_timestamp = ( datetime.datetime.now() - datetime.timedelta(days=30)).strftime('%Y-%m-%d %H:%M:%S UTC') data = metric_history.fetch_data(test_name, cutoff_timestamp) plots = metric_history.make_plots(test_name, metric_substr, data) plot_rows = [row(p) for p in plots] if plots else [] curdoc().clear() curdoc().add_root(column(children=base_rows + plot_rows, )) t1 = time.time() timer.text = '(Execution time: %s seconds)' % round(t1 - t0, 4)
def __init__(self): self.idLabel = Paragraph(text='ID = ') self.speciesLabel = Paragraph(text='Species = ') self.typeLabel = Paragraph(text='Type = ') self.birthDateLabel = Paragraph(text='Birth Date = ') self.notesLabel = PreText(text='Notes = ') self.addNoteButton = Button(label='Add Note') self.imagesLabel = Paragraph(text='# of Images = ') self.loadImageButton = Button(label='Upload Image', button_type='success') self.deleteButton = Button(label='Delete Sample!!', button_type='danger') self.widget = Column(self.idLabel, self.speciesLabel, self.typeLabel, self.birthDateLabel, self.notesLabel, self.addNoteButton, self.imagesLabel, self.loadImageButton, self.deleteButton)
def hookUpPlots(pCandle, pBuySell, pVolume, divCandle, divText, crosshairTool, pDebug): pCandle.x_range = pBuySell.x_range pVolume.x_range = pBuySell.x_range pCandle.add_tools(crosshairTool) pBuySell.add_tools(crosshairTool) pVolume.add_tools(crosshairTool) pCandle.xaxis.ticker = [8.75, 9, 9.5, 10, 10.5, 11, 11.5, 13, 13.5, 14, 14.5, 14.75] pCandle.xaxis.major_label_overrides = { 8.5:"8:30", 8.75:"8:45", 9:"9:00", 9.5:"9:30", 10:"10:00", 10.5:"10:30", 11:"11:00", 11.5:"11:30", 13:"13:00", 13.5:"13:30", 14:"14:00", 14.5:"14:30", 14.75:"14:45"} pBuySell.xaxis.ticker = pCandle.xaxis.ticker pVolume.xaxis.ticker = pCandle.xaxis.ticker pVolume.xaxis.major_label_overrides = pCandle.xaxis.major_label_overrides def btnStart_clicked(event): btnStart._document.get_model_by_name("btnStart").label = "Started!" # activation_function() def activation_function(): btnStart._document.add_periodic_callback(lambda: updateDoc(btnStart._document), 1000) btnStart._document.get_model_by_name("btnStart").label = "Started!" btnStart.disabled = True pLabel = Paragraph(text="Debug information (please ignore): ", width=pDebug.width, height=10, name="pLabel") btnStart = Button(label="Start automatic update", button_type="success", name="btnStart") btnStart.on_event(ButtonClick, btnStart_clicked) return row(column(pCandle, pBuySell, pVolume), column(divCandle, btnStart, divText, pLabel, pDebug)), \ activation_function
def make_plot(self, dataframe): temp_df = dataframe.groupby(['hour']).mean().reset_index() TOOLS = 'save,pan,box_zoom,reset,wheel_zoom,hover' self.plot = figure(title="Gas variations wrt hours", y_axis_type="linear", plot_height=400, tools=TOOLS, plot_width=800) self.plot.xaxis.axis_label = 'Hour of day' self.plot.yaxis.axis_label = 'ppm' self.plot.line(temp_df.hour, temp_df.co, line_color="purple", line_width=3, name="CO") self.plot.line(temp_df.hour, temp_df.co2, line_color="blue", line_width=3, name="CO2") self.plot.line(temp_df.hour, temp_df.h2, line_color="green", line_width=3, name="H2") self.title = Paragraph(text=TITLE) return column(self.title, self.plot)
def make_plot(self, dataframe): self.source = ColumnDataSource(data=dataframe) self.plot = figure(x_axis_type="datetime", plot_width=400, plot_height=300, tools='', toolbar_location=None) vbar = self.plot.vbar(x='date', top='prcp', width=1, color='#fdae61', source=self.source) hover_tool = HoverTool(tooltips=[ ('Value', '$y'), ('Date', '@date_readable'), ], renderers=[vbar]) self.plot.tools.append(hover_tool) self.plot.xaxis.axis_label = None self.plot.yaxis.axis_label = None self.plot.axis.axis_label_text_font_style = 'bold' self.plot.x_range = DataRange1d(range_padding=0.0) self.plot.grid.grid_line_alpha = 0.3 self.title = Paragraph(text=TITLE) return column(self.title, self.plot)
def _create_aspectratio_config(self): self.sld_obs_ar = None self.sld_data_ar = None self.sld_vol_ar = None self.sld_ind_ar = None title = Paragraph( text='Aspect Ratios', css_classes=['config-title']) self.sld_obs_ar = Slider( title='Observer Aspect Ratio', value=self.scheme.obs_aspectratio, start=0.1, end=20.0, step=0.1) self.sld_data_ar = Slider( title='Data Aspect Ratio', value=self.scheme.data_aspectratio, start=0.1, end=20.0, step=0.1) self.sld_vol_ar = Slider( title='Volume Aspect Ratio', value=self.scheme.vol_aspectratio, start=0.1, end=20.0, step=0.1) self.sld_ind_ar = Slider( title='Indicator Aspect Ratio', value=self.scheme.ind_aspectratio, start=0.1, end=20.0, step=0.1) return column([title, self.sld_obs_ar, self.sld_data_ar, self.sld_vol_ar, self.sld_ind_ar])
def make_plot(self, dataframe): self.source = ColumnDataSource(data=dataframe) self.plot = figure( x_axis_type="datetime", plot_width=600, plot_height=300, tools='', toolbar_location=None) self.plot.quad( top='max_temp', bottom='min_temp', left='left', right='right', color=Blues4[2], source=self.source, legend='Magnitude') line = self.plot.line( x='date', y='avg_temp', line_width=3, color=Blues4[1], source=self.source, legend='Average') hover_tool = HoverTool(tooltips=[ ('Value', '$y'), ('Date', '@date_readable'), ], renderers=[line]) self.plot.tools.append(hover_tool) self.plot.xaxis.axis_label = None self.plot.yaxis.axis_label = None self.plot.axis.axis_label_text_font_style = 'bold' self.plot.x_range = DataRange1d(range_padding=0.0) self.plot.grid.grid_line_alpha = 0.3 self.title = Paragraph(text=TITLE) return column(self.title, self.plot)
def _get_panel(self): ''' Returns the panel for tab ''' title = Paragraph( text='Client Configuration', css_classes=['panel-title']) button = Button( label='Save', button_type='success', width_policy='min') button.on_click(self._on_button_save_config) # layout for config area config = column( [self._create_fill_gaps_config(), self._create_lookback_config(), self._create_plotgroup_config(), self._create_aspectratio_config()], sizing_mode='scale_width') # layout for config buttons buttons = column([button]) # config layout child = column( children=[title, config, buttons], sizing_mode='scale_width') return child, 'Config'
def get_analyzers_tables( self, analyzer: bt.analyzers.Analyzer) -> (Paragraph, List[DataTable]): """Return a header for this analyzer and one *or more* data tables.""" if hasattr(analyzer, 'get_analysis_table'): title, table_columns_list = analyzer.get_analysis_table() else: # Analyzer does not provide a table function. Use our generic one title, table_columns_list = TableGenerator._get_analysis_table_generic( analyzer) param_str = get_params_str(analyzer.params) if len(param_str) > 0: title += f' ({param_str})' elems: List[DataTable] = [] for table_columns in table_columns_list: cds = ColumnDataSource() columns = [] for i, c in enumerate(table_columns): col_name = f'col{i}' cds.add(c[2:], col_name) columns.append( TableColumn(field=col_name, title=c[0], formatter=self._get_formatter(c[1]))) column_height = len(table_columns[0]) * 25 elems.append( DataTable(source=cds, columns=columns, index_position=None, height=column_height)) return Paragraph(text=title, style={'font-size': 'large'}), elems
def make_plot(self, dataframe): self.source = ColumnDataSource(data=dataframe) palette = all_palettes['Set2'][6] hover_tool = HoverTool(tooltips=[ ("Value", "$y"), ("Year", "@year"), ]) self.plot = figure(plot_width=600, plot_height=300, tools=[hover_tool], toolbar_location=None) columns = { 'pm10': 'PM10 Mass (µg/m³)', 'pm25_frm': 'PM2.5 FRM (µg/m³)', 'pm25_nonfrm': 'PM2.5 non FRM (µg/m³)', 'lead': 'Lead (¹/₁₀₀ µg/m³)', } for i, (code, label) in enumerate(columns.items()): self.plot.line(x='year', y=code, source=self.source, line_width=3, line_alpha=0.6, line_color=palette[i], legend=label) self.title = Paragraph(text=TITLE) return column(self.title, self.plot)
def errorMessage(errText): pre = PreText(text="""Your text is initialized with the 'text' argument. The remaining Paragraph arguments are 'width' and 'height'. For this example, those values are 500 and 100 respectively.""", width=500, height=100) pre = Paragraph(text=errText, width=500, height=100) return pre
def test_set_style(self, bokeh_model_page: BokehModelPage) -> None: para = Paragraph(text=text, style={'font-size': '26px'}) page = bokeh_model_page(para) el = find_element_for(page.driver, para) assert 'font-size: 26px;' in el.get_attribute('style') assert page.has_no_console_errors()
def test_displays_div_as_text(self, bokeh_model_page): para = Paragraph(text=text, css_classes=["foo"]) page = bokeh_model_page(para) el = page.driver.find_element_by_css_selector('.foo div p') assert el.get_attribute("innerHTML") == escape(text, quote=None) assert page.has_no_console_errors()
def test_set_style(self, bokeh_model_page): para = Paragraph(text=text, css_classes=["foo"], style={'font-size': '20pt'}) page = bokeh_model_page(para) el = page.driver.find_element_by_css_selector('.foo div') assert 'font-size: 20pt;' in el.get_attribute('style') assert page.has_no_console_errors()
def _create_lookback_config(self): title = Paragraph( text='Lookback period', css_classes=['config-title']) self.sld_lookback = Slider( title='Period for data to plot', value=self._client.lookback, start=1, end=200, step=1) return column([title, self.sld_lookback], sizing_mode='stretch_width')
def fsgd(X,Y): start_time = time.time() blabla5 = PreText(text=" SGD selected") scaler = StandardScaler(with_mean=False, copy=True) Feature_norm = scaler.fit_transform(X) #in case different scaled data type_feature = np.dtype(Y).name if ('int' in type_feature) or ('float' in type_feature): #Regression X_train, X_test, y_train, y_test = train_test_split(Feature_norm, Y, train_size=0.8) #or Feature_norm instead of X Regressor = SGDRegressor(max_iter=10**7//len(X_train)+1) #Model instance, empirically result for max_iter with 10**6 params2 = {'alpha':[ 1e-3, 1e-4, 1e-5, 1e-6 ], 'penalty':['l1', 'l2'], 'loss':['squared_loss','huber','epsilon_insensitive']} #Paramètres à tester clf = GridSearchCV(Regressor, param_grid=params2, cv=5, n_jobs=6) #,scoring=scorer) clf.fit(X_train, y_train) #On applique sur les données d'apprentissage #predictions on train data y_train_predict=clf.predict(X_train) #predictions on test data y_pred = clf.predict(X_test) print(clf.best_params_)#Meilleur paramètrage end_time = time.time() exec_time = round(end_time - start_time, 2) p5 = figure(title="Prediction de la variable : %s " % select_cible.value) p5.circle(range(len(y_pred)), y_pred[np.argsort(y_test)] , fill_alpha=0.8 , color = 'red', legend_label = "Prédiction")#,source=source) p5.line(range(len(y_test)), np.sort(y_test) , color = 'blue', legend_label = "Echantillon test") #données réelles p5.plot_width = 900 resu5 = row(p5, Regression_metrics(clf, X_train,y_train,X_test,y_test, exec_time, blabla5)) #column(blabla5,model_info,pre5,learn)) return resu5 else : #Classification X_train, X_test, y_train, y_test = train_test_split(Feature_norm, Y, train_size=0.8, stratify = Y) #stratify to avoid missing classes Classifier = SGDClassifier(max_iter=10**7//len(X_train)+1) #Model instance, empirically result for max_iter with 10**6 params = {'alpha':[ 1e-3, 1e-4, 1e-5, 1e-6 ], 'penalty':['l1', 'l2'], 'loss':['hinge','log']} #Paramètres à tester clf = GridSearchCV(Classifier, param_grid=params, cv=5, n_jobs=6)#scoring=scorer) clf.fit(X_train, y_train) #On applique sur les données d'apprentissage #predictions on train data y_train_predict=clf.predict(X_train) #predictions on test data y_pred=clf.predict(X_test) # Évaluation de l'algorithme print(clf.best_params_) end_time = time.time() exec_time = round(end_time - start_time, 2) #Graphique categ = y_test.astype("category") dico_tmp = dict(enumerate(categ.cat.categories)) dico = dict((v, k) for k, v in dico_tmp.items()) #on converti les categories en entier y_test_int = y_test.map(dico) y_pred_int = pd.Series(y_pred).map(dico) dico_bokeh = Paragraph(text=" Dictionnaire des correspondances (clef, valeur) : \n "+str(dico), width= 1000) #Graphiique p5 = figure( title="Prediction de la variable : %s " % select_cible.value, x_axis_label = "x" , y_axis_label = "y") p5.circle(range(len(y_test)), y_test_int, fill_alpha=0.8 , color = 'blue', legend_label = "Echantillon test") #données réelles p5.circle(range(len(y_pred)), y_pred_int, fill_alpha=0.4 , color = 'red', legend_label = "Prédiction")#,source=source) p5.plot_width = 900 resu5 = row(column(p5,dico_bokeh), Classification_metrics(clf, X_train,y_train,X_test,y_test, exec_time, blabla5)) #column(blabla5,model_info,pre5,learn)) return resu5
def test_displays_div_as_text(self, bokeh_model_page: BokehModelPage) -> None: para = Paragraph(text=text) page = bokeh_model_page(para) el = find_element_for(page.driver, para, "div p") assert el.get_attribute("innerHTML") == escape(text, quote=None) assert page.has_no_console_errors()
def _get_panel(self): title = Paragraph(text='Source Code', css_classes=['panel-title']) child = column([ title, Div(text=self._getSource(), css_classes=['source-pre'], sizing_mode='stretch_width') ], sizing_mode='stretch_width') return child, 'Source Code'
def fknn(X, Y): nomal = PreText(text=" KNN selected") start_time = time.time() X_train, X_test, y_train, y_test = train_test_split(X, Y, train_size=0.8) #List Hyperparameters that we want to tune. leaf_size = list(range(1, 10)) n_neighbors = list(range(1, 10, 2)) p = [1, 2] #Convert to dictionary hyperparameters = dict(leaf_size=leaf_size, n_neighbors=n_neighbors, p=p) #Create new KNN object knn_2 = KNeighborsClassifier() #Fit the model clf = GridSearchCV(knn_2, hyperparameters, cv=10) clf.fit(X_train, y_train) y_pred = clf.predict(X_test) end_time = time.time() exec_time = round(end_time - start_time, 2) #Graphique categ = y_test.astype("category") dico_tmp = dict(enumerate(categ.cat.categories)) dico = dict((v, k) for k, v in dico_tmp.items()) #on converti les categories en entier y_test_int = y_test.map(dico) y_pred_int = pd.Series(y_pred).map(dico) dico_bokeh = Paragraph( text=" Dictionnaire des correspondances (clef, valeur) : \n " + str(dico), width=1000) p7 = figure(title="Prediction de la variable : %s " % select_cible.value, x_axis_label="x", y_axis_label="y") p7.circle(range(len(y_pred)), y_pred_int, fill_alpha=0.8, color='red', legend_label="Prédiction") #,source=source) p7.circle(range(len(y_test)), y_test_int, fill_alpha=0.4, color='blue', legend_label="Echantillon test") #données réelles p7.plot_width = 900 resu3 = row( column(p7, dico_bokeh), Classification_metrics(clf, X_train, y_train, X_test, y_test, exec_time, nomal)) return resu3
def download_tab(data, ticker): data_df = ColumnDataSource(data) datefmt = DateFormatter(format="dd-M-yyyy") pfmt = NumberFormatter(format="0.00") # Columns of table table_columns = [TableColumn(field='Date', title='Trade Date', formatter=datefmt), TableColumn(field='Open', title='Open', formatter=pfmt), TableColumn(field='High', title='High', formatter=pfmt), TableColumn(field='Low', title='Low', formatter=pfmt), TableColumn(field='Close', title='Close', formatter=pfmt), TableColumn(field='Change %', title='Change (%)')] stocks_data = DataTable(source=data_df, columns=table_columns, width=1000) pg_title = Paragraph(text = '[ '+ticker+' ] HISTORICAL DATA') about_ticker = Paragraph(text="""Safaricom Plc, formerly Safaricom Limited, is a telecommunications company. The Company provides integrated telecommunication services, including mobile and fixed voice, short messaging service (SMS), data, Internet and M-PESA, a service to send and receive money or pay for goods and services through a mobile phone. It also provides financial services and enterprise solutions to businesses and the public sector. The Company's voice services include national and international roaming services. It offers mobile handsets, mobile broadband modems, routers, tablets and notebooks. Its converged business solutions include fixed voice service for corporate and Small and Medium-sized Enterprises (SMEs), mobile solutions and fixed data for homes and businesses using fixed lease lines, and Internet solutions for enterprises and hosted services, such as cloud hosting, domains and security services. The Company offers bill payment, bulk payments and dividend payments..""", width=200, height=100) disclaimer = Paragraph(text="""Disclaimer: All investments and trading in the stock market involve risk. Any decisions to place trades in the financial markets, including trading in stock or options or other financial instruments is a personal decision that should only be made after thorough research, including a personal risk and financial assessment and the engagement of professional assistance to the extent you believe necessary. The trading strategies or related information mentioned in this article is for informational purposes only.""") layout = column(pg_title, stocks_data, about_ticker, disclaimer) tab = Panel(child = layout, title = 'Historical Data') return tab
def bkapp(curdoc): #import time #time.sleep(5) """ df = sea_surface_temperature.copy() source = ColumnDataSource(data=df) plot = figure(x_axis_type='datetime', y_range=(0, 25), y_axis_label='Temperature (Celsius)', title="Sea Surface Temperature at 43.18, -70.43") plot.line('time', 'temperature', source=source) def callback(attr, old, new): if new == 0: data = df else: data = df.rolling('{0}D'.format(new)).mean() source.data = data """ slider = pn.widgets.FloatSlider(start=-10, end=10, value=0, step=0.01, title="Alpha") @pn.depends(slider.param.value) def create_sine_plot(alpha): plot = figure(y_range=(-15, 15)) data = np.linspace(-10, 10, 500) y = alpha * np.sin(data) plot.line(x=data, y=y) plot.sizing_mode = "stretch_both" return plot paragraph = Paragraph(text="IOloop's id: %s" % str(id(bokeh_server.io_loop.asyncio_loop))) row = pn.Column(slider, create_sine_plot, name="chart_1") row.sizing_mode = "stretch_both" row.server_doc(curdoc) other_figure = figure(title="Jajaja") other_figure.scatter(x=[1, 2, 3], y=[4, 5, 6]) other_figure.sizing_mode = "stretch_both" pn.Pane(other_figure, name="chart_2").server_doc(curdoc) #curdoc.theme = Theme(filename="theme.yaml") # Options for Jinja template rendered by the Bokeh Server # (as opposed of by Starlette): curdoc.template = (Environment(loader=FileSystemLoader( searchpath="templates")).get_template("index.html")) curdoc.template_variables["rendered_by_bokeh_server"] = True
def createPlots(): ######################################## BS Pressure Plot ######################################## sourceBuySell, sourceVolume = requestHoseData() pBuySell = Figure(plot_width=PLOT_WIDTH, plot_height=BUYSELL_PLOT_HEIGHT, name="pltBuySell") pBuySell.xaxis.ticker = [8.75, 9, 9.5, 10, 10.5, 11, 11.5, 13, 13.5, 14, 14.5, 14.75] pBuySell.xaxis.major_label_overrides = { 8.5: "8:30", 8.75: "8:45", 9: "9:00", 9.5: "9:30", 10: "10:00", 10.5: "10:30", 11: "11:00", 11.5: "11:30", 13: "13:00", 13.5: "13:30", 14: "14:00", 14.5: "14:30", 14.75: "14:45"} pBuySell.line(x='index', y='buyPressure', source=sourceBuySell, color='green', legend_label="Tổng đặt mua", name="glyphSellPressure") pBuySell.line(x='index', y='sellPressure', source=sourceBuySell, color='red', legend_label="Tổng đặt bán", name="glyphBuyPressure") wz = WheelZoomTool(dimensions="width"); pBuySell.add_tools(wz); pBuySell.toolbar.active_scroll = wz pBuySell.toolbar.logo = None pBuySell.axis[0].visible = False pBuySell.legend.location = "top_left" pBuySell.legend.click_policy = "hide" pBuySell.legend.background_fill_alpha = 0.0 ######################################## Volume Plot ######################################## pVolume = Figure(width=PLOT_WIDTH, height=VOLUME_PLOT_HEIGHT, tools="pan, reset", name="pltVolume") pVolume.toolbar.logo = None wz = WheelZoomTool(dimensions="height"); pVolume.add_tools(wz); pVolume.toolbar.active_scroll = wz pVolume.vbar(x='index', top='totalValue', width=1 /60, color='blue', source=sourceVolume, fill_alpha=LIQUIDITY_ALPHA, line_alpha=LIQUIDITY_ALPHA, name="glyphTotalValue", legend_label="Thanh khoản toàn tt") pVolume.vbar(x='index', top='nnBuy', width=1/1.2/60, color='green', source=sourceVolume ,name="glyphNNBuy", legend_label="NN mua",) pVolume.vbar(x='index', top='nnSell', width=1/1.2/60, color='red', source=sourceVolume ,name="glyphNNSell", legend_label="NN bán",) pVolume.x_range = pBuySell.x_range pVolume.y_range=Range1d(-10, 45) pVolume.legend.location = "top_left" pVolume.legend.click_policy = "hide" pVolume.legend.background_fill_alpha = 0.0 ######################################### OHLC plot ######################################### orders, source, pressure = requestPSData() plotOhlc = createOhlcPlot(source) pCandle, divCandle = hookupFigure(plotOhlc) # "divCustomJS" "pltOHLC" "glyphOHLCSegment" pDebug = Paragraph(text=f"""["num_ps_orders": "{len(orders['index'])}"]\n""" """""", width=DIV_TEXT_WIDTH, height=100, name="pDebug") ################################# Putting all plots together ################################ def activation_function(): pBuySell._document.add_periodic_callback(lambda: updateDoc(pBuySell._document), 500) print("Document activated !") return pCandle, pBuySell, pVolume, divCandle , activation_function, sourceBuySell, sourceVolume, pDebug
def _create_fill_gaps_config(self): title = Paragraph( text='Fill Gaps', css_classes=['config-title']) if self._client.fill_gaps: active = [0] else: active = [] self.chk_fill_gaps = CheckboxGroup( labels=['Fill gaps with data'], active=active) return column([title, self.chk_fill_gaps], sizing_mode='stretch_width')
def update_reviews(attr, old, new): data_set = pd.read_csv('Outputs/data_set.csv') i = int(star_rating.value) #output_review_list = extract_ngrams(str(data_set[(data_set['Star_count'] == i)]['Review'].values),2,3) data_set_blob = data_set.copy() data_set_blob['Noun_sentences'] = data_set_blob['Review'].apply(lambda x:get_nouns(x)) n_gram_blob = TextBlob(str(data_set_blob[(data_set_blob['Star_count'] == i)]['Noun_sentences'].values)) #Styling the paragraph element text1 = Paragraph(style={'font-variant': 'small-caps','font-family': "Tahoma"}) text1.text="" #review1 = text_cleaner(str(n_gram_blob.ngrams(1)[0])) #review2 = text_cleaner(str(n_gram_blob.ngrams(1)[1])) review1 = text_cleaner(n_gram_blob.ngrams(1)[1][0]) review2 = text_cleaner(n_gram_blob.ngrams(1)[2][0]) text1.text = "Top "+str(i)+" star reviews feel: "+review1+", followed by "+review2 curdoc().add_root(Row(text1))
def paragraph(name, error): if error < .5: add_text = "Which means they are pretty similar" elif .5 < error < 1: add_text = "Which means they are sort of similar" else: add_text = ". Which means there are not many similar flavors" front = "Your flavor is closest to: " second = ". This has and error of " third = ("{:05.2f}".format(error)) text = front + str(name) + second + third + add_text para = Paragraph(text=text, width=250) return para
def _get_help_widgets(self): models_help = Paragraph(text=""" When using a linear regression model, you should be aware that the errors should be stochastically independent, and the residuals of the model should be normally distributed. (For more detail check this article: https://en.wikipedia.org/wiki/Errors_and_residuals) This preconditions often breaks something called autocorrelation. That means that the current error in measurement is affected by the previous error. This often happens in time series like measuring the temperature. Fortunately, we have some methods on how to get rid of autocorrelation. We can compute the autocorrelation coefficient as a correlation between residuals[1, ..., n-1] and residuals [2, ..., n]. When this coefficient is close to 1 or -1, we have a problem. One method is GLS, which can take the autocorrelation coefficient into account and do some magic. The other is the Cochranne-Orcutt method, which tries to modify data with this correlation coefficient and eliminate the correlation. For more info you can check these: https://en.wikipedia.org/wiki/Autocorrelation https://en.wikipedia.org/wiki/Generalized_least_squares """) quantiles_help = Paragraph(text=""" The points should be close to the line. """) index_help_1 = Paragraph(text=""" Those should be randomly distributed """) index_help_2 = Paragraph(text=""" around Reziduals axe. """) index_help = column(index_help_1, index_help_2) reziduals_help = Paragraph(text=""" There should NOT be any correlation apparent. That means the line should be ideally horizontal. """) plot_help = Paragraph(text=""" All lines in the main plot represents some form of regression. Blue is Ordinary least squares. Green is Generalized least squares. Red is Cochranne-Orcutt method. """) usage_help = Paragraph(text=""" Select Point draw tool in the tool box and click to add point. You can also select one point or multiple points by holding shift. Then you can drag them or remove with Backspace. You can select more points with lasso. Then select Point draw tool and drag them or remove them. """) std_data_help = Paragraph(text=""" Implicit dataset describes number of birds of particular species which were observed on Hawaii. For better fit, data on both axes were somehow normalized. """) return models_help, quantiles_help, index_help, reziduals_help, \ plot_help, usage_help, std_data_help
def text(): return Paragraph(text=""" Bacon ipsum dolor amet hamburger brisket prosciutto, pork ball tip andouille sausage landjaeger filet mignon ribeye ground round. Jerky fatback cupim landjaeger meatball pork loin corned beef, frankfurter short ribs short loin bresaola capicola chuck kevin. Andouille biltong turkey, tail t-bone ribeye short loin tongue prosciutto kielbasa short ribs boudin. Swine beef ribs tri-tip filet mignon bresaola boudin beef meatball venison leberkas fatback strip steak landjaeger drumstick prosciutto. Bacon ipsum dolor amet hamburger brisket prosciutto, pork ball tip andouille sausage landjaeger filet mignon ribeye ground round. Jerky fatback cupim landjaeger meatball pork loin corned beef, frankfurter short ribs short loin bresaola capicola chuck kevin. Andouille biltong turkey, tail t-bone ribeye short loin tongue prosciutto kielbasa short ribs boudin. Swine beef ribs tri-tip filet mignon bresaola boudin beef meatball venison leberkas fatback strip steak landjaeger drumstick prosciutto. """)