Beispiel #1
0
def create_simple_layout(obj):
    # TODO: Seems that DateRangeSlider is broken on latest release. It'd be
    #       nice to add it when issue is fixed
    # start = datetime.date(2010, 1, 1)#'2010-01-01'
    # end = datetime.date(2015, 1, 1)#'2015-01-01'
    # obj.dr = DateRangeSlider(
    #     title="Period:", name="period", value=(start, end),
    #     bounds=(start, end), range=(dict(days=1), None)
    # )
    # Get the widget for all available plugins and add them

    interval_plugins = {pl.name: getattr(obj, pl.name)
                        for pl in obj._interval_plugins}
    names = dict(
        js_list_of_sources=str({k: k for k in interval_plugins.keys()}).replace("'", "")
    )
    code = callbacks.window_selector % names
    objs = dict(interval_plugins)
    callback = Callback(args=objs, code=code)
    obj.window_selector.callback = callback
    callback.args['interval_selector'] = obj.window_selector

    # configure button to open pump and dump detection (Poulson Algorithm)
    code = callbacks.btn_detect_pumps % names
    callback = Callback(args=objs, code=code)
    obj.btn_detect_pumps.callback = callback

    main_view = plotting.hplot(
        plotting.vplot(
            obj.ts_filters_plot,
            obj.main_plot,
            # obj.cp_plot,
            # obj.trends_plot
        ),
    )

    # add spams table to spams tab
    obj.spam_tab.child = plotting.hplot(obj.spam_table)

    # create
    obj.vpeaks = plotting.vplot(obj.PEAKS)
    obj.children = [plotting.vplot(
        main_view,
    )]
Beispiel #2
0
def create_evts_widget(objs, evts_source, hevts_source, **kws):
    javascript_list_of_sources = str(list(objs.keys())).replace("'", "")
    slen = len(objs)

    code = """
        var new_selection = [];
        for (var i = 0; i < spam_slider.get('value'); i++) {
            new_selection.push(i);
        }
        var new_selection_object = {
            '0d': {'flag': false, 'indices': []},
            '1d': {'indices': new_selection},
            '2d': {'indices': []}
        };

        evts_source.attributes.selected = new_selection_object;
        evts_source.trigger('change');

        if (spam_slider.get('value') == 0) {
            hevts_source.get('data').top = hevts_source.get('data').bottom;
        } else {
            var sources = %s;

            ss = sources[spam_slider.get('value')];
            hevts_source.get('data').top = ss.get('data').real_top;

        }
        hevts_source.trigger('change');

    """ % javascript_list_of_sources

    objs['evts_source'] = evts_source
    objs['hevts_source'] = hevts_source

    callback = Callback(args=objs, code=code)

    slider = Slider(
        value=0, start=0, end=slen, step=1, callback=callback,
        **kws
    )
    callback.args["spam_slider"] = slider
    return slider
Beispiel #3
0
def create_layout(obj):
    # Get the widget for all available plugins and add them

    interval_plugins = {pl.name: getattr(obj, pl.name)
                        for pl in obj._interval_plugins}
    names = dict(
        js_list_of_sources=str({k: k for k in interval_plugins.keys()}).replace("'", "")
    )
    code = callbacks.window_selector % names
    objs = dict(interval_plugins)
    callback = Callback(args=objs, code=code)
    obj.window_selector.callback = callback
    callback.args['interval_selector'] = obj.window_selector


    # configure button to open pump and dump detection (Poulson Algorithm)
    code = callbacks.btn_detect_pumps % names
    callback = Callback(args=objs, code=code)
    obj.btn_detect_pumps.callback = callback

    # add all elements of the main dashboard
    main_view = plotting.hplot(
        plotting.vplot(
            obj.ts_filters_plot, obj.main_plot,
        ),
    )

    # add spams table to spams tab
    obj.spam_tab.child = plotting.hplot(obj.spam_table)

    # create
    obj.vpeaks = plotting.vplot(obj.PEAKS)
    # vsteinberg = plotting.vplot(obj.TICKS_IN_ROW)
    obj.children = [plotting.vplot(
        # obj.symbol,
        # obj.tabs,
        main_view,
        # vpeaks, # add peaks plugin dialog view
        # vsteinberg,
        # obj.dialog_loading,
    )]
Beispiel #4
0
    def create_objects(cls, securities):

        ranks = utils.get_pumps_rank()
        quotient_metrics = utils.get_quotient_metrics()
        ranks['quotient'] = quotient_metrics['quotient']

        foo = lambda x: utils.spam_counts.get(x, 0)
        ranks['spams'] = map(foo, ranks['symbol'])
        ranks = ranks.sort('quotient', ascending=False)

        cls._pre_filtered_ranks = {
            'All': {k: ranks[k]
                    for k in ranks.columns},
            'Stocks with Spam':
            dict(ranks[ranks['symbol'].isin(plugins.spam_counts.keys())].sort(
                'quotient', ascending=False)),
            'Stocks without Spam':
            dict(ranks[~ranks['symbol'].isin(plugins.spam_counts.keys())].sort(
                'quotient', ascending=False)),
        }

        source_stocks_rank = ColumnDataSource(
            cls._pre_filtered_ranks['Stocks with Spam'])
        table_stocks_rank = DataTable(source=source_stocks_rank,
                                      width=785,
                                      height=400,
                                      selectable=True,
                                      editable=True,
                                      columns=[
                                          TableColumn(field='symbol',
                                                      title='symbol',
                                                      editor=StringEditor()),
                                          TableColumn(field='quotient',
                                                      title='quotient',
                                                      editor=StringEditor()),
                                          TableColumn(field='rank',
                                                      title='rank',
                                                      editor=StringEditor()),
                                          TableColumn(field='spams',
                                                      title='spams',
                                                      editor=StringEditor()),
                                      ])

        callback = Callback(args={
            'tr': table_stocks_rank,
            'sr': source_stocks_rank
        },
                            code=callbacks.source_stocks_rank)
        source_stocks_rank.callback = callback
        return locals()
Beispiel #5
0
def create_selection_plot(main_plot, theme):

    static_source = ColumnDataSource(data)
    selection_plot = figure(height=100,
                            tools="box_select",
                            x_axis_location="above",
                            x_axis_type="datetime",
                            toolbar_location=None,
                            outline_line_color=None,
                            name="small_plot")
    selection_source = ColumnDataSource()
    for k in ['end', 'values', 'start', 'bottom']:
        selection_source.add([], k)

    if theme == 'default':
        selection_color = '#c6dbef'
    elif theme == 'dark':
        selection_color = "#FFAD5C"

    selection_plot.quad(top='values',
                        bottom='bottom',
                        left='start',
                        right='end',
                        source=selection_source,
                        color=selection_color,
                        fill_alpha=0.5)

    selection_plot.line('Date', 'Price', color='#A6CEE3', source=static_source)
    selection_plot.circle('Date',
                          'Price',
                          color='#A6CEE3',
                          source=static_source,
                          size=1)

    style_selection_plot(selection_plot, theme)

    select_tool = selection_plot.select(dict(type=BoxSelectTool))
    select_tool.dimensions = ['width']

    code = """
        if (window.xrange_base_start == undefined){
            window.xrange_base_start = main_plot.get('x_range').get('start');
        }
        if (window.xrange_base_end == undefined){
            window.xrange_base_end = main_plot.get('x_range').get('end');
        }

        data = source.get('data');
        sel = source.get('selected')['1d']['indices'];
        var mi = 1000000000;
        var ma = -100000;
        if (sel.length == 0){
           var url = "http://127.0.0.1:5000/alldata";
           source_data = selection_source.get('data');
           source_data.bottom = []
           source_data.values = [];
           source_data.start = [];
           source_data.end = [];

            // reset main plot ranges
            main_range.set('start', window.xrange_base_start);
            main_range.set('end', window.xrange_base_end);
        }else{
           for (i=0; i<sel.length; i++){
            if (mi>sel[i]){
                mi = sel[i];
            }
            if (ma<sel[i]){
                ma = sel[i];
            }
           }
           var url = "http://127.0.0.1:5000/subsample/"+data.Date[mi]+"/"+data.Date[ma];
           source_data = selection_source.get('data');
           source_data.bottom = [0]
           source_data.values = [700];
           source_data.start = [data.Date[mi]];
           source_data.end = [data.Date[ma]];

           main_range = main_plot.get('x_range');
           main_range.set('start', data.Date[mi]);
           main_range.set('end', data.Date[ma]);
        }

        xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", url, true);
        xmlhttp.send();

        selection_source.trigger('change');

        if (sel.length==0){
            $("#details_panel").addClass("hidden");
            $("#details_panel").html("");
        }else{

            var url = "http://127.0.0.1:5000/details";
            xhr = $.ajax({
                type: 'GET',
                url: url,
                contentType: "application/json",
                // data: jsondata,
                header: {
                  client: "javascript"
                }
            });

            xhr.done(function(details) {
                $("#details_panel").removeClass("hidden");
                $("#details_panel").html("<h3>Selected Region Report</h3>");
                $("#details_panel").append("<div>From " + details.start + " to " + details.end + "</div>");
                $("#details_panel").append("<div>Number of original samples " + details.original_samples_no + "</div>");
                $("#details_panel").append("<div>Number of samples " + details.samples_no + "</div>");
                $("#details_panel").append("<div>Factor " + details.factor + "</div>");
            });
        }

    """

    callback = Callback(args={
        'source': static_source,
        'selection_source': selection_source,
        'main_plot': main_plot
    },
                        code=code)
    static_source.callback = callback

    return selection_plot
Beispiel #6
0
x = np.linspace(0, 10, 500)
y = np.sin(x)

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

plot = figure(y_range=(-10, 10), plot_width=400, plot_height=400)
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)

callback = Callback(args=dict(source=source),
                    code="""
    var data = source.get('data');
    var A = amp.get('value')
    var k = freq.get('value')
    var phi = phase.get('value')
    var B = offset.get('value')
    x = data['x']
    y = data['y']
    for (i = 0; i < x.length; i++) {
        y[i] = B + A*Math.sin(k*x[i]+phi);
    }
    source.trigger('change');
""")

amp_slider = Slider(start=0.1,
                    end=10,
                    value=1,
                    step=.1,
                    title="Amplitude",
                    callback=callback)
callback.args["amp"] = amp_slider
 def test_actions_callback_returns_callbacks_customjs(self):
     callback = Callback()
     self.assertIsInstance(callback, callbacks.CustomJS)
Beispiel #8
0
# NOTE: the JS functions for converting RGB to hex are taken from the excellent answer
# by Tim Down at http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
callback = Callback(args=dict(source=source),
                    code="""
    function componentToHex(c) {
        var hex = c.toString(16);
        return hex.length == 1 ? "0" + hex : hex;
    }
    function rgbToHex(r, g, b) {
        return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
    }
    var data = source.get('data');
    var RS = red_slider;
    var GS = green_slider;
    var BS = blue_slider;
    color = data['color'];
    var red_from_slider = RS.get('value');
    var green_from_slider = GS.get('value');
    var blue_from_slider = BS.get('value');
    text_color = data['text_color'];
    color[0] = rgbToHex(red_from_slider, green_from_slider, blue_from_slider);
    if ((red_from_slider > 127) || (green_from_slider > 127) || (blue_from_slider > 127)) {
        text_color[0] = '#000000';
    }
    else {
        text_color[0] = '#ffffff';
    }
    source.trigger('change');
""")

# create slider tool objects to control the RGB levels for first plot. Set callback function to allow refresh
Beispiel #9
0
    plot.add_glyph(Text(x=text_x, y=text_y, text=[region], text_font_size='10pt', text_color='#666666'))
    plot.add_glyph(Circle(x=text_x - 0.1, y=text_y + 2, fill_color=Spectral6[i], size=10, line_color=None, fill_alpha=0.8))
    text_y = text_y - 5

# Add the slider
code = """
    var year = slider.get('value'),
        sources = %s,
        new_source_data = sources[year].get('data');
    renderer_source.set('data', new_source_data);
    renderer_source.trigger('change');
    text_source.set('data', {'year': [String(year)]});
    text_source.trigger('change');
""" % js_source_array

callback = Callback(args=sources, code=code)
slider = Slider(start=years[0], end=years[-1], value=1, step=1, title="Year", callback=callback, name='testy')
callback.args["slider"] = slider
callback.args["renderer_source"] = renderer_source
callback.args["text_source"] = text_source


# Stick the plot and the slider together
layout = vplot(plot, slider)

# Open our custom template
with open('gapminder_template.jinja', 'r') as f:
    template = Template(f.read())

# Use inline resources, render the html and open
resources = Resources(mode='inline')
Beispiel #10
0
# the callback function to update the color of the block and associated label text
# NOTE: the JS functions for converting RGB to hex are taken from the excellent answer
# by Tim Down at http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
callback = Callback(args=dict(source=source), code="""
    function componentToHex(c) {
        var hex = c.toString(16);
        return hex.length == 1 ? "0" + hex : hex;
    }
    function rgbToHex(r, g, b) {
        return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
    }
    var data = source.get('data');
    var RS = red_slider;
    var GS = green_slider;
    var BS = blue_slider;
    color = data['color'];
    var red_from_slider = RS.get('value');
    var green_from_slider = GS.get('value');
    var blue_from_slider = BS.get('value');
    text_color = data['text_color'];
    color[0] = rgbToHex(red_from_slider, green_from_slider, blue_from_slider);
    if ((red_from_slider > 127) || (green_from_slider > 127) || (blue_from_slider > 127)) {
        text_color[0] = '#000000';
    }
    else {
        text_color[0] = '#ffffff';
    }
    source.trigger('change');
""")

# create slider tool objects to control the RGB levels for first plot. Set callback function to allow refresh
red_slider = Slider(start=0, end=255, value=255, step=1, title="R", callback=callback)
Beispiel #11
0
x = np.linspace(0, 10, 500)
y = np.sin(x)

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


plot = figure(y_range=(-10, 10), plot_width=400, plot_height=400)
plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)

callback = Callback(args=dict(source=source), code="""
    var data = source.get('data');
    var A = amp.get('value')
    var k = freq.get('value')
    var phi = phase.get('value')
    var B = offset.get('value')
    x = data['x']
    y = data['y']
    for (i = 0; i < x.length; i++) {
        y[i] = B + A*Math.sin(k*x[i]+phi);
    }
    source.trigger('change');
""")

amp_slider = Slider(start=0.1, end=10, value=1, step=.1, title="Amplitude", callback=callback)
callback.args["amp"] = amp_slider

freq_slider = Slider(start=0.1, end=10, value=1, step=.1, title="Frequency", callback=callback)
callback.args["freq"] = freq_slider

phase_slider = Slider(start=0, end=6.4, value=0, step=.1, title="Phase", callback=callback)
callback.args["phase"] = phase_slider
Beispiel #12
0
    def create_objects(cls, symbol, df, securities):
        descr_box = Paragraph(text='content loading...')

        btn_close_loading = Button(label='Close Loading')
        dialog_loading = Dialog(title='loading',
                                content=vplot(descr_box),
                                name='loading_dialog',
                                buttons=[btn_close_loading],
                                visible=False)

        source_data = dict(df)
        main_source = ColumnDataSource(dict(df))
        source = ColumnDataSource(source_data)

        # TODO: REMOVE THIS COMMENTED CODE! IT'S JUST THE PREVIOUS
        # VERSION USED BEFORE NEW P&D Cached results and algorithm
        # get the cached results of the P&D algorithm computed with the
        # "default" configuration
        # intervals = utils.cached_pumps.get(symbol, pumps.to_dicts(((),(),(),(),(),())))
        # intervals['bottom'] = [0] * len(intervals['start'])
        # intervals['values'] = [max(df['price'])] * len(intervals['start'])
        #
        # intervals = pd.DataFrame(intervals)

        # new version
        stats = utils.get_symbols_cached_stats()[symbol]
        intervals = pd.DataFrame(stats)
        intervals['bottom'] = [0] * len(intervals['start'])
        intervals['values'] = [max(df['price'])] * len(intervals['start'])

        conv = lambda x: utils.to_seconds(pd.to_datetime(x))

        intervals = intervals[
            (pd.to_datetime(intervals['start']) > conv(config.date_range[0])) &
            (pd.to_datetime(intervals['start']) < conv(config.date_range[1]))]

        # Create P&Ds intervals DataSource
        intervals_source = ColumnDataSource(intervals)
        source.tags = ['main_source']

        trends = utils.load_trends_data(symbol, start_date=min(df['dt']))
        trends_source = ColumnDataSource(trends)

        trades = Slider(title="trades",
                        name='trades',
                        value=0,
                        start=0,
                        end=124,
                        step=1)

        # Selectors
        symbol = Select.create(options=securities,
                               value=symbol,
                               name='symbol',
                               title="")
        window_selector = Select.create(options=['---'],
                                        name='period_selector',
                                        title="Search intervals with:")
        symbol_filter = Select.create(
            options=['All', 'Stocks with Spam', 'Stocks without Spam'],
            name='symbol_filter',
            title="Filter Symbols:",
            value='Stocks with Spam')
        callback = Callback(args={
            'symbol_filter': symbol_filter,
            'dialog_loading': dialog_loading
        },
                            code=callbacks.symbol_filter)
        symbol_filter.callback = callback

        btn_detect_pumps = Button(label='Configure P&D Detection',
                                  name='config_pumps')

        main_tab = Panel(title="Main")
        tabs = Tabs()

        # Create STOCKS TABLE
        ranks = utils.get_pumps_rank()
        # quotient_metrics = utils.get_quotient_metrics()
        # ranks['quotient'] = quotient_metrics['quotient']

        foo = lambda x: utils.spams_count.get(x, 0)
        ranks['spams'] = map(foo, ranks['symbol'])
        ranks = ranks.sort(['spams', 'vol_quotient'], ascending=False)

        cls._pre_filtered_ranks = {
            'All': {k: ranks[k]
                    for k in ranks.columns},
            'Stocks with Spam':
            dict(ranks[ranks['spams'] > 0].sort('vol_quotient',
                                                ascending=False)),
            'Stocks without Spam':
            dict(ranks[ranks['spams'] == 0].sort('vol_quotient',
                                                 ascending=False)),
        }

        source_stocks_rank = ColumnDataSource(cls._pre_filtered_ranks['All'])

        table_stocks_rank = DataTable(
            source=source_stocks_rank,
            width=560,
            height=450,
            selectable=True,
            editable=True,
            columns=[
                TableColumn(field='symbol',
                            title='symbol',
                            width=130,
                            editor=StringEditor()),
                TableColumn(field='vol_quotient',
                            title='volume ratio',
                            editor=StringEditor(),
                            default_sort='descending'),
                TableColumn(field='risk_score',
                            title='risk',
                            width=100,
                            editor=StringEditor(),
                            default_sort='descending'),
                TableColumn(field='spams',
                            title='spams',
                            width=130,
                            editor=StringEditor(),
                            default_sort='descending'),
            ])

        callback = Callback(args={
            'tr': table_stocks_rank,
            'sr': source_stocks_rank,
            'symb': symbol,
            'dialog_loading': dialog_loading
        },
                            code=callbacks.source_stocks_rank)
        source_stocks_rank.callback = callback

        return locals()
Beispiel #13
0
       var url = "http://127.0.0.1:5000/subsample/"+data.Date[mi]+"/"+data.Date[ma];
       source_data = selection_source.get('data');
       source_data.bottom = [0]
       source_data.values = [700];
       source_data.start = [data.Date[mi]];
       source_data.end = [data.Date[ma]];

       main_range = main_plot.get('x_range');
       main_range.set('start', data.Date[mi]);
       main_range.set('end', data.Date[ma]);
    }

    xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", url, true);
    xmlhttp.send();

    selection_source.trigger('change');

"""

callback = Callback(args={
    'source': static_source,
    'selection_source': selection_source,
    'main_plot': p
},
                    code=code)
static_source.callback = callback
layout = vplot(selection_plot, p)

show(layout)
Beispiel #14
0
               line_color=None,
               fill_alpha=0.8))
    text_y = text_y - 5

# Add the slider
code = """
    var year = slider.get('value'),
        sources = %s,
        new_source_data = sources[year].get('data');
    renderer_source.set('data', new_source_data);
    renderer_source.trigger('change');
    text_source.set('data', {'year': [String(year)]});
    text_source.trigger('change');
""" % js_source_array

callback = Callback(args=sources, code=code)
slider = Slider(start=years[0],
                end=years[-1],
                value=1,
                step=1,
                title="Year",
                callback=callback,
                name='testy')
callback.args["slider"] = slider
callback.args["renderer_source"] = renderer_source
callback.args["text_source"] = text_source

# Stick the plot and the slider together
layout = vplot(plot, slider)

# Open our custom template