Ejemplo n.º 1
0
def newapplet():
    theme = request.args.get('theme', 'default')
    INLINE = Resources(
        mode="inline",
        minified=False,
    )
    templname = "stocks_custom.html"

    js_resources = JS_RESOURCES.render(js_raw=INLINE.js_raw,
                                       js_files=INLINE.js_files)

    css_resources = CSS_RESOURCES.render(css_raw=INLINE.css_raw,
                                         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,
        js_resources=js_resources,
        css_resources=css_resources,
        theme_options=options,
    )
Ejemplo n.º 2
0
def newapplet():
    theme = request.args.get('theme', 'default')
    INLINE = Resources(mode="inline", minified=False,)
    templname = "stocks_custom.html"

    js_resources = JS_RESOURCES.render(
        js_raw=INLINE.js_raw,
        js_files=INLINE.js_files
    )

    css_resources = CSS_RESOURCES.render(
        css_raw=INLINE.css_raw,
        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,
        js_resources=js_resources,
        css_resources=css_resources,
        theme_options=options,
    )
Ejemplo n.º 3
0
def graphstocks(ssymbol):
    """ Very simple embedding of a polynomial chart"""
    # Grab the inputs arguments from the URL
    # This is automated by the button
    args = ["ADAM"] 
    args = 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)
    AAPL= pd.read_csv("https://ichart.yahoo.com/table.csv?s="+ssymbol+"&a=0&b=1&c=2000&d=0&e=1&f=2010",parse_dates=['Date'])   
    data = dict(AAPL=AAPL['Adj Close'], Date=AAPL['Date'])
    tsline = TimeSeries(data,x='Date', y='AAPL', ylabel='Stock Prices', legend=True)
    #tsline=TimeSeries(data,x='Date', y=['AAPL'], color=['AAPL'], dash=['AAPL'],
   #                   title="Timeseries", ylabel = 'Stock Prices', legend=True)
#    tspoint=TimeSeries(data,x='Date',y=[ssymbol], dash=[ssymbol],title="Timeseries",ylabel='Stock Prices', legend=True)
    output_file("timeseries.html")
    fig=vplot(tsline)
    
    # Configure resources to include BokehJS inline in the document.
    # For more details see:
    #   http://bokeh.pydata.org/en/latest/docs/reference/resources_embedding.html#bokeh-embed
    js_resources = JS_RESOURCES.render(
        js_raw=INLINE.js_raw,
        js_files=INLINE.js_files
    )

    css_resources = CSS_RESOURCES.render(
        css_raw=INLINE.css_raw,
        css_files=INLINE.css_files
    )
#from: http://bokeh.pydata.org/en/0.11.1/docs/releases/0.11.0.html  
# Before:

#html = file_html(layout, None, title=title, template=template, js_resources=js_resources, css_resources=css_resources)
#v0.11:
#
#html = file_html(layout, resources=(js_resources, css_resources), title=title, template=template)
 
   # For more details see:
    #   http://bokeh.pydata.org/en/latest/docs/user_guide/embedding.html#components
    script, div = components(fig, INLINE)
    html = render_template(
        'embed.html',
        plot_script=script,
        plot_div=div,
        js_resources=js_resources,
        css_resources=css_resources,
        color=color,
        _from=_from,
        to=to
    )
    return encode_utf8(html)
Ejemplo n.º 4
0
def model():
    pTOOLS = "crosshair,hover,pan,box_zoom,reset,save"
    p2 = figure(tools=pTOOLS,background_fill="#dbe0eb",
                x_range = (0,100),
                y_range =(80,100),
                x_axis_label='Decision Boundary (score)',
                y_axis_label='Precision',
                title='Recall and Precision',
                plot_height=600,
                plot_width=800)

    # Setting the second y axis range name and range
    p2.extra_y_ranges = {"foo": Range1d(start=-5, end=105)}

    # Adding the second axis to the plot.  
    p2.add_layout(LinearAxis(y_range_name="foo",axis_label="Recall", 
                             axis_label_text_color = "red",
                             major_label_text_color = "red"), 'right')

    source1 = ColumnDataSource(
        data=dict(precision = crit_r_c[1]*100, recall =  crit_r_c[2]*100.0/153546,
                 risk = 100 - crit_r_c[1]*100, miss = 100- crit_r_c[2]*100.0/153546))

    source2 = ColumnDataSource(
        data=dict(precision = crit_r_c[1]*100, recall =  crit_r_c[2]*100.0/153546,
                 risk = 100 - crit_r_c[1]*100, miss = 100- crit_r_c[2]*100.0/153546))


    p2.line(crit_r_c[0],crit_r_c[1]*100,line_color="blue", line_width=20, alpha=0.7,source=source1)
    p2.line(crit_r_c[0],crit_r_c[2]*100.0/153546,line_color="red", line_width=20, alpha=0.7,y_range_name="foo",source=source2)

    hover = p2.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([
        ('Decison Boundary (score)', '$x'),
        ("Precision            (%)","@precision"),
        ("Risk                 (%)", "@risk"),
        ("Recall               (%)", "@recall"),
        ("Missed Opportunity   (%)", "@miss"),

    ])

    js_resources2 = JS_RESOURCES.render(
        js_raw=INLINE.js_raw,
        js_files=INLINE.js_files)

    css_resources2 = CSS_RESOURCES.render(
        css_raw=INLINE.css_raw,
        css_files=INLINE.css_files)
    p2script, p2div = components(p2, INLINE)

    html = flask.render_template(
        'model.html',
        plot_script2=p2script, plot_div2=p2div, 
        js_resources=js_resources2,
        css_resources=css_resources2)
    return encode_utf8(html)
Ejemplo n.º 5
0
def test_file_html_handles_css_only_resources():
    css_resources = CSSResources()
    template = Template("<head>{{ bokeh_css }}</head><body></body>")
    output = embed.file_html(_embed_test_plot,
                             None,
                             "title",
                             template=template,
                             css_resources=css_resources)
    rendered_css = CSS_RESOURCES.render(css_raw=css_resources.css_raw)
    assert output == "<head>%s</head><body></body>" % rendered_css
Ejemplo n.º 6
0
def graphstocks(ssymbol, sdate, edate,color):
    stock = ssymbol
    if color not in colors:
        color="Black"
    api_url='https://www.quandl.com/api/v3/datasets/WIKI/%(symbol)s.json?api_key=%(key)s&start_date=%(sdate)s&end_date=%(edate)s' % {"symbol":stock, "key":YOURAPIKEY,"sdate":sdate, "edate":edate}
    session = requests.Session()
    session.mount('http://', requests.adapters.HTTPAdapter(max_retries=3))
    raw_data=session.get(api_url)
    aapl_stock=raw_data.json()
    color="Black"
    cnames = aapl_stock['dataset']['column_names']
    df = pandas.DataFrame(aapl_stock['dataset']['data'],columns=cnames) # create dataframe and assign column names
    df['Date']=pandas.to_datetime(df['Date']) # convert Date column to DateTime in place
    tsline = TimeSeries(df,x='Date', y='Close', ylabel=ssymbol+' Stock Prices', legend=True, color=colors[color])
    fig=vplot(tsline)
    # Configure resources to include BokehJS inline in the document.
    # For more details see:
    #   http://bokeh.pydata.org/en/latest/docs/reference/resources_embedding.html#bokeh-embed
    js_resources = JS_RESOURCES.render(
        js_raw=INLINE.js_raw,
        js_files=INLINE.js_files
    )

    css_resources = CSS_RESOURCES.render(
        css_raw=INLINE.css_raw,
        css_files=INLINE.css_files
    )
#from: http://bokeh.pydata.org/en/0.11.1/docs/releases/0.11.0.html  
# Before:

#html = file_html(layout, None, title=title, template=template, js_resources=js_resources, css_resources=css_resources)
#v0.11:
#
#html = file_html(layout, resources=(js_resources, css_resources), title=title, template=template)
 
   # For more details see:
    #   http://bokeh.pydata.org/en/latest/docs/user_guide/embedding.html#components
    script, div = components(fig, INLINE)
    html = render_template(
        'embed.html',
        plot_script=script,
        plot_div=div,
        js_resources=js_resources,
        css_resources=css_resources,
        color=color,
        _from=sdate,
        to=edate,
        symbol_lulu=ssymbol
    )
    return encode_utf8(html)
Ejemplo n.º 7
0
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#bokeh-embed
    js_resources = JS_RESOURCES.render(
        js_raw=INLINE.js_raw,
        js_files=INLINE.js_files
    )

    css_resources = CSS_RESOURCES.render(
        css_raw=INLINE.css_raw,
        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,
        js_resources=js_resources,
        css_resources=css_resources,
        color=color,
        _from=_from,
        to=to
    )
    return encode_utf8(html)
Ejemplo n.º 8
0
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#bokeh-embed
    js_resources = JS_RESOURCES.render(js_raw=INLINE.js_raw,
                                       js_files=INLINE.js_files)

    css_resources = CSS_RESOURCES.render(css_raw=INLINE.css_raw,
                                         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,
                                 js_resources=js_resources,
                                 css_resources=css_resources,
                                 color=color,
                                 _from=_from,
                                 to=to)
    return encode_utf8(html)
Ejemplo n.º 9
0
    {{ plot_div.blue }}

    {{ plot_script }}
    </body>
</html>
''')

resources = INLINE

js_resources = JS_RESOURCES.render(
    js_raw=resources.js_raw,
    js_files=resources.js_files
)

css_resources = CSS_RESOURCES.render(
    css_raw=resources.css_raw,
    css_files=resources.css_files
)

script, div = components({'red': red, 'blue': blue, 'green': green})

html = template.render(js_resources=js_resources,
                       css_resources=css_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)
Ejemplo n.º 10
0
app = flask.Flask(__name__)

colors = {
    'Black': '#000000',
    'Red':   '#FF0000',
    'Green': '#00FF00',
    'Blue':  '#0000FF',
}

js_resources = JS_RESOURCES.render(
    js_raw=INLINE.js_raw,
    js_files=INLINE.js_files
)

css_resources = CSS_RESOURCES.render(
    css_raw=INLINE.css_raw,
    css_files=INLINE.css_files
)

@app.route("/figure1")
def plot_data():
    # get data
    x = []
    y = []
    colors = []
    i = 0
    with open("data.csv", "r") as f:
        while True:
            line = f.readline()
            if len(line) == 0:
                break
            if i == 6:
Ejemplo n.º 11
0
def prediction():
    args = session['loan']
    Grade = args['sub_grade']

    x = pd.DataFrame(args,index=[0])
    x_dict = List2DictT.transform(x)

    x_vect = DictVectorT.transform(x_dict)
    x_y_prob = []
    for RF in FinalTotModes[:-1]:
        x_y_prob.append(RF.predict_proba(x_vect)[:,0])
    y_pred = FinalTotModes[-1].predict_proba(np.array(x_y_prob).T)
    YourLoan = int(y_pred[:,1]*100)
    Loc  = int(YourLoan/5)
    xgrades =[i for i in ScoreByGrade.index]

    Beats = ['%.2f' %(ScoreByGrade.PayoffProba.iloc[Loc]*100) + 
             ' (your loan is better than %.2f%% of loans)' % (sum(ScoreByGrade[Grade].iloc[:Loc]))]
    
    Median = MedianScore.loc[Grade].prob
    MedianLoc = MedianLoc = int(Median)/5+1

    TOOLS = "hover,pan,box_zoom,reset,save"
    p = figure(background_fill='white', 
               x_range=[2,102],
               x_axis_label='Score assigned by the model',
               y_range = [0, int(max(ScoreByGrade[Grade]))+3],
               title="Score of " + Grade + " loans",
               y_axis_label='Counts per 100 loans',
               tools = TOOLS,
               plot_width=1000, 
               plot_height=600)
    
    source1 = ColumnDataSource(
        data=dict(payoffProb = ScoreByGrade.PayoffProba.values*100, 
              distribution =  ScoreByGrade[Grade].values,
              scores = ['%d-%d' %(i-4,i) for i in ScoreByGrade.index]))
    source2 = ColumnDataSource(
        data=dict(payoffProb = Beats, distribution =[ScoreByGrade[Grade].iloc[Loc]],
                  scores = ['%d-%d' %(i-4,i) for i in [ScoreByGrade.index[Loc]]]))

    source3 = ColumnDataSource(
        data=dict(payoffProb = [ScoreByGrade.PayoffProba.iloc[MedianLoc]*100], 
                  distribution =[ScoreByGrade[Grade].iloc[MedianLoc]],
                  scores = ['%d' %(Median) ]))


    p.rect(xgrades, ScoreByGrade[Grade]/2,  0.6*5, ScoreByGrade[Grade],
        fill_color="#08c994",source = source1)
    p.rect([xgrades[Loc]], ScoreByGrade[Grade].iloc[Loc]/2,  0.6*5, ScoreByGrade[Grade].iloc[Loc],
        fill_color="#ff5a00",source = source2, legend='Score of your loan')
    # p.xaxis.major_label_orientation = np.pi/6
    p.rect([Median], (int(max(ScoreByGrade[Grade]))+1)/2.0,  0.15*5, (int(max(ScoreByGrade[Grade]))+1),
        fill_color="black",source = source3, legend='Average Score')

    # p.line([Median,Median],[0,int(max(ScoreByGrade[Grade]))+1],
    #         line_color="black", line_width=10, legend='Average Score',
    #         source = source3)


    hover = p.select(dict(type=HoverTool))
    hover.tooltips = OrderedDict([
        ("Score","@scores"),
        ("Within 100 loans", "@distribution in this group"),
        ('Payoff chance (%)', '@payoffProb'),
    ])

    js_resources = JS_RESOURCES.render(
        js_raw=INLINE.js_raw,
        js_files=INLINE.js_files
    )

    css_resources = CSS_RESOURCES.render(
        css_raw=INLINE.css_raw,
        css_files=INLINE.css_files
    )

    script, div = components(p, INLINE)

    if YourLoan>=60:
        ShouldOrNot = 'SHOULD'
        tmplt ="result_success.html"
    elif YourLoan>=50:
        ShouldOrNot = 'MAY'
        tmplt ="result_success.html"
    elif YourLoan>=40:
        ShouldOrNot = 'may NOT'
        tmplt ="result_failure.html"
    else:
        ShouldOrNot = 'should NOT'
        tmplt ="result_failure.html"

    pTOOLS = "crosshair,hover,pan,box_zoom,reset,save"
    p2 = figure(background_fill='white', 
               x_axis_label='Score assigned by the model',
               title="Score versus Success rate",
               y_axis_label='Success rate (%)',
               tools = pTOOLS,
               plot_width=1000, 
               plot_height=600)

    p2.line(ScoreByGrade.index,ScoreByGrade.PayoffProba*100,line_color="blue", line_width=20, alpha=0.7)
    r2 = p2.circle(Median,ScoreByGrade.PayoffProba.iloc[MedianLoc]*100-3,color="black",legend='Average Loan')
    r  = p2.circle(YourLoan,ScoreByGrade.PayoffProba.iloc[Loc]*100-3,color="#ff5a00",legend='Your Loan')
    def glyy(r,colors):
        glyph = r.glyph
        glyph.size = 40
        glyph.fill_alpha = 0.5
        glyph.line_color = colors
        glyph.line_dash = [6, 3]
        glyph.line_width = 2
    glyy(r,"#ff5a00")
    glyy(r2,"black")

    p2.grid.grid_line_alpha=0.7
    p2.legend.orientation = "top_left"
    hover2 = p2.select(dict(type=HoverTool))
    hover2.tooltips = OrderedDict([
        ('Score', "$x"),
        ('Payoff chance (%)', '$y')])

    js_resources2 = JS_RESOURCES.render(
        js_raw=INLINE.js_raw,
        js_files=INLINE.js_files)

    css_resources2 = CSS_RESOURCES.render(
        css_raw=INLINE.css_raw,
        css_files=INLINE.css_files)
    p2script, p2div = components(p2, INLINE)


    html = flask.render_template(
        tmplt,
        plot_script=script, plot_div=div, 
        plot_script2=p2script, plot_div2=p2div, 
        js_resources=js_resources,
        css_resources=css_resources,
        score=YourLoan,
        beats="%.2f" %(sum(ScoreByGrade[Grade].iloc[:Loc])),
        prob="%.2f" %(ScoreByGrade.PayoffProba.iloc[Loc]*100),
        invest=ShouldOrNot)

    return encode_utf8(html)
Ejemplo n.º 12
0
def static_html(template, title="bokehutils plot", resources=INLINE, css_raw=None, template_variables=None):
    """Render static html document.

    This is a minor modification of :py:meth:`bokeh.embed.file_html`.

    Args:
      template (Template): a Jinja2 HTML document template
      title (str): a title for the HTML document ``<title>`` tags.
      resources (Resources): a resource configuration for BokehJS assets
      css_raw (list): a list of file names for inclusion in the raw css

      template_variables (dict): variables to be used in the Jinja2
          template. In contrast to :py:meth:`bokeh.embed.file_html`,
          this is where plot objects are placed. The plot objects will
          be automagically split into script and div components. If
          used, the following variable names will be overwritten:
          title, js_resources, css_resources

    Returns:
      html : standalone HTML document with embedded plot

    """
    # From bokeh.resources
    def _inline(paths):
        strings = []
        for path in paths:
            begin = "/* BEGIN %s */" % path
            middle = open(path, 'rb').read().decode("utf-8")
            end = "/* END %s */" % path
            strings.append(begin + '\n' + middle + '\n' + end)
        return strings


    # Assume we always have resources
    js_resources = resources
    css_resources = resources

    bokeh_js = ''
    if js_resources:
        bokeh_js = JS_RESOURCES.render(js_raw=js_resources.js_raw, js_files=js_resources.js_files)

    bokeh_css = ''

    _css_raw = css_resources.css_raw
    if css_raw:
        tmp = lambda: _inline(css_raw)
        _css_raw += tmp()
    if css_resources:
        bokeh_css = CSS_RESOURCES.render(css_raw=_css_raw, css_files=css_resources.css_files)
        
    # Hack to get on-the-fly double mapping
    def _update(template_variables):
        tmp = {}
        for k, v in template_variables.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

    template_variables.update(_update(template_variables))
    template_variables_full = \
        template_variables.copy() if template_variables is not None else {}
    template_variables_full.update(
        {
            'title' : title,
            'bokeh_js' : bokeh_js,
            'bokeh_css' : bokeh_css,
        }     
    )
    html = template.render(template_variables_full)
    return encode_utf8(html)
Ejemplo n.º 13
0
def output():
    ALL = request.args.get('ALL')
    if ALL == "ALL":
        input_team = ['ATL', 'BOS', 'BKN', 'CHA', 'CHI', 'CLE', 'DAL',
                      'DEN', 'DET', 'GSW', 'HOU', 'IND', 'LAC', 'LAL',
                      'MEM', 'MIA', 'MIL', 'MIN', 'NOP', 'NYK', 'OKC',
                      'ORL', 'PHI', 'PHO', 'POR', 'SAC', 'SAS', 'TOR',
                      'UTA', 'WAS']
    else:
        ATL = request.args.get('ATL')
        BOS = request.args.get('BOS')
        BKN = request.args.get('BKN')
        CHA = request.args.get('CHA')
        CHI = request.args.get('CHI')
        CLE = request.args.get('CLE')
        DAL = request.args.get('DAL')
        DET = request.args.get('DET')
        GSW = request.args.get('GSW')
        HOU = request.args.get('HOU')
        IND = request.args.get('IND')
        LAC = request.args.get('LAC')
        LAL = request.args.get('LAL')
        MEM = request.args.get('MEM')
        MIA = request.args.get('MIA')
        MIL = request.args.get('MIL')
        NOP = request.args.get('NOP')
        OKC = request.args.get('OKC')
        ORL = request.args.get('ORL')
        PHO = request.args.get('PHO')
        POR = request.args.get('POR')
        SAC = request.args.get('SAC')
        SAS = request.args.get('SAS')
        TOR = request.args.get('TOR')
        UTA = request.args.get('UTA')
        WAS = request.args.get('WAS')

        teams = [ATL, BOS, BKN, CHA, CHI, CLE, DAL, DET, GSW, HOU, IND,
                 LAC, LAL, MEM, MIA, MIL, NOP, OKC, ORL, PHO, POR, SAC,
                 SAS, TOR, UTA, WAS]
        input_team = []
        for team in teams:
            if team:
                input_team += [team]
    if len(input_team) < 1:
        input_team = ['ATL', 'BOS', 'BKN', 'CHA', 'CHI', 'CLE', 'DAL',
                      'DEN', 'DET', 'GSW', 'HOU', 'IND', 'LAC', 'LAL',
                      'MEM', 'MIA', 'MIL', 'MIN', 'NOP', 'NYK', 'OKC',
                      'ORL', 'PHI', 'PHO', 'POR', 'SAC', 'SAS', 'TOR',
                      'UTA', 'WAS']

    # Grab data off database
    sql = "SELECT * FROM results"
    df = pd.read_sql_query(sql, g.db)
    df = df.drop('index', axis = 1)
    df = df[df['team'].isin(input_team)]
    df = df.sort_values('points', ascending = False)
    df = df.reset_index().drop('index', axis = 1)
    # Round values for display purposes
    for col in ['avg_pm','pred','points']:
        df[col] = np.round(df[col], 1)

    entries = [dict(lineup = df['lineup'][row],
               team = df['team'][row],
               opponent = df['opponent'][row],
               month = df['month'][row],
               day = df['dayofmonth'][row],
               base = df['avg_pm'][row],
               pred = df['pred'][row],
               points = df['points'][row]) for row in range(df.shape[0])]


    # Get dimensions of screen with Tkinter
    root = tk.Tk()
    scr_width = root.winfo_screenwidth()
    scr_height = root.winfo_screenheight()
    wide = scr_width * 0.4
    height = scr_height * 0.45


    # MAKE PLOT DATA
    pred = np.array(df['pred'])
    y_test = np.array(df['points'])
    avg_pm = np.array(df['avg_pm'])

    # Configure resources to include BokehJS inline in the document.
    js_resources = JS_RESOURCES.render(
        js_raw=INLINE.js_raw,
        js_files=INLINE.js_files
    )

    css_resources = CSS_RESOURCES.render(
        css_raw=INLINE.css_raw,
        css_files=INLINE.css_files
    )

    source = ColumnDataSource(data = dict(x = y_test,
                                          y = pred,
                                          lineup = np.array(df['lineup']),
                                          base = np.array(df['avg_pm']),
                                          month = np.array(df['month']),
                                          day = np.array(df['dayofmonth']),
                                          team = np.array(df['team']),
                                          opponent = np.array(df['opponent'])
                                          )
                              )


    # create a new plot with the tools above, and explicit ranges
    TOOLS = "resize, pan, wheel_zoom, box_zoom, reset, hover"
    p = figure(tools = TOOLS, x_range=(-175,175), y_range=(-175, 175),
               plot_width = int(wide), plot_height = int(height))
    # Plot fill quadrant 1 and 4
    p.patch([0, 0, 5000, 5000], [0, 5000, 5000, 0],
            alpha =  0.3, color = (6, 110, 10))
    p.patch([0, 0, -5000, -5000],[0, -5000, -5000, 0],
            alpha = 0.3, color = (6, 110, 10))
    # Plot results
    p.line(np.arange(-2000,2000,100), np.arange(-2000,2000,100),
           line_width = 2, color = "grey", legend = "Perfect Prediction")
    p.circle('x', 'y', source = source, radius=3,
             color = (153, 0, 51), alpha = 0.9, legend = "New Model")

    # Plot styling
    p.text(50, 150, text = ['True Positive:'], text_font_size="10pt")
    p.text(50, 135, text = ['Favorable Matchup'], text_font_size="10pt")
    p.text(-120, -135, text = ['True Negative:'], text_font_size="10pt")
    p.text(-120, -150, text = ['Unfavorable Matchup'], text_font_size="10pt")
    p.text(80, -135, text = ['False Negative:'], text_font_size="10pt")
    p.text(80, -150, text = ['Missed Opportunity'], text_font_size="10pt")
    p.text(-150, 100, text = ['False Positive:'], text_font_size="10pt")
    p.text(-150, 85, text = ['Mistaken Prediction'], text_font_size="10pt")
    p.legend.orientation = "top_left"
    p.xaxis.axis_label = 'Actual +/- (points/48min)'
    p.yaxis.axis_label = 'Predicted +/- (points/48min)'


    hover = p.select(dict(type=HoverTool))
    hover.point_policy = "follow_mouse"
    hover.tooltips = OrderedDict([("Lineup", "@lineup"),
                                  ("Team", "@team"),
                                  ("Opponent", "@opponent"),
                                  ("(Month, Day)", "(@month, @day)"),
                                  ("Actual", "@x"),
                                  ("Prediction", "@y"),
                                  ("Base Model", "@base")])


    plot_script, plot_div = components(p)

    # convert input_team to a string for html and then passed to img function
    input_team = ','.join(input_team)
    """
    # Debugging
    output_file("tt2.html")
    f = open('tfile', 'w')
    f.write(plot_script)
    f.close()
    show(p)
    """
    html = render_template("result.html", input_team = input_team,
                           entries = entries, wide = wide, height = height,
                           plot_script = plot_script, plot_div = plot_div,
                           js_resources=js_resources,
                           css_resources=css_resources)
    return encode_utf8(html)
Ejemplo n.º 14
0
def static_html(template,
                title="bokehutils plot",
                resources=INLINE,
                css_raw=None,
                template_variables=None):
    """Render static html document.

    This is a minor modification of :py:meth:`bokeh.embed.file_html`.

    Args:
      template (Template): a Jinja2 HTML document template
      title (str): a title for the HTML document ``<title>`` tags.
      resources (Resources): a resource configuration for BokehJS assets
      css_raw (list): a list of file names for inclusion in the raw css

      template_variables (dict): variables to be used in the Jinja2
          template. In contrast to :py:meth:`bokeh.embed.file_html`,
          this is where plot objects are placed. The plot objects will
          be automagically split into script and div components. If
          used, the following variable names will be overwritten:
          title, js_resources, css_resources

    Returns:
      html : standalone HTML document with embedded plot

    """

    # From bokeh.resources
    def _inline(paths):
        strings = []
        for path in paths:
            begin = "/* BEGIN %s */" % path
            middle = open(path, 'rb').read().decode("utf-8")
            end = "/* END %s */" % path
            strings.append(begin + '\n' + middle + '\n' + end)
        return strings

    # Assume we always have resources
    js_resources = resources
    css_resources = resources

    bokeh_js = ''
    if js_resources:
        bokeh_js = JS_RESOURCES.render(js_raw=js_resources.js_raw,
                                       js_files=js_resources.js_files)

    bokeh_css = ''

    _css_raw = css_resources.css_raw
    if css_raw:
        tmp = lambda: _inline(css_raw)
        _css_raw += tmp()
    if css_resources:
        bokeh_css = CSS_RESOURCES.render(css_raw=_css_raw,
                                         css_files=css_resources.css_files)

    # Hack to get on-the-fly double mapping
    def _update(template_variables):
        tmp = {}
        for k, v in template_variables.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

    template_variables.update(_update(template_variables))
    template_variables_full = \
        template_variables.copy() if template_variables is not None else {}
    template_variables_full.update({
        'title': title,
        'bokeh_js': bokeh_js,
        'bokeh_css': bokeh_css,
    })
    html = template.render(template_variables_full)
    return encode_utf8(html)
Ejemplo n.º 15
0
def test_file_html_handles_css_only_resources():
    css_resources = CSSResources()
    template = Template("<head>{{ bokeh_css }}</head><body></body>")
    output = embed.file_html(_embed_test_plot, None, "title", template=template, css_resources=css_resources)
    rendered_css = CSS_RESOURCES.render(css_raw=css_resources.css_raw)
    assert output == "<head>%s</head><body></body>" % rendered_css
Ejemplo n.º 16
0
    <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

js_resources = JS_RESOURCES.render(js_raw=resources.js_raw,
                                   js_files=resources.js_files)

css_resources = CSS_RESOURCES.render(css_raw=resources.css_raw,
                                     css_files=resources.css_files)

script, div = components({'red': red, 'blue': blue, 'green': green})

html = template.render(js_resources=js_resources,
                       css_resources=css_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)