Beispiel #1
0
def switch_theme(value, old, new):
    if new in ['dark_minimal', 'night_sky', 'contrast']:
        for i in p.toolbar.tools:
            if type(i) == type(CrosshairTool()):
                p.toolbar.tools.remove(i)
                p.add_tools(CrosshairTool(line_color='white'))
    else:
        for i in p.toolbar.tools:
            if type(i) == type(CrosshairTool()):
                p.toolbar.tools.remove(i)
                p.add_tools(CrosshairTool(line_color='black'))
    curdoc().theme = new
    '''
    def _set_tools(self):
        wheel_zoom = WheelZoomTool()
        pan = PanTool()
        box_zoom = BoxZoomTool()
        box_select = BoxSelectTool()
        crosshair = CrosshairTool()
        tap = TapTool()
        save = SaveTool()
        reset = ResetTool()
        self.lasso_select = LassoSelectTool(
            renderers=self.circles,          # default = all available renderers
            select_every_mousemove=False,    # to enhance performance
        )

        self.lasso_select.overlay.line_alpha=0.9
        self.lasso_select.overlay.line_color="black"
        self.lasso_select.overlay.fill_alpha=0.2
        self.lasso_select.overlay.fill_color="grey"

        hover = self._get_hover_tool()
        self.tools = (
            pan, box_zoom, self.lasso_select, box_select,
            crosshair, save, reset, tap, wheel_zoom
        )
        self.plot.add_tools(*self.tools)
Beispiel #3
0
def ridgeplot(courses_obj):
    # first format 'courses_obj' into 'probly' DataFrame format
    # courses_obj: [{'course_name': 'Calculus...', ...}, ...]
    grades = [[100*y[2]/y[3] for y in x['assignments']] for x in courses_obj]
    # turn this list of lists into a complete NumPy array
    length = len(sorted(grades, key=len, reverse=True)[0])
    grades = np.array([xi+[None]*(length-len(xi)) for xi in grades], dtype='float')
    columns = [x['course_name'] for x in courses_obj]
    grades = grades.transpose()
    probly = pd.DataFrame(grades, columns=columns)


    cats = list(reversed(probly.keys()))


    palette = [cc.rainbow[i*15] for i in range(17)]

    x = np.linspace(-20,110, 500)

    source = ColumnDataSource(data=dict(x=x))

    p = figure(y_range=cats, plot_width=900, plot_height = 300, x_range=(-5, 120))#, toolbar_location=None)

    for i, cat in enumerate(reversed(cats)):
        adjusted = probly[cat].replace([np.inf, -np.inf], np.nan).dropna(how="all")
        if adjusted.size == 1 or pd.unique(adjusted).size == 1: # this means we can't compute
            continue
        pdf = gaussian_kde(adjusted)
        #p = figure(plot_width=400, plot_height=400)
        #p.line(x, pdf(x))
        y = ridge(cat, pdf(x), scale=2)
        #p.line(x, y, color='black')
        #show(p)
        source.add(y, cat)
        p.patch('x', cat, color=palette[i], alpha=0.6, line_color="black", source=source)

    p.outline_line_color = None
    p.background_fill_color = "#efefef"

    p.tools = [PanTool(), CrosshairTool(), HoverTool(), SaveTool(), BoxZoomTool(), WheelZoomTool(), ResetTool()]

    ticks = list(np.array([np.array([0,3,7])+i*10 for i in range(10)]).flatten()) + [100]
    p.xaxis.ticker = FixedTicker(ticks=ticks)
    p.xaxis.formatter = PrintfTickFormatter(format="%d")
    p.xaxis.axis_label = "Your Grade Distribution"

    p.yaxis.axis_label = "Your Courses"

    p.ygrid.grid_line_color = None
    p.xgrid.grid_line_color = "Grey"
    p.xgrid.ticker = p.xaxis[0].ticker

    p.axis.minor_tick_line_color = None
    p.axis.major_tick_line_color = None
    p.axis.axis_line_color = None

    p.y_range.range_padding = 0.12

    return p
Beispiel #4
0
    def _set_tools(self):
        wheel_zoom = WheelZoomTool()
        pan = PanTool()
        box_zoom = BoxZoomTool()
        box_select = BoxSelectTool()
        crosshair = CrosshairTool()
        tap = TapTool()
        save = SaveTool()

        lasso_select = LassoSelectTool(
            select_every_mousemove=False,  # enhance performance
        )

        code = """
            var projections = require("core/util/projections");
            var x = special_vars.x
            var y = special_vars.y
            var coords = projections.wgs84_mercator.inverse([x, y])
            return coords[%d].toFixed(2)
        """

        tooltips = '''
            <style>
                .bk-tooltip>div:not(:nth-child(-n+5)) {{
                    display:none;
                }}

                .bk-tooltip>div {{
                    background-color: #dff0d8;
                    padding: 5px;
                }}
            </style>

            <b>STATION: </b> @{STNNBR} <br />
            <b>LON: </b> @X_WMTS{custom} <br />
            <b>LAT: </b> @Y_WMTS{custom} <br />
        '''

        hover = HoverTool(toggleable=True,
                          mode='mouse',
                          tooltips=tooltips,
                          renderers=[self.env.wmts_map_scatter],
                          formatters={
                              'X_WMTS': CustomJSHover(code=code % 0),
                              'Y_WMTS': CustomJSHover(code=code % 1),
                          })

        tools = (pan, box_zoom, lasso_select, hover, crosshair, tap,
                 wheel_zoom)
        self.env.wmts_map.add_tools(*tools)

        # set defaults
        self.env.wmts_map.toolbar.active_drag = pan
        self.env.wmts_map.toolbar.active_inspect = [crosshair, hover]
        self.env.wmts_map.toolbar.active_scroll = wheel_zoom
        self.env.wmts_map.toolbar.active_tap = None
Beispiel #5
0
def workloadplot(courses_obj, is_ridge=True):
    # we just need to first get a list of lists of dicts
    # each sublist is a separate course
    # within each sublist you're gonna have a bunch of datetimes
    # for each datetime, you want to repeat it depending on the category
    datetimes = [[[xi[5]]*repeat(xi[1].lower()) for xi in x['assignments']] for x in courses_obj]
    datetimes = [list(itertools.chain.from_iterable(x)) for x in datetimes]
    datetimes = pd.DataFrame(datetimes, index=[x['course_name'] for x in courses_obj]).transpose()
    datetimes = datetimes.apply(pd.to_datetime) # convert to datetime
    datetimes = pd.DataFrame([datetimes[x].dt.week for x in datetimes])

    counts = pd.DataFrame([datetimes[x].value_counts() for x in datetimes]).transpose()
    #counts = 
    # use something like a[0].combine(pd.Series([0 for x in range(50)]), lambda x1, x2: x1 if type(x1)==type(pd.to_datetime('8/8/2018')) else pd.to_datetime('1/1/2018' ))

    assert(datetimes.shape[1] == len(courses_obj))

    # for each course, need a list where each element is the number of assignments
    # due that week (by index)
    first_date = time.mktime(datetimes.apply(min).min().timetuple())
    last_date = time.mktime(datetimes.apply(max).max().timetuple())

    x = np.arange(first_date, last_date+DIVISION, TWO_WEEKS)
    x_ = np.linspace(0,101,2)

    source = ColumnDataSource(data=dict(x_=x_))

    cats = list(datetimes.keys())



    p.outline_line_color = None
    p.background_fill_color = "#efefef"

    p.tools = [PanTool(), CrosshairTool(), HoverTool(), SaveTool(), BoxZoomTool(), WheelZoomTool(), ResetTool()]
    p.xaxis.axis_label = "Your Workload Over Time"

    p.yaxis.axis_label = "Your Courses"

    p.ygrid.grid_line_color = None
    p.xgrid.grid_line_color = "Grey"

    #ticks = ['Beginning', 'End']
    #p.xaxis.ticker = FixedTicker(ticks=ticks)

    p.xgrid.ticker = p.xaxis[0].ticker

    p.axis.minor_tick_line_color = None
    p.axis.major_tick_line_color = None
    p.axis.axis_line_color = None

    p.y_range.range_padding = 0.8
    #p.y_range.group_padding = 3

    return p
Beispiel #6
0
def gradesplot(course_obj):
    assignment_array = course_obj['assignments']
    assignment_array.reverse()
    all_categories = get_categories(assignment_array)
    # get a list of lists
    # so each list within has all of the assignments belonging to that category/group
    data = []
    for category in all_categories:
        category_data = []
        for assignment in assignment_array:
            if assignment[1] == category:
                category_data.append(assignment)
        data.append(category_data)
    p = figure(x_axis_type="datetime", plot_width=1000, plot_height=300, y_range=(50,120))
    p.title.text = "Grades over time"

    colors = Spectral[len(all_categories)] if len(all_categories) >= 3 else Spectral[3][:len(all_categories)]
    
    assert(len(data) == len(all_categories) == len(colors))

    for datum, category, color in zip(data, all_categories, colors):
        df = pd.DataFrame(datum)
        df = df.rename({0:'name',1:'grouping', 2:'score', 3:'possible',4:'assigned',5:'due'}, axis='columns')

        df['due'] = pd.to_datetime(df['due'])
        source = ColumnDataSource(data=dict(
                x=df['due'],
                y=100*df['score']/df['possible'],
                category=df['grouping'],
                name=df['name']
            ))
        p.line('x', 'y', line_width=2, color=color, source=source, legend=category, tags=[category])
        p.circle('x', 'y', color=color, legend=category, source=source, tags=[category])

    p.ygrid.grid_line_alpha = 0.75
    p.ygrid.grid_line_color = "Black"
    p.legend.location = "bottom_left"
    p.legend.click_policy="hide"
    p.legend.label_text_font_size = '8pt'
    p.legend.spacing = -6

    p.toolbar.logo = None
    p.tools = [PanTool(), CrosshairTool(), HoverTool(), SaveTool(), BoxZoomTool(), WheelZoomTool(), ResetTool()]

    hover = p.select(dict(type=HoverTool))
    hover.tooltips = """
        <style>
            .bk-tooltip>div:not(:first-child) {display:none;}
        </style>
        <span style="font-size: 12px;">@name</span>
        <span style="font-size: 10px;"> (@category) <br>
        Grade: @y%</span>
    """

    return p
Beispiel #7
0
    def _set_tools(self):
        wheel_zoom = WheelZoomTool()
        pan = PanTool()
        box_zoom = BoxZoomTool()
        box_select = BoxSelectTool()
        crosshair = CrosshairTool()
        tap = TapTool()
        save = SaveTool()
        reset = ResetTool()     # TODO: add only to one plot, maybe with n_plot

        self.lasso_select = LassoSelectTool(
            renderers=self.circles,                  # default all available renderers
            select_every_mousemove=False,            # enhance performance
        )

        tooltips = '''
            <style>
                .bk-tooltip>div:not(:nth-child(-n+5)) {{
                    display:none;
                }}

                /* .bk-tooltip-custom + .bk-tooltip-custom {{
                    display: none;  sometimes everything is hidden with this
                }} */

                .bk-tooltip>div {{
                    background-color: #dff0d8;
                    padding: 5px;
                }}
            </style>

            <b>INDEX: </b> @INDEX <br>
            <b>{x}: </b> @{x} <br>
            <b>{x}_FLAG_W: </b> @{x}_FLAG_W <br>
            <b>{y}: </b> @{y} <br>
            <b>{y}_FLAG_W: </b> @{y}_FLAG_W <br>
        '''.format(x=self.x, y=self.y)

        hover = HoverTool(                  # TODO: try to make this toggleable
            renderers=self.circles,
            toggleable=True,
            mode='mouse',
            tooltips=tooltips,
        )

        tools = (
            pan, box_zoom, self.lasso_select, box_select,
            crosshair, save, reset, tap, wheel_zoom
        )
        self.plot.add_tools(*tools)
Beispiel #8
0
def plot_layoult(title, grid1, save_figs=False, show_figs=True, grid2=None):

    if title is None:
        title='NOME DA FIGURA NAO FORNECIDO'
        
    xwheel_zoom = WheelZoomTool(dimensions="width")
    pan_tool = PanTool()
    hover = HoverTool()
    crosshair = CrosshairTool()

    toolbar = Toolbar(
        tools=[xwheel_zoom, pan_tool, hover, crosshair],
        active_inspect=[crosshair],
        # active_drag =                         # here you can assign the defaults
        # active_scroll =                       # wheel_zoom sometimes is not working if it is set here
        # active_tap
    )

    toolbar_box = ToolbarBox(toolbar=toolbar, toolbar_location="above")

    if grid2 is None:
        layout_2 = layout(children=[[
#                toolbar_box, 
                grid1
                ]], 
#                          sizing_mode="stretch_both",
#                          plot_width=400, plot_height=800,
                          )
    else:
        layout_2 = layout(children=[[
#                toolbar_box, 
                [[grid1], 
                [grid2]]
                ]],
#            sizing_mode="stretch_both",
#            plot_width=3000, plot_height=1000,
            )

    
    
    
    if save_figs is True:
        output_file(title + ".html")
        if show_figs is True:
            show(layout_2)
        else:
            save(layout_2)
    else:
        show(layout_2)
Beispiel #9
0
    def plot_perf(
        data: pd.DataFrame,
        mod: DirectReinforcementModel,
        tail: int = config["chartTail"],
        modelName: str = f"{config['modelName']} v{config['modelVersion']}",
    ) -> str:  # returns HTML str
        data = data.tail(tail)
        data = DataVisualiser.add_positions_to_data(mod, data)
        data = DataVisualiser.add_performance_to_data(mod, data)
        p1 = figure(
            x_axis_type="datetime",
            title="Cumulative Returns by Strategy",
            plot_width=800,
            plot_height=500,
        )
        p1.grid.grid_line_alpha = 0.3
        p1.xaxis.axis_label = "Date"
        p1.yaxis.axis_label = "Cumulative Returns"

        p1.toolbar.logo = None
        p1.tools = [
            PanTool(),
            # SaveTool(),
            WheelZoomTool(),
            ResetTool(),
            CrosshairTool(),
        ]

        p1.line(  # pylint: disable=too-many-function-args
            datet(data.closeTimeIso),
            data.modelReturnsCumSum,
            color="#33A02C",
            legend_label=modelName,
        )
        p1.line(  # pylint: disable=too-many-function-args
            datet(data.closeTimeIso),
            data.buyHoldReturns,
            color="#FB9A99",
            legend_label="HODL",
        )

        return file_html(p1, CDN), data
Beispiel #10
0
    def __init__(self, dataset, parameters):

        self.dataset = dataset

        # Set up the controls
        self.specials = Selector(
            name="Specials",
            kind="specials",
            css_classes=["specials"],
            entries={
                "Color-magnitude diagram": "cmd",
                "Period vs. radius": "pr",
                "Period vs. transit duration": "pdt",
            },
            default="Color-magnitude diagram",
        )
        self.data = Selector(
            name="Datasets",
            kind="datasets",
            css_classes=["data"],
            entries={"TOI Catalog": "toi", "Confirmed Planets": "confirmed"},
            default="Confirmed Planets",
        )
        self.xaxis = Selector(
            name="Build-Your-Own",
            kind="parameters",
            css_classes=["build-your-own"],
            entries=parameters,
            default="ra",
            title="X Axis",
        )
        self.yaxis = Selector(
            kind="parameters",
            css_classes=["build-your-own"],
            entries=parameters,
            default="dec",
            title="Y Axis",
        )
        self.size = Selector(
            name="Sides",
            kind="parameters",
            css_classes=["sides"],
            entries=parameters,
            default="dist",
            title="Marker Size",
            none_allowed=True,
        )
        self.color = Selector(
            kind="parameters",
            css_classes=["sides"],
            entries=parameters,
            default="dist",
            title="Marker Color",
            none_allowed=True,
        )

        # Set up the plot
        self.source = ColumnDataSource(
            data=dict(x=[], y=[], size=[], color=[])
        )
        self.plot = figure(
            plot_height=600,
            plot_width=700,
            title="",
            tooltips=[("TIC ID", "@ticid")],
            sizing_mode="scale_both",
        )
        self.plot.circle(
            x="x",
            y="y",
            source=self.source,
            size="size",
            color=linear_cmap(
                field_name="color", palette=Viridis256, low=0, high=1
            ),
            line_color=None,
        )
        self.plot.add_tools(
            BoxSelectTool(),
            BoxZoomTool(),
            LassoSelectTool(),
            PanTool(),
            PolySelectTool(),
            TapTool(),
            WheelZoomTool(),
            WheelPanTool(),
            ZoomInTool(),
            ZoomOutTool(),
            HoverTool(),
            CrosshairTool(),
            ResetTool(),
        )

        # Register the callback
        for control in [
            self.specials,
            self.data,
            self.xaxis,
            self.yaxis,
            self.size,
            self.color,
        ]:
            control.widget.on_change("value", self.callback)

        # Load and display the data
        self.callback(None, None, None)
Beispiel #11
0
from bokeh.models import Span, Label

from bokeh.io import export_svgs, export_png

# from bokeh.palettes import Spectral6
from bokeh.transform import linear_cmap
import bokeh.palettes as bp

import numpy as np
from copy import deepcopy

xwheel_zoom = WheelZoomTool(dimensions="width")
pan_tool = PanTool()
hover = HoverTool()
crosshair = CrosshairTool()

#    tools = (xwheel_zoom, pan_tool, hover, crosshair)

toolbar = Toolbar(
    tools=[xwheel_zoom, pan_tool, hover, crosshair],
    active_inspect=[crosshair],
    # active_drag =                         # here you can assign the defaults
    # active_scroll =                       # wheel_zoom sometimes is not working if it is set here
    # active_tap
)

toolbar_box = ToolbarBox(toolbar=toolbar, toolbar_location="above")


Beispiel #12
0
step = None
rate = orig_rate = None
au = orig_au = lx = orig_lx = p1 = orig_p1 = p2 = orig_p2 = []
lp_p1 = orig_lp_p1 = lp_p2 = orig_lp_p2 = timepts = []
raw_p1 = raw_p2 = raw_lp_p1 = raw_lp_p2 = raw_lp_decim_p1 = raw_lp_decim_p2 = []
p1_cal = p2_cal = None
width = 800
height = 200
cutoff = 50
order = 3
source = ColumnDataSource(data=dict(
    x=timepts, au=au, p1=p1, raw_lp_decim_p1=p1, p2=p2, raw_lp_decim_p2=p2))

# Create the tools for the toolbar
ts_cnt = np.arange(3)
cross = [CrosshairTool() for n in ts_cnt]
hover = [
    HoverTool(tooltips=[('time', '$x'), ('sample', '@x')]),
    HoverTool(tooltips=[('time', '$x'), ('val',
                                         '@p1'), ('raw', '@raw_lp_decim_p1')]),
    HoverTool(tooltips=[('time', '$x'), ('val',
                                         '@p2'), ('raw', '@raw_lp_decim_p2')])
]
xzoom = [BoxZoomTool(dimensions=['width']) for n in ts_cnt]
xwzoom = [WheelZoomTool(dimensions=['width']) for n in ts_cnt]
xsel = [BoxSelectTool(dimensions=['width']) for n in ts_cnt]
xtsel = [TapTool() for n in ts_cnt]
xpan = [PanTool(dimensions=['width']) for n in ts_cnt]
save = [SaveTool() for n in ts_cnt]
reset = [ResetTool() for n in ts_cnt]
tools = [[
Beispiel #13
0
with open('sensor_locations.pickle', 'rb') as handle:
    sensorLocDict = pickle.load(handle);

#saveEditDistanceForAllMonths(reserve_data);

hover_heatmap = HoverTool(tooltips=[('Time', '@hh'),('Sensor','@sensors'),('Freq','@value')]);
heatmap_hh = pd.unique(reserve_data['Timestamp'].dt.hour);
heatmap_sensors = pd.unique(reserve_data['gate-name']);
heatmapNormalData, heatmapSpecialData = getHeatMapData(heatmap_hh, heatmap_sensors, reserve_data);
heatMapData = ColumnDataSource(data=heatmapNormalData.data);
exp_heatmap = figure(title="Activity inside the reserve",x_range=[str(h) for h in heatmap_hh],y_range=list(heatmap_sensors), plot_height=550, plot_width=750);
exp_heatmap.title.text_font_size='13pt';
exp_heatmap.rect(x='hh', y='sensors', color='colors', width = 0.9, height = 0.9,source=heatMapData);
exp_heatmap.add_tools(hover_heatmap);
exp_heatmap.add_tools(CrosshairTool());
exp_heatmap.yaxis.axis_label="Sensor Locations";
exp_heatmap.xaxis.axis_label="Time (24h)";
exp_heatmap.min_border_top = 50;

heatmap_button = Button(label="Show Ranger Traffic", width=150, button_type='success');
heatmap_button.on_click(heatmap_button_callback);
outlier_button = Button(label="Find the Outliers", width=150, button_type='warning');
outlier_button.on_click(outlier_button_callback);

heatmap_pretext = PreText(text="""
The Heat Map on the left shows the sensor readings by sensor location and
time for the entire dataset. The ‘Show Ranger Traffic/Show Normal Traffic’
button shifts the Heat Map between ranger and traffic readings.
The ‘Outlier’ button shows interesting outliers in the dataset. We define
an Outlier as any normal traffic reading in restricted zones (i.e zones that
Beispiel #14
0
    title=
    "Validation loss during training for an array of models of different sizes",
    tools="pan,reset,save,wheel_zoom,tap",
    active_scroll="wheel_zoom",
    x_range=[
        min(all_points[:, 0]) * day_ratio,
        max(all_points[:, 0]) * day_ratio
    ],
    y_range=[min(all_points[:, 1]),
             max(all_points[:, 1])],
    x_axis_type="log",
    y_axis_type="log",
    x_axis_label="Floating-point operations (excluding embeddings & softmax)",
    y_axis_label="Validation loss on Wikitext-103",
    output_backend="webgl")
loss_plot.add_tools(CrosshairTool(dimensions="width", line_alpha=0.2))
loss_plot.add_layout(color_bar, "left")
# for i, run in indexed_runs.items():
#     source = ColumnDataSource(data=dict(x=run[:, 0] * day_ratio, y=run[:, 1]))
#     loss_plot.line('x', 'y', source=source, line_width=1, line_alpha=0.6, color=color_list[i])
#     loss_plot.scatter('x', 'y', source=source, line_width=1, line_alpha=0.6, color=color_list[i])

source = ColumnDataSource(data=dict(
    xs=[run[:, 0] * day_ratio
        for run in indexed_runs],  # x coords for each line (list of lists)
    ys=[run[:, 1]
        for run in indexed_runs],  # y coords for each line (list of lists)
    params=params_per_run  # data to use for colormapping
))
loss_plot.multi_line('xs',
                     'ys',
    def update_plot(self):

        today = Timestamp.today().strftime('%Y-%m-%d')
        today_date = to_datetime(today)

        df = self.counts_data
        weights = self.similarities_data.xs(self.school, level='school_name', axis=1)
        df_all = df[df['school_name'].eq(self.school)]
        present_academic_year = df['academic_year'].unique()[0]

        tooltips = '''
        <div style="font-size: 12px;">
        <span style="font-weight: bold;">@school_name</span> (@school_type, @school_age years old)<br>
        Grade @grade enrollment, as of @reference_date_string<br>
        <br>
        <span style="font-weight: bold;">Attrition</span>: @exit_count_present_cumm (@exit_percent_present_cumm{'0.0%'} change from October 1)<br>
        <span style="font-weight: bold;">Backfill</span>: @enter_count_present_cumm (@enter_percent_present_cumm{'0.0%'} change from October 1)<br>
        <span style="font-weight: bold;">Current total enrollment</span>: @total_enrollment
        </div>
        '''

        ticker_ref = DataFrame({'month': date_range('2014-10-01', '2015-06-01', freq='MS')})
        ticker_ref['marker'] = ticker_ref['month']
        ticker_ref['month'] = ticker_ref['month'].apply(lambda x: x.strftime('%B'))
        ticker_ref = ticker_ref.set_index('marker')['month'].to_dict()

        x_range1d = Range1d(-0.05, 290.0)
        y_index = max(
            -df_all['exit_percent_present_cumm'].min(),
            df_all['enter_percent_present_cumm'].max(),
            -df_all['exit_percent_past_cumm'].min(),
            df_all['enter_percent_past_cumm'].max()
        )
        y_range1d = Range1d(-y_index - 0.005, y_index + 0.005)
        plots = []
        focus_cols = ['enter_percent_present_cumm', 'exit_percent_present_cumm']
        unique_grades = sorted(df_all['grade'].unique().astype('int'))
        for grade in unique_grades:
            grade_weight = weights[grade]
            benchmark_df = DataFrame(columns=focus_cols)
            df_copy = df[df['academic_year'].eq(present_academic_year)].copy().set_index(['school_name', 'grade'])

            for rid, label in sorted(ticker_ref.items(), reverse=True):
                df_copy = df_copy[df_copy['reference_date'].le(rid)]
                df_ave = df_copy.groupby(level=['school_name', 'grade'])[focus_cols].tail(1).\
                    mul(grade_weight, axis=0).sum() / grade_weight.sum()
                df_ave.name = label
                benchmark_df = benchmark_df.append(df_ave)
            benchmark_df = benchmark_df.reset_index()
            benchmark_df['reference_date'] = benchmark_df['index'].map({y: x for x, y in ticker_ref.items()})
            benchmark_df['reference_id'] = benchmark_df['reference_date'].apply(lambda x: x.toordinal()) - \
                df_all['reference_date'].min().toordinal()

            source_df = df_all[df_all['grade'].eq(grade)]
            source_df_rev = source_df.sort_values('reference_id', ascending=False)
            source_df_trunc = source_df.loc[source_df['reference_date'].le(today_date), :]
            source = ColumnDataSource(source_df)
            source_trunc = ColumnDataSource(source_df_trunc)
            patch_source = ColumnDataSource(dict(
                x_past=source_df['reference_id'].tolist() + source_df_rev['reference_id'].tolist(),
                y_past=source_df['enter_percent_past_cumm'].tolist() + source_df_rev['exit_percent_past_cumm'].tolist()
            ))

            plot1 = Plot(
                x_range=x_range1d,
                y_range=y_range1d,
                min_border_bottom=5,
                min_border_top=10,
                min_border_right=10,
                plot_width=700,
                plot_height=150,
                title=None,
                title_text_font_size='0pt',
                title_text_color='grey',
                outline_line_alpha=0.0)

            plot1.add_layout(
                LinearAxis(
                    axis_label='Grade ' + str(grade), axis_label_text_font_size='9pt', minor_tick_line_alpha=0.0,
                    axis_label_text_color='grey',
                    axis_line_alpha=0.1, major_tick_line_alpha=0.1, major_label_text_color='grey',
                    major_label_text_font_size='7pt', formatter=NumeralTickFormatter(format='0%')
                ), 'left')

            patch = Patch(x='x_past', y='y_past', fill_color='#AFAFAD', fill_alpha=0.25, line_alpha=0.0)
            plot1.add_glyph(patch_source, patch)

            line1 = Line(
                x='reference_id', y='enter_percent_present_cumm', line_width=2, line_color='#f7910b', line_alpha=1.0)
            plot1.add_glyph(source_trunc, line1)

            line2 = Line(
                x='reference_id', y='exit_percent_present_cumm', line_width=2, line_color='#f7910b', line_alpha=1.0)
            plot1.add_glyph(source_trunc, line2)

            line_h = Line(x='reference_id', y=0, line_width=1, line_color='black', line_alpha=0.1)
            line_renderer = GlyphRenderer(data_source=source, glyph=line_h, name='line')
            plot1.add_glyph(source, line_h)

            for ind, series in benchmark_df.iterrows():
                x = series['reference_id']
                y_enter = series['enter_percent_present_cumm']
                y_exit = series['exit_percent_present_cumm']
                label = series['index']

                line = Segment(x0=x, x1=x, y0=-y_index, y1=y_index, line_width=1, line_color='#165788', line_alpha=0.1)
                plot1.add_glyph(line)

                linec1 = Segment(
                    x0=x - 3, x1=x + 3, y0=y_enter, y1=y_enter, line_width=1, line_color='#ed2939', line_alpha=1.0)
                plot1.add_glyph(linec1)

                linec2 = Segment(
                    x0=x - 3, x1=x + 3, y0=y_exit, y1=y_exit, line_width=1, line_color='#ed2939', line_alpha=1.0)
                plot1.add_glyph(linec2)

                text = Text(x=x+3, y=-y_index, text=[label], text_font_size='8pt', text_color='grey', text_alpha=0.5)
                plot1.add_glyph(text)

            hover_tool = HoverTool(
                plot=plot1, renderers=[line_renderer], tooltips=tooltips, always_active=False, mode='vline',
                point_policy='follow_mouse', line_policy='prev')
            crosshair_tool = CrosshairTool(plot=plot1, dimensions=['height'])
            zoom_tool = BoxZoomTool(plot=plot1, dimensions=['width'])
            reset_tool = ResetTool(plot=plot1)
            save_tool = PreviewSaveTool(plot=plot1)
            pan_tool = PanTool(plot=plot1, dimensions=['width'])
            help_tool = HelpTool(plot=plot1, help_tooltip='App help page', redirect='http://data.successacademies.org/blog/')
            plot1.tools.extend([hover_tool, zoom_tool, pan_tool, reset_tool, save_tool, help_tool, crosshair_tool])
            plot1.renderers.extend([line_renderer])
            plots.append([plot1])

        self.plot.children = plots
Beispiel #16
0
def draw_maingraph(df, offset, title):
    """ Draws Candlesticks and Bollinger's Bands
      returns plot_script, plot_div """
    #    df = d15.iloc[-50:]
    inc = df.close > df.open
    dec = df.open > df.close
    w = calc_elem_width(df.index.min(), df.index.max(), len(df))
    # fill NaN:
    df.fillna(df.mean())
    """
    TOOLS = "pan,wheel_zoom,box_zoom,reset,save"
    TOOLTIPS = [
        ('index', "$index"),
        ('date', '@index'),
        ("open", "@open"),
        ("close", "@close"),
        ("volume", "@vol"),
        ('squared', '@squared')
    ] """

    p = figure(x_axis_type="datetime",
               plot_width=800,
               plot_height=500,
               y_range=(df['BBLow'].min() * 0.99, df['BBUp'].max() * 1.01),
               title=title)  #, tools=TOOLS, tooltips=TOOLTIPS )
    p.add_tools(CrosshairTool())
    # ohcl
    p.segment(df.index, df.high, df.index, df.low, color="black")
    p.vbar(df.index[inc],
           w,
           df.open[inc],
           df.close[inc],
           fill_color="green",
           line_color="black")
    p.vbar(df.index[dec],
           w,
           df.open[dec],
           df.close[dec],
           fill_color="red",
           line_color="black")
    # bollinger's band
    source = ColumnDataSource(df)
    p.line(df.index, df['MA'], line_dash='dotted', legend="MA")
    band = Band(base='index',
                lower='BBLow',
                upper='BBUp',
                source=source,
                level='underlay',
                line_width=1,
                line_color='mediumslateblue',
                fill_color='mediumslateblue',
                fill_alpha=0.05)
    p.add_layout(band)
    # volume
    p.extra_y_ranges = {"vol_range": Range1d(start=0, end=df['vol'].max() * 4)}
    p.vbar('index',
           top='vol',
           width=w,
           source=source,
           bottom=0,
           color="firebrick",
           y_range_name="vol_range")
    p.add_layout(LinearAxis(y_range_name="vol_range"), 'right')

    return components(p)