def polinet(): error = None if request.method == 'POST': try: app_polinet.vars['pol_name'] = get_pol_name(request.form['pol_name']) except: app_polinet.vars['pol_name'] = 'Not a valid name' else: app_polinet.vars['pol_name'] = 'Bernard Sanders' app.vars['pol_data'] = pd.DataFrame([[1,2,3,1,3,2,4,1]]) fig = TimeSeries(app.vars['pol_data']) plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files ) script, div = components(fig, INLINE) return render_template('polinet.html', name=app_polinet.vars['pol_name'], data=app_polinet.vars['pol_data'], plot_script=script, plot_div=div, plot_resources=plot_resources)
def index(): error = None if request.method == 'POST': try: app.vars['stock_name'] = stock_to_caps(request.form['ticker']) app.vars['data_table'] = get_data(app.vars['stock_name']) except: app.vars['stock_name'] = 'GOOG' app.vars['data_table'] = get_data('GOOG') else: app.vars['stock_name'] = 'GOOG' app.vars['data_table'] = get_data('GOOG') fig = TimeSeries(app.vars['data_table']) plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files ) script, div = components(fig, INLINE) return render_template('index.html', name=app.vars['stock_name'], data=app.vars['data_table'], plot_script=script, plot_div=div, plot_resources=plot_resources)
def graph(): df = app.vars['data'] # Create a line plot from our data. p = figure(width=700, height=500, x_axis_type="datetime", title="Data from Quandle WIKI set") for category in app.vars['features']: p.line(pd.to_datetime(df['Date']), df[category], color=app.vars['color'][category], line_width=1, legend=app.vars['ticker'] + ": " + category) p.legend.orientation = "top_right" # Configure resources to include BokehJS inline in the document. plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) script, div = components(p, INLINE) html = render_template( 'graph.html', ticker=app.vars['ticker'], plot_script=script, plot_div=div, plot_resources=plot_resources ) return encode_utf8(html)
def plot_data(): """Obtains post data and produces two graphs: volume of posts mentioning 'dengue' versus time; and volume of posts versus neighborhood """ (df, df_volume, df_by_location) = get_data() script1, div1 = volumeGraph(df_volume) script2, div2 = locationGraph(df_by_location) plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) html = flask.render_template( 'embed.html', plot_script1=script1, plot_div1=div1, plot_script2=script2, plot_div2=div2, plot_resources=plot_resources ) return encode_utf8(html)
def index(): error = None if request.method == 'POST': try: app.vars['stock_name'] = stock_to_caps(request.form['ticker']) app.vars['data_table'] = get_data(app.vars['stock_name']) except: app.vars['stock_name'] = 'GOOG' app.vars['data_table'] = get_data('GOOG') else: app.vars['stock_name'] = 'GOOG' app.vars['data_table'] = get_data('GOOG') fig = TimeSeries(app.vars['data_table']) plot_resources = RESOURCES.render(js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files) script, div = components(fig, INLINE) return render_template('index.html', name=app.vars['stock_name'], data=app.vars['data_table'], plot_script=script, plot_div=div, plot_resources=plot_resources)
def wordcloud(): req_id = cache_request() req = REQUESTS[req_id] start_years = [] end_years = [] for i in range(req.num_intervals): start_years.append(i * req.interval_len + req.year1) end_years.append(min(req.year2, start_years[-1] + req.interval_len)) plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) plot_scripts, plot_divs = req.get_bokeh_word_frequencies() num_docs = req.get_num_docs() return render_template('wordcloud.html', year1=req.year1, year2=req.year2, words=req.stop_words, req_id=req_id, percent1=req.percent1, percent2=req.percent2, num_intervals=req.num_intervals, start_years=start_years, end_years=end_years, plot_resources=plot_resources, plot_scripts=plot_scripts, plot_divs=plot_divs, num_docs=num_docs, side_by_side=req.side_by_side)
def graph(): df = app.vars['data'] # Create a line plot from our data. p = figure(width=700, height=500, x_axis_type="datetime", title="Data from Quandle WIKI set") for category in app.vars['features']: p.line(pd.to_datetime(df['Date']), df[category], color=app.vars['color'][category], line_width=1, legend=app.vars['ticker'] + ": " + category) p.legend.orientation = "top_right" # Configure resources to include BokehJS inline in the document. plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) script, div = components(p, INLINE) html = render_template('graph.html', ticker=app.vars['ticker'], plot_script=script, plot_div=div, plot_resources=plot_resources) return encode_utf8(html)
def polynomial(): """ Very simple embedding of a polynomial chart""" # Grab the inputs arguments from the URL # This is automated by the button args = flask.request.args # Get all the form arguments in the url with defaults color = colors[getitem(args, 'color', 'Black')] _from = int(getitem(args, '_from', 0)) to = int(getitem(args, 'to', 10)) # Create a polynomial line graph x = list(range(_from, to + 1)) fig = figure(title="Polynomial") fig.line(x, [i ** 2 for i in x], color=color, line_width=2) # Configure resources to include BokehJS inline in the document. # For more details see: # http://bokeh.pydata.org/en/latest/docs/reference/resources_embedding.html#module-bokeh.resources plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) # For more details see: # http://bokeh.pydata.org/en/latest/docs/user_guide/embedding.html#components script, div = components(fig, INLINE) html = flask.render_template( 'embed.html', plot_script=script, plot_div=div, plot_resources=plot_resources, color=color, _from=_from, to=to ) return encode_utf8(html)
def stock_plot(): # compute start and end time end_time = time.strftime('%Y-%m-%d',time.localtime(time.time())) start_time = time.strftime('%Y-%m-%d',time.localtime(time.time()-60*60*24*30)) # construct API request req = 'https://www.quandl.com/api/v3/datasets/WIKI/'+app.vars['stock_name']+'.json?start_date='+start_time+'&end_date='+end_time # read API results using pandas df = pandas.read_json(req) df = df['dataset'] id = df["column_names"].index('Close') date_id = df["column_names"].index('Date') data = np.asarray(df['data']) plot_time = data[:,date_id] plot_data = data[:,id] plot_time = np.asarray(plot_time,dtype=np.datetime64) plot_data = np.asarray(plot_data) # construct response html # Get all the form arguments in the url with defaults fig = figure(title="Closing Price of "+app.vars['stock_name'],x_axis_type="datetime") fig.line(plot_time, plot_data) fig.xaxis.axis_label = 'Date' fig.yaxis.axis_label = 'Closing Price' plot_resources = RESOURCES.render(js_raw=INLINE.js_raw,css_raw=INLINE.css_raw,js_files=INLINE.js_files,css_files=INLINE.css_files,) script, div = components(fig) return render_template('stock_plot.html',stock_name = app.vars['stock_name'],plot_script=script, plot_div=div,plot_resources=plot_resources)
def polynomial(): """ Very simple embeding of a polynomial chart """ # Grab input arguments from the URL # This is automated by the button args = flask.request.args # Get all the form arguments in their url with defaults color = colors[getitem(args,'color','Black')] fig = figure(width=800, height=350,x_axis_type='datetime', title='%s closing prices for last 30 days' % st) fig.line(dates, closing_prices, line_width=2, color=color, alpha=0.2, legend='close') fig.xaxis.axis_label = 'Date' fig.yaxis.axis_label = 'Price' # Configure resources to include BokehJS inline in the document. plot_resources = RESOURCES.render( js_raw = INLINE.js_raw, css_raw = INLINE.css_raw, js_files = INLINE.js_files, css_files = INLINE.css_files ) script, div = components(fig, INLINE) html = flask.render_template( 'embed.html', plot_script = script, plot_div=div, plot_resources=plot_resources, color=color ) return encode_utf8(html)
def newapplet(): theme = request.args.get('theme', 'default') INLINE = Resources( mode="inline", minified=False, ) templname = "stocks_custom.html" plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) p = create_main_plot(theme) plot_script, extra_divs = components({ "main_plot": p, "selection_plot": create_selection_plot(p, theme), }) themes = ["default", "dark"] options = {k: 'selected="selected"' if theme == k else "" for k in themes} return render_template( templname, theme=theme, extra_divs=extra_divs, plot_script=plot_script, plot_resources=plot_resources, theme_options=options, )
def stock(): """ Very simple plot of stock closing price for last month or so""" # Grab the inputs arguments from the URL # This is automated by the button args = flask.request.args return 'ALA' # Get all the form arguments in the url with defaults if 'company' in args.keys() and args['company']: company = args['company'] else: company = 'GOOG' cl = requests.get("https://www.quandl.com/api/v3/datasets/WIKI/%s.json?order=asc&rows=31&start_date=2015-07-01&end_date=2015-09-03" % (company)) if cl.status_code == 200: c2=cl.content stock=simplejson.loads(c2) abb=stock['dataset']['dataset_code'] datanames=stock['dataset']['column_names'] data=stock['dataset']['data'] dataorg=pd.DataFrame(data,columns=datanames) dataorg['Date']=pd.to_datetime(dataorg['Date']) else: ######## THIS IS NOT RECOMMENDED, because now it just returns an error message if not find the ticker. return 'Error! Ticker does not exist!' # Create a graph fig = figure(x_axis_type="datetime") fig.line(dataorg.Date,dataorg.Close) fig.title="Stock closing price (%s), from 07-01-2015 " % (company) # fig.xaxis_axis_label='Date' # fig.yaxis_axis_label='Price' # Configure resources to include BokehJS inline in the document. # For more details see: # http://bokeh.pydata.org/en/latest/docs/reference/resources_embedding.html#module-bokeh.resources plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) # For more details see: # http://bokeh.pydata.org/en/latest/docs/user_guide/embedding.html#components script, div = components(fig, INLINE) html = flask.render_template( 'embed.html', plot_script=script, plot_div=div, plot_resources=plot_resources, # color=color, company=company ) return encode_utf8(html)
def get_bubble_html(): layout = _get_plot() with open('assets/bubble_template.html', 'r') as f: template = Template(f.read()) bokeh_js = RESOURCES.render(js_raw=INLINE.js_raw) script, div = components(layout) html = template.render( title="Bokeh - Gapminder demo", bokeh_js=bokeh_js, plot_script=script, plot_div=div, ) return html
def close_price_chart(): global st, dates, closing_prices # receiving data st = request.form['stock_ticker'] today = datetime.datetime.now() end_date = today.strftime("%Y-%m-%d") month_ago = today - datetime.timedelta(days=30) start_date = month_ago.strftime("%Y-%m-%d") request_str = 'https://www.quandl.com/api/v3/datasets/WIKI/%s.json/?start_date=%s&end_date=%s' % (st,start_date,end_date) r = requests.get(request_str) response_json = r.json() col_names = response_json['dataset']['column_names'] all_data = pd.DataFrame(response_json['dataset']['data'], columns=col_names) #all_data.set_index('Date', inplace=True) #all_data.Close # constructing plot color = 'Black' dates = np.array(all_data['Date'], dtype=np.datetime64) closing_prices = np.array(all_data['Close']) fig = figure(width=800, height=350,x_axis_type='datetime', title='%s closing prices for last 30 days' % st) fig.line(dates, closing_prices, line_width=2, color=color, alpha=0.2, legend='close') fig.xaxis.axis_label = 'Date' fig.yaxis.axis_label = 'Price' # Configure resources to include BokehJS inline in the document. plot_resources = RESOURCES.render( js_raw = INLINE.js_raw, css_raw = INLINE.css_raw, js_files = INLINE.js_files, css_files = INLINE.css_files ) script, div = components(fig, INLINE) html = flask.render_template( 'embed.html', plot_script = script, plot_div=div, plot_resources=plot_resources, color=color ) return encode_utf8(html)
def result(): args = session['company'] r = rq.get('https://www.quandl.com/api/v1/datasets/WIKI/' + args['company'] + '.json') if not r.status_code == 200: flask.flash(Message) return flask.redirect(flask.url_for('index')) # return flask.render_template('welcome.html') company = args['company'] data = r.json() price = pd.DataFrame(data['data']) price.columns = data['column_names'] TOOLS = "pan,wheel_zoom,box_zoom,reset,save" r = figure(x_axis_type = "datetime", x_axis_label = "Time", tools=TOOLS) tim = [np.datetime64(i) for i in price['Date']] datatype = ['Close','Adj. Volume','Volume'] for i in xrange(3): if datatype[i] in args.keys(): r.line(tim, price[datatype[i]], color=colors[i], legend=company+' : '+datatype[i]) r.title = "Stock data from Quandl WIKI set" r.grid.grid_line_alpha=0.3 # Configure resources to include BokehJS inline in the document. # For more details see: # http://bokeh.pydata.org/en/latest/docs/reference/resources_embedding.html#module-bokeh.resources plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) # For more details see: # http://bokeh.pydata.org/en/latest/docs/user_guide/embedding.html#components script, div = components(r, INLINE) html = flask.render_template( 'result.html', plot_script=script, plot_div=div, plot_resources=plot_resources, company=company ) return encode_utf8(html)
def get_bubble_html(plot=None): if plot: layout = plot else: layout = _get_plot() with open('assets/bubble_template.html', 'r') as f: template = Template(f.read()) resources = Resources(mode='server', root_url='/tree/') bokeh_js = RESOURCES.render(js_files=resources.js_files) script, div = components(layout) html = template.render( title="Bokeh - Gapminder demo", bokeh_js=bokeh_js, plot_script=script, plot_div=div, ) return html
def newapplet(): symbol = request.args.get('symbol', '') INLINE = Resources(mode="inline", minified=False,) if symbol: templname = "feat_static.html" else: symbol = 'HEMP' templname = "feat_home.html" app = StaticDash.create(symbol) plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) plot_script, extra_divs = components( { "table_ranks": app.table_stocks_rank, "main_app": app.children[0], "btn_detect_pumps": app.btn_detect_pumps, "dlg_peaks": app.PEAKS, }, INLINE ) def get_id(div): soup = BeautifulSoup(div) tag=soup.div return soup.div.get('id') div_ids = {k: get_id(v) for k, v in extra_divs.items()} return render_template( templname, app_url = gen_config['bokeh_url'] + "/bokeh/jsgenerate/VBox/Dashboard/Dashboard", symbol = symbol, extra_divs = extra_divs, plot_script = plot_script, plot_resources=plot_resources, bokeh_divs_id_json = json.dumps(div_ids), bokeh_divs_id = div_ids )
def newapplet(): symbol = request.args.get('symbol', '') INLINE = Resources( mode="inline", minified=False, ) if symbol: templname = "feat_static.html" else: symbol = 'HEMP' templname = "feat_home.html" app = StaticDash.create(symbol) plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) plot_script, extra_divs = components( { "table_ranks": app.table_stocks_rank, "main_app": app.children[0], "btn_detect_pumps": app.btn_detect_pumps, "dlg_peaks": app.PEAKS, }, INLINE) def get_id(div): soup = BeautifulSoup(div) tag = soup.div return soup.div.get('id') div_ids = {k: get_id(v) for k, v in extra_divs.items()} return render_template(templname, app_url=gen_config['bokeh_url'] + "/bokeh/jsgenerate/VBox/Dashboard/Dashboard", symbol=symbol, extra_divs=extra_divs, plot_script=plot_script, plot_resources=plot_resources, bokeh_divs_id_json=json.dumps(div_ids), bokeh_divs_id=div_ids)
def index(): args = flask.request.args color = flask.request.values.get("color", "black") p = create_plot(300, np.sin, np.cos, color=color) plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) script, div = components(p, INLINE) html = flask.render_template('embed.html', plot_script=script, plot_div=div, plot_resources=plot_resources, color=color) return encode_utf8(html)
def static_html(template, resources=CDN, as_utf8=True, **kw): """Render static html document. This is a minor modification of bokeh.embed.file_html Args: template (Template): jinja2 HTML document template resources (Resources): a resource configuration for BokehJS assets kw: keyword argument list of bokeh components. Keywords must match with keywords in template Returns: html : standalone HTML document with embedded plot """ plot_resources = RESOURCES.render( js_raw = resources.js_raw, css_raw = resources.css_raw, js_files = resources.js_files, css_files = resources.css_files, ) with open (os.path.join(sml_base_path(), 'static/basic.css')) as fh: css = "".join(fh.readlines()) # Hack to get on-the-fly double mapping. Can this be rewritten with e.g. map? def _update(kw): tmp = {} for k,v in kw.items(): if (isinstance(v, Widget)): tmp.update({k : [{'script' : s, 'div' : d } for s,d in [components(v, resources)]][0]}) elif (isinstance(v, dict)): if not v: tmp.update(v) else: v.update(_update(v)) else: tmp.update({k:v}) return tmp kw.update(_update(kw)) if as_utf8: return encode_utf8(template.render(plot_resources=plot_resources, css=css, **kw)) else: return template.render(plot_resources=plot_resources, css=css, **kw)
def index(): if request.method == 'GET': return render_template('index.html') else: #request was a POST app.vars['ticker'] = request.form['ticker'] app.vars['feature'] = request.form['features'] url = 'https://www.quandl.com/api/v3/datasets/WIKI/' + str( app.vars['ticker'] ) + '.json?order=asc&rows=31&start_date=2015-08-01&end_date=2015-08-31' r = requests.get(url) dat1 = json.loads(r.text) df = pd.DataFrame(dat1['dataset']['data'], columns=dat1['dataset']['column_names']) df['Date'] = pd.to_datetime(df['Date']) if app.vars['feature'] == 'Close': ylab = "Closing price" if app.vars['feature'] == 'Adj. Close': ylab = "Adjusted closing price" if app.vars['feature'] == 'Volume': ylab = "Volume" fig = TimeSeries(df[str(app.vars['feature'])], df['Date'], title=str(app.vars['ticker']) + " August 2015", ylabel=ylab) resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) script, div = components(fig, INLINE) html = render_template('index_post.html', plot_script=script, plot_div=div, plot_resources=resources) return encode_utf8(html)
def root(): resources = Resources("inline") scatter = scatter_example() scatter_el = VBox(children=[HBox(children=[scatter])]) plot_script, plot_div = components(scatter_el, resources) plot_resources = RESOURCES.render( js_raw=resources.js_raw, css_raw=resources.css_raw, js_files=resources.js_files, css_files=resources.css_files, ) html = render_template("test.html", plot_resources=plot_resources, plot_script=plot_script, plot_div=plot_div) return encode_utf8(html)
def index(self): args = flask.request.args filters = select_filter() pairs = select_pair() # Get all the form arguments in the url with defaults filter = int(getitem(args, 'filter', 1)) pair = int(getitem(args, 'pair', 0)) component = getitem(args, 'component', 'ZZ') format = getitem(args, 'format', 'stack') db = connect() station1, station2 = pairs[pair]['text'].replace('.','_').split(' - ') start, end, dates = build_ref_datelist(db) i, result = get_results(db,station1, station2, filter, component, dates, format=format) if format == 'stack': if i != 0: maxlag = float(get_config(db, 'maxlag')) x = np.linspace(-maxlag, maxlag, get_maxlag_samples(db)) y = result db.close() fig = figure(title=pairs[pair]['text'], plot_width=1000) fig.line(x, y, line_width=2) plot_resources = RESOURCES.render( js_raw=CDN.js_raw, css_raw=CDN.css_raw, js_files=CDN.js_files, css_files=CDN.css_files, ) script, div = components(fig, INLINE) return self.render( 'admin/results.html', plot_script=script, plot_div=div, plot_resources=plot_resources, filter_list=filters, pair_list=pairs )
def index(): args = flask.request.args color = flask.request.values.get("color", "black") p = create_plot(300, np.sin, np.cos, color=color) plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) script, div = components(p, INLINE) html = flask.render_template( 'embed.html', plot_script=script, plot_div=div, plot_resources=plot_resources, color=color ) return encode_utf8(html)
def root(): resources = Resources("inline") scatter = scatter_example() scatter_el = VBox(children=[HBox(children=[scatter])]) plot_script, plot_div = components(scatter_el, resources) plot_resources = RESOURCES.render( js_raw = resources.js_raw, css_raw = resources.css_raw, js_files = resources.js_files, css_files = resources.css_files, ) html = render_template("test.html", plot_resources = plot_resources, plot_script = plot_script, plot_div = plot_div ) return encode_utf8(html)
def stock_plot(): # compute start and end time end_time = time.strftime('%Y-%m-%d', time.localtime(time.time())) start_time = time.strftime('%Y-%m-%d', time.localtime(time.time() - 60 * 60 * 24 * 30)) # construct API request req = 'https://www.quandl.com/api/v3/datasets/WIKI/' + app.vars[ 'stock_name'] + '.json?start_date=' + start_time + '&end_date=' + end_time # read API results using pandas df = pandas.read_json(req) df = df['dataset'] id = df["column_names"].index('Close') date_id = df["column_names"].index('Date') data = np.asarray(df['data']) plot_time = data[:, date_id] plot_data = data[:, id] plot_time = np.asarray(plot_time, dtype=np.datetime64) plot_data = np.asarray(plot_data) # construct response html # Get all the form arguments in the url with defaults fig = figure(title="Closing Price of " + app.vars['stock_name'], x_axis_type="datetime") fig.line(plot_time, plot_data) fig.xaxis.axis_label = 'Date' fig.yaxis.axis_label = 'Closing Price' plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) script, div = components(fig) return render_template('stock_plot.html', stock_name=app.vars['stock_name'], plot_script=script, plot_div=div, plot_resources=plot_resources)
def root(): """ Returns the spectrogram of audio data served from /data """ spectrogram = make_spectrogram() resources = Resources("inline") plot_resources = RESOURCES.render( js_raw=resources.js_raw, css_raw=resources.css_raw, js_files=resources.js_files, css_files=resources.css_files, ) plot_script, plot_div = components(spectrogram, resources) html = flask.render_template( "spectrogram.html", plot_resources=plot_resources, plot_script=plot_script, plot_div=plot_div, ) return encode_utf8(html)
def plot_data(): """Obtains post data and produces two graphs: volume of posts mentioning 'dengue' versus time; and volume of posts versus neighborhood """ (df, df_volume, df_by_location) = get_data() script1, div1 = volumeGraph(df_volume) script2, div2 = locationGraph(df_by_location) plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) html = flask.render_template('embed.html', plot_script1=script1, plot_div1=div1, plot_script2=script2, plot_div2=div2, plot_resources=plot_resources) return encode_utf8(html)
def wordcloud(): req_id = cache_request() req = REQUESTS[req_id] start_years = [] end_years = [] for i in range(req.num_intervals): start_years.append(i*req.interval_len + req.year1) end_years.append(min(req.year2, start_years[-1] + req.interval_len)) plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) plot_scripts, plot_divs = req.get_bokeh_word_frequencies() num_docs = req.get_num_docs() return render_template('wordcloud.html', year1=req.year1, year2=req.year2, words=req.stop_words, req_id=req_id, percent1=req.percent1, percent2=req.percent2, num_intervals=req.num_intervals, start_years=start_years, end_years=end_years, plot_resources=plot_resources, plot_scripts=plot_scripts, plot_divs=plot_divs, num_docs=num_docs, side_by_side=req.side_by_side)
def polynomial(): """ Very simple embedding of a polynomial chart""" # Grab the inputs arguments from the URL # This is automated by the button args = flask.request.args # Get all the form arguments in the url with defaults color = colors[getitem(args, 'color', 'Black')] _from = int(getitem(args, '_from', 0)) to = int(getitem(args, 'to', 10)) # Create a polynomial line graph x = list(range(_from, to + 1)) fig = figure(title="Polynomial") fig.line(x, [i**2 for i in x], color=color, line_width=2) # Configure resources to include BokehJS inline in the document. # For more details see: # http://bokeh.pydata.org/en/latest/docs/reference/resources_embedding.html#module-bokeh.resources plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) # For more details see: # http://bokeh.pydata.org/en/latest/docs/user_guide/embedding.html#components script, div = components(fig, INLINE) html = flask.render_template('embed.html', plot_script=script, plot_div=div, plot_resources=plot_resources, color=color, _from=_from, to=to) return encode_utf8(html)
def index(): # Create layout c_map = climate_map() ts = timeseries() l = legend() t = title() map_legend = hplot(c_map, l) layout = vplot(t, map_legend, ts) plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) script, div = components(layout, INLINE) html = flask.render_template( 'embed.html', plot_script=script, plot_div=div, plot_resources=plot_resources, ) return encode_utf8(html)
def root(): """ Returns the spectrogram of audio data served from /data """ spectrogram = make_spectrogram() resources = Resources("inline") plot_resources = RESOURCES.render( js_raw = resources.js_raw, css_raw = resources.css_raw, js_files = resources.js_files, css_files = resources.css_files, ) plot_script, plot_div = components( spectrogram, resources ) html = flask.render_template( "spectrogram.html", plot_resources = plot_resources, plot_script = plot_script, plot_div = plot_div, ) return encode_utf8(html)
def index(): args = flask.request.args selected_team = flask.request.values.get("selected_team", "LAA") selected_year = int(flask.request.values.get("selected_year", "2012")) p = create_plot(selected_team, selected_year) plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) script, div = components(p, INLINE) html = flask.render_template( 'embed.html', plot_script=script, plot_div=div, plot_resources=plot_resources, selected_team=selected_team, selected_year=selected_year, years=distinct_years, teams=distinct_teams, ) return encode_utf8(html)
def index(): if request.method == 'GET': return render_template('index.html') else: #request was a POST app.vars['ticker'] = request.form['ticker'] app.vars['features'] = request.form.getlist('features') #### my code from ipython notebook #### # set variables closing, adj_closing, volume ticker = app.vars['ticker'] closing = 'Close' in app.vars['features'] adj_closing = 'Adj. Close' in app.vars['features'] volume = 'Volume' in app.vars['features'] """ f = open('%s.txt'%(app.vars['ticker']),'w') f.write('Ticker: %s\n'%(app.vars['ticker'])) f.write('Features: %s\n'%(app.vars['features'])) f.write('Include Closing: %s\n'%(closing)) f.write('Include Adjusted Closing: %s\n'%(adj_closing)) f.write('Include Volume: %s\n'%(volume)) f.close() """ # import data from Quandle WIKI r = requests.get('https://www.quandl.com/api/v3/datasets/WIKI/'+ticker+'.json?order=asc') parsed_json = json.loads(r.text) # import to dataframe df = pd.DataFrame(parsed_json['dataset']['data']) # rename columns, set date to datetime type df.columns = parsed_json['dataset']['column_names'] df['Date'] = pd.to_datetime(df['Date']) company = parsed_json['dataset']['name'].split('.') company = company[0] def generate_close(ticker, closing): if closing: return p1.line(df['Date'], df['Close'], color='#0000FF', legend=ticker+": Close") def generate_adjclose(ticker,adj_closing): if adj_closing: return p1.line(df['Date'], df['Adj. Close'], color='#009933', legend=ticker+": Adj. Close") def generate_volume(ticker, volume): if volume: return p1.line(df['Date'], df['Volume'], color='#CC3300', legend=ticker+": Volume") from bokeh.plotting import figure, show, output_file, vplot output_file("stockstest.html", title=company) p1 = figure(x_axis_type = "datetime") # generate lines for the selected options generate_close(ticker, closing) generate_adjclose(ticker, adj_closing) generate_volume(ticker, volume) if not (closing or adj_closing or volume): generate_close(ticker, True) p1.title = ticker + " (Data from Quandle WIKI set)" p1.grid.grid_line_alpha=1.0 p1.xaxis.axis_label = 'Date' plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) script, div = components(p1, INLINE) html = flask.render_template( 'index_post.html', plot_script=script, plot_div=div, plot_resources=plot_resources, ticker=ticker, company=company ) return encode_utf8(html)
def salt_step_peptide_analysis(dtafile_pk): ''' Determines how many filtered peptides are present per chromatography step and draws a plot ''' current_dtafile = models.DTAFile.query.get_or_404(dtafile_pk) dtafile_quickinfo_dict = views_helpers.get_json_response('api.dtafile_quickinfo', dtafile_pk) dtafile_quickinfo_dict = json.loads(dtafile_quickinfo_dict) dtafile_json = views_helpers.get_json_response('api.dtafile_json', dtafile_pk) dtafile_json = json.loads(dtafile_json) parent_dbsearch = models.DBSearch.query.get_or_404(dtafile_quickinfo_dict['parent_dbsearch']) sqt_files = parent_dbsearch.sqtfiles.all() parent_dataset = models.Dataset.query.get_or_404(parent_dbsearch.dataset_id) def get_distinct_psm_ids(dtaselect_parser): psms = set() for locus in dtaselect_parser: for peptide in locus['peptides']: psm_id = str(peptide['LCStep'])+'_'+str(peptide['Scan'])+'_'+str(peptide['ChargeState']) psms.add(psm_id) return psms def make_LCStep_histogram(psm_ids_set): full_lcstep_count = [] for psm in psm_ids_set: full_lcstep_count.append(psm.split('_')[0]) return Counter(full_lcstep_count) psm_ids = get_distinct_psm_ids(dtafile_json['data']) hist = make_LCStep_histogram(psm_ids) labels, values = zip(*sorted(hist.items(), key=lambda x: int(x[0]))) labels = np.array(labels) values = np.array(values) fig = figure(title="Peptides per LC Step", y_range=[0, max(values)*1.25], plot_height=400, plot_width=700) fig.rect(x=labels, y=values/2, width=0.8, height=values) fig.xaxis.axis_label = 'chromatography step' fig.yaxis.axis_label = '# peptides identified' from bokeh.models import FixedTicker fig.xaxis[0].ticker.desired_num_ticks = len(labels) plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) script, div = components(fig, INLINE) return render_template( 'plots/empty.html', dtafile_quickinfo_dict=dtafile_quickinfo_dict, current_dtafile=current_dtafile, parent_dbsearch=parent_dbsearch, sqt_files=sqt_files, parent_dataset=parent_dataset, plot_script=script, plot_div=div, plot_resources=plot_resources, # color=color, # _from=_from, # to=to, )
def stock_plot(): """30-day price history for a user-provided stock ticker""" # Grab the inputs arguments from the URL # This is automated by the button args = flask.request.args # Set default for ticker ticker = getitem(args, 'ticker', 'TWTR') url = 'https://www.quandl.com/api/v1/datasets/WIKI/' + ticker + '.json' r = requests.get(url) if (type(r.json().get('error')) == unicode): # any returned error message means there's uh, an error return flask.render_template('error.html') else: # otherwise, we've got our stock ticker_data = r.json().get('data') # highly silly way to extract the full company name from the data ticker_company_name = r.json().get('name') ticker_company_name = \ ticker_company_name[0:(ticker_company_name.find(')'))+1] # gather column names ticker_columns = r.json().get('column_names') # and chuck everything into a DataFrame temp_df = pd.DataFrame(ticker_data, columns=ticker_columns) # then pare down for the DataFrame we'll use df = temp_df[['Date', 'Open', 'Close', 'Low', 'High']] df.columns = ['date', 'open', 'close', 'low', 'high'] df["date"] = pd.to_datetime(df["date"]) df.index = df.date # various gyrations to grab the last month worth of data # find the last day in the data lastdate = df['date'][0] # set the first date to one month back from the last date firstdate = lastdate - pd.DateOffset(months=1) # then grab the last month worth of data df = df[lastdate:firstdate] # calculations associated with generating candlesticks, taken from: # http://bokeh.pydata.org/en/latest/docs/gallery/candlestick.html mids = (df.open + df.close) / 2 spans = abs(df.close - df.open) inc = df.close > df.open dec = df.open > df.close # set candlestick duration (in ms) w = 24 * 60 * 60 * 1000 # configure plot TOOLS = "pan,wheel_zoom,box_zoom,reset,save" p = figure(title=ticker + " Daily Candles", x_axis_type="datetime", \ tools=TOOLS, plot_width=1000, toolbar_location="left") p.segment(df.date, df.high, df.date, df.low, color="black") p.rect(df.date[inc], mids[inc], w, spans[inc], fill_color="#abdb8d", \ line_color="black") p.rect(df.date[dec], mids[dec], w, spans[dec], fill_color="#F2583E", \ line_color="black") p.title = ticker_company_name + ' Daily Candles' p.xaxis.major_label_orientation = pi / 4 p.grid.grid_line_alpha = 0.3 p.xaxis.axis_label = 'Date' p.yaxis.axis_label = 'Price' # Configure resources to include BokehJS inline in the document. # For more details see: # http://bokeh.pydata.org/en/latest/docs/reference/resources_embedding.html#module-bokeh.resources plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) # For more details see: # http://bokeh.pydata.org/en/latest/docs/user_guide/embedding.html#components script, div = components(p, INLINE) html = flask.render_template('embed.html', plot_script=script, plot_div=div, plot_resources=plot_resources, ticker=ticker) return encode_utf8(html)
def stock(): stockcode = request.args.get('stockcode') stockperiod = str(request.args.get('period')) if stockcode and stockcode.strip(): #request data from QuanDL baseURL = 'https://www.quandl.com/api/v1/datasets/WIKI/' periodURL = { '1M': '?trim_start=' + (datetime.datetime.now() - datetime.timedelta(days=30)).strftime('%Y-%m-%d'), '6M': '?trim_start=' + (datetime.datetime.now() - datetime.timedelta(days=183)).strftime('%Y-%m-%d'), '1Y': '?trim_start=' + (datetime.datetime.now() - datetime.timedelta(days=365)).strftime('%Y-%m-%d'), 'All': '', 'None': '' } jsonURL = baseURL + stockcode + '.json' + periodURL[stockperiod] jsonRespond = requests.get(jsonURL) HTTPstatusCode = jsonRespond.status_code print '[URL] ' + jsonURL print '[HTTP] ' + str(HTTPstatusCode) print '[Stockcode]' + stockcode print '[Period] ' + stockperiod #parse data if HTTP Status is OK if HTTPstatusCode == 200: jheader = (jsonRespond.json())['column_names'] jdata = (jsonRespond.json())['data'] stockdata = pd.DataFrame(jdata, columns=jheader) stockdata["Date"] = pd.to_datetime(stockdata["Date"]) print stockdata.head() #To calculate the positions of the bars mids = (stockdata.Open + stockdata.Close) / 2 spans = abs(stockdata.Close - stockdata.Open) #To check the up/down of the day to determin the bar color inc = stockdata.Close > stockdata.Open dec = stockdata.Open > stockdata.Close w = 12 * 60 * 60 * 1000 # half day in ms #Render Chart fig = figure( title=None, plot_width=600, plot_height=480, x_axis_type="datetime", toolbar_location="below", tools="crosshair, pan,wheel_zoom,box_zoom,reset,resize") fig.segment(stockdata.Date, stockdata.High, stockdata.Date, stockdata.Low, color="black") fig.rect(stockdata.Date[inc], mids[inc], w, spans[inc], fill_color="#D5E1DD", line_color="black") fig.rect(stockdata.Date[dec], mids[dec], w, spans[dec], fill_color="#F2583E", line_color="black") plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) script, div = components(fig, INLINE) html = render_template('stock.html', status={ 'code': 1, 'msg': 'OK' }, stock={ 'code': stockcode, 'period': stockperiod }, plot={ 'script': script, 'div': div, 'resources': plot_resources }) else: html = render_template('stock.html', status={ 'code': 2, 'msg': 'Server Error' }, stock={ 'code': stockcode, 'period': stockperiod }) else: html = render_template('stock.html', status={ 'code': 3, 'msg': 'Please Enter a Stockcode' }, stock={ 'code': 'None', 'period': 'None' }) return html
def stock(): stockcode = request.args.get("stockcode") stockperiod = str(request.args.get("period")) if stockcode and stockcode.strip(): # request data from QuanDL baseURL = "https://www.quandl.com/api/v1/datasets/WIKI/" periodURL = { "1M": "?trim_start=" + (datetime.datetime.now() - datetime.timedelta(days=30)).strftime("%Y-%m-%d"), "6M": "?trim_start=" + (datetime.datetime.now() - datetime.timedelta(days=183)).strftime("%Y-%m-%d"), "1Y": "?trim_start=" + (datetime.datetime.now() - datetime.timedelta(days=365)).strftime("%Y-%m-%d"), "All": "", "None": "", } jsonURL = baseURL + stockcode + ".json" + periodURL[stockperiod] jsonRespond = requests.get(jsonURL) HTTPstatusCode = jsonRespond.status_code print "[URL] " + jsonURL print "[HTTP] " + str(HTTPstatusCode) print "[Stockcode]" + stockcode print "[Period] " + stockperiod # parse data if HTTP Status is OK if HTTPstatusCode == 200: jheader = (jsonRespond.json())["column_names"] jdata = (jsonRespond.json())["data"] stockdata = pd.DataFrame(jdata, columns=jheader) stockdata["Date"] = pd.to_datetime(stockdata["Date"]) print stockdata.head() # To calculate the positions of the bars mids = (stockdata.Open + stockdata.Close) / 2 spans = abs(stockdata.Close - stockdata.Open) # To check the up/down of the day to determin the bar color inc = stockdata.Close > stockdata.Open dec = stockdata.Open > stockdata.Close w = 12 * 60 * 60 * 1000 # half day in ms # Render Chart fig = figure( title=None, plot_width=600, plot_height=480, x_axis_type="datetime", toolbar_location="below", tools="crosshair, pan,wheel_zoom,box_zoom,reset,resize", ) fig.segment(stockdata.Date, stockdata.High, stockdata.Date, stockdata.Low, color="black") fig.rect(stockdata.Date[inc], mids[inc], w, spans[inc], fill_color="#D5E1DD", line_color="black") fig.rect(stockdata.Date[dec], mids[dec], w, spans[dec], fill_color="#F2583E", line_color="black") plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files ) script, div = components(fig, INLINE) html = render_template( "stock.html", status={"code": 1, "msg": "OK"}, stock={"code": stockcode, "period": stockperiod}, plot={"script": script, "div": div, "resources": plot_resources}, ) else: html = render_template( "stock.html", status={"code": 2, "msg": "Server Error"}, stock={"code": stockcode, "period": stockperiod}, ) else: html = render_template( "stock.html", status={"code": 3, "msg": "Please Enter a Stockcode"}, stock={"code": "None", "period": "None"}, ) return html
import bokeh from bokeh.embed import components from bokeh.plotting import figure from bokeh.resources import INLINE from bokeh.templates import RESOURCES from bokeh.io import vplot, hplot import numpy as np PLOT_RESOURCES = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) def plot_table_by_time(table): plots = [] table = table.set_index('time') for col in table: s = table[col] s.dropna(inplace=True) if not np.isscalar(s.values[0]): # replace with the sum s = s.apply(np.sum) x_range = plots[0].x_range if plots else None fig = figure(title=col, x_axis_type='datetime', x_range=x_range) fig.line(s.index, s, line_width=2) fig.circle(s.index, s, fill_color='white', size=8) plots.append(fig)
{{ plot_resources }} </head> <body> <h2>Resize the window to see some plots resizing</h2> <h3>Red - pan with responsive</h3> {{ plot_div.red }} <h3>Green - pan with resize & responsive (should maintain new aspect ratio)</h3> {{ plot_div.green }} <h3>Blue - pan no responsive</h3> {{ plot_div.blue }} {{ plot_script }} </body> </html> ''') resources = INLINE plot_resources = RESOURCES.render( js_raw=resources.js_raw, css_raw=resources.css_raw, js_files=resources.js_files, css_files=resources.css_files, ) script, div = components({'red': red, 'blue': blue, 'green': green}) html = template.render(plot_resources=plot_resources, plot_script=script, plot_div=div) html_file = 'embed_multiple_responsive.html' with open(html_file, 'w') as f: f.write(html) view(html_file)
def process(): """ Receive the upload smiles, process and retrieve results. """ from alchemy import alchemy from collections import OrderedDict if request.method == 'POST': render_template('pages/process.html') input_file = request.files['input_file'] background_file = request.files['background_file'] if input_file and allowed_file(input_file.filename): input_filename = secure_filename(input_file.filename) input_file.save(os.path.join(app.config['UPLOAD_FOLDER'], input_filename)) if background_file and allowed_file(background_file.filename): background_filename = secure_filename(background_file.filename) background_file.save(os.path.join(app.config['UPLOAD_FOLDER'], background_filename)) # Assemble arguments # input_file args = [ os.path.join(app.config['UPLOAD_FOLDER'], input_filename)] # background if background_file and allowed_file(background_file.filename): args += [ "-b", os.path.join(app.config['UPLOAD_FOLDER'], background_filename)] # input_type args += [ "-t", request.form.get('input_type')] # delimiter args += [ "-d", request.form.get('delimiter')] # header # annotation_output # background_annotation_output # enrichment_output # enrich # processors # tmp_dir # start processing data annotated_query, enriched_query = alchemy.main(args) # return results # Bokeh graph fig = figure(title="Volcano plot") fig.scatter(enriched_query.oddsratio, enriched_query.corrected_pvalue, color="#000000") fig.logo = None fig.toolbar_location = None # Configure resources to include BokehJS inline in the document. plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) script, div = components(fig) html = flask.render_template( 'pages/results.html', plot_script=script, plot_div=div, plot_resources=plot_resources, compounds=OrderedDict(zip( enriched_query.index, enriched_query.corrected_pvalue)) ) return encode_utf8(html) return render_template('pages/home.html')
def stock_plot(): """30-day price history for a user-provided stock ticker""" # Grab the inputs arguments from the URL # This is automated by the button args = flask.request.args # Set default for ticker ticker = getitem(args, 'ticker', 'TWTR') url = 'https://www.quandl.com/api/v1/datasets/WIKI/' + ticker + '.json' r = requests.get(url) if(type(r.json().get('error')) == unicode): # any returned error message means there's uh, an error return flask.render_template('error.html') else: # otherwise, we've got our stock ticker_data = r.json().get('data') # highly silly way to extract the full company name from the data ticker_company_name = r.json().get('name') ticker_company_name = \ ticker_company_name[0:(ticker_company_name.find(')'))+1] # gather column names ticker_columns = r.json().get('column_names') # and chuck everything into a DataFrame temp_df = pd.DataFrame(ticker_data,columns=ticker_columns) # then pare down for the DataFrame we'll use df = temp_df[['Date','Open', 'Close', 'Low', 'High']] df.columns = ['date','open', 'close', 'low', 'high'] df["date"] = pd.to_datetime(df["date"]) df.index = df.date # various gyrations to grab the last month worth of data # find the last day in the data lastdate = df['date'][0] # set the first date to one month back from the last date firstdate = lastdate - pd.DateOffset(months=1) # then grab the last month worth of data df = df[lastdate:firstdate] # calculations associated with generating candlesticks, taken from: # http://bokeh.pydata.org/en/latest/docs/gallery/candlestick.html mids = (df.open + df.close)/2 spans = abs(df.close-df.open) inc = df.close > df.open dec = df.open > df.close # set candlestick duration (in ms) w = 24*60*60*1000 # configure plot TOOLS = "pan,wheel_zoom,box_zoom,reset,save" p = figure(title=ticker + " Daily Candles", x_axis_type="datetime", \ tools=TOOLS, plot_width=1000, toolbar_location="left") p.segment(df.date, df.high, df.date, df.low, color="black") p.rect(df.date[inc], mids[inc], w, spans[inc], fill_color="#abdb8d", \ line_color="black") p.rect(df.date[dec], mids[dec], w, spans[dec], fill_color="#F2583E", \ line_color="black") p.title = ticker_company_name +' Daily Candles' p.xaxis.major_label_orientation = pi/4 p.grid.grid_line_alpha=0.3 p.xaxis.axis_label = 'Date' p.yaxis.axis_label = 'Price' # Configure resources to include BokehJS inline in the document. # For more details see: # http://bokeh.pydata.org/en/latest/docs/reference/resources_embedding.html#module-bokeh.resources plot_resources = RESOURCES.render( js_raw=INLINE.js_raw, css_raw=INLINE.css_raw, js_files=INLINE.js_files, css_files=INLINE.css_files, ) # For more details see: # http://bokeh.pydata.org/en/latest/docs/user_guide/embedding.html#components script, div = components(p, INLINE) html = flask.render_template( 'embed.html', plot_script=script, plot_div=div, plot_resources=plot_resources, ticker=ticker ) return encode_utf8(html)