Python ipywidgets.Button() Examples

The following are 30 code examples of ipywidgets.Button(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ipywidgets , or try the search function .
Example #1
Source File: plot.py    From QuLab with MIT License 6 votes vote down vote up
def show(plot, get_data, fig=None):
    if fig is None:
        fig = figure()

    qbt = widgets.Button(description='Quit')
    qbt.value = False

    def cb(bt):
        qbt.value = True
        qbt.disabled = True

    qbt.on_click(cb)

    async def run():
        task = None
        for data in get_data():
            task = draw(fig, plot, data, task)
            if qbt.value == True:
                break
            await asyncio.sleep(0.05)

    fig.display()
    display(qbt)
    asyncio.ensure_future(run()) 
Example #2
Source File: visualization.py    From minian with GNU General Public License v3.0 6 votes vote down vote up
def _meta_wgt(self):
        wgt_meta = {d: pnwgt.Select(
            name=d, options=v, height=45, width=120)
                    for d, v in self.meta_dicts.items()}
        def make_update_func(meta_name):
            def _update(x):
                self.metas[meta_name] = x.new
                self.update_subs()
            return _update
        for d, wgt in wgt_meta.items():
            cur_update = make_update_func(d)
            wgt.param.watch(cur_update, 'value')
        wgt_update = pnwgt.Button(
            name='Refresh', button_type='primary', height=30, width=120)
        wgt_update.param.watch(self.update_all, 'clicks')
        wgt_load = pnwgt.Button(
            name='Load Data', button_type='danger', height=30, width=120)
        wgt_load.param.watch(self.compute_subs, 'clicks')
        return pn.layout.WidgetBox(
            *(list(wgt_meta.values()) + [wgt_update, wgt_load]),
            width=150) 
Example #3
Source File: selection.py    From notebook-molecular-visualization with Apache License 2.0 6 votes vote down vote up
def __init__(self, mol):
        super().__init__(mol)

        self._atomset = collections.OrderedDict()

        self.atom_listname = ipy.Label('Selected atoms:', layout=ipy.Layout(width='100%'))
        self.atom_list = ipy.SelectMultiple(options=list(self.viewer.selected_atom_indices),
                                            layout=ipy.Layout(height='150px'))
        traitlets.directional_link(
            (self.viewer, 'selected_atom_indices'),
            (self.atom_list, 'options'),
            self._atom_indices_to_atoms
        )

        self.select_all_atoms_button = ipy.Button(description='Select all atoms')
        self.select_all_atoms_button.on_click(self.select_all_atoms)

        self.select_none = ipy.Button(description='Clear all selections')
        self.select_none.on_click(self.clear_selections)

        self.representation_buttons = ipy.ToggleButtons(options=['stick','ribbon', 'auto', 'vdw'],
                                                        value='auto')
        self.representation_buttons.observe(self._change_representation, 'value') 
Example #4
Source File: visualization.py    From notebook-molecular-visualization with Apache License 2.0 6 votes vote down vote up
def __init__(self, parent, props):
        super().__init__(layout=ipywidgets.Layout(align_items='flex-end'))
        self.parent = parent
        self.props = props
        self.install_button = ipywidgets.Button()
        self.install_button.add_class('nbv-table-row')
        self.remove_button = ipywidgets.Button(description='remove')
        self.remove_button.add_class('nbv-table-row')
        self.html = ipywidgets.HTML()

        if self.props['writable'] == 'INSTALLED':
            self.chidlren = (self.html,)
        else:
            self.children = (self.html, self.install_button, self.remove_button)
        self.install_button.on_click(self.install)
        self.remove_button.on_click(self.uninstall)
        self.rerender() 
Example #5
Source File: pointcloud.py    From AlignNet-3D with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def show_mesh(mesh_id, cat='car', aligned=True):
    print(mesh_id)
    mesh_fname = f'/globalwork/gross/ModelNet/ModelNet40{"Aligned" if aligned else ""}/{cat}/train/{cat}_{str(mesh_id).zfill(4)}.off'
    if not os.path.isfile(mesh_fname):
        mesh_fname = f'/globalwork/gross/ModelNet/ModelNet40{"Aligned" if aligned else ""}/{cat}/test/{cat}_{str(mesh_id).zfill(4)}.off'
    mesh = get_mesh(mesh_fname)
    mesh.apply_scale(3.)

    def on_button_next(b):
        clear_output()
        show_mesh(mesh_id + 1, cat=cat, aligned=aligned)

    def on_button_prev(b):
        clear_output()
        show_mesh(max(mesh_id - 1, 1), cat=cat, aligned=aligned)

    button_next = ipywidgets.Button(description="Next")
    button_prev = ipywidgets.Button(description="Prev")
    display(ipywidgets.HBox([button_prev, button_next]))
    button_next.on_click(on_button_next)
    button_prev.on_click(on_button_prev)
    scene = trimesh.Scene(mesh.mesh)
    viewer = scene.show(viewer='notebook')
    display(viewer)
    return scene, viewer 
Example #6
Source File: Viewer.py    From meshplot with GNU General Public License v3.0 6 votes vote down vote up
def add_text(self, text, shading={}):
        self.update_shading(shading)
        tt = p3s.TextTexture(string=text, color=self.s["text_color"])
        sm = p3s.SpriteMaterial(map=tt)
        self.text = p3s.Sprite(material=sm, scaleToTexture=True)
        self.scene.add(self.text)

    #def add_widget(self, widget, callback):
    #    self.widgets.append(widget)
    #    widget.observe(callback, names='value')

#    def add_dropdown(self, options, default, desc, cb):
#        widget = widgets.Dropdown(options=options, value=default, description=desc)
#        self.__widgets.append(widget)
#        widget.observe(cb, names="value")
#        display(widget)

#    def add_button(self, text, cb):
#        button = widgets.Button(description=text)
#        self.__widgets.append(button)
#        button.on_click(cb)
#        display(button) 
Example #7
Source File: ABuWGPSBase.py    From abu with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, wg_manager):
        super(WidgetPickStockBase, self).__init__(wg_manager)
        self.add = widgets.Button(description=u'添加为全局选股策略', layout=widgets.Layout(width='98%'),
                                  button_style='info')
        # 添加全局选股策略指令按钮
        self.add.on_click(self.add_pick_stock)
        # 运行混入的BFSubscriberMixin中ui初始化
        self.subscriber_ui([u'点击\'已添加的买入策略\'框中的买入策略', u'将选股策略做为买入策略的附属选股策略'])
        # 买入策略框点击行为:将本卖出策略加到对应的买入策略做为附属
        self.buy_factors.observe(self.add_pick_stock_to_buy_factor, names='value')
        self.accordion.set_title(0, u'添加为指定买入因子的选股策略')
        accordion_shut(self.accordion)
        self.add_box = widgets.VBox([self.add, self.accordion])
        # 构建选股策略独有基础通用ui
        self._pick_stock_base_ui()
        # 具体子策略构建
        self._init_widget() 
Example #8
Source File: ABuWGBFBase.py    From abu with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, wg_manager):
        super(WidgetFactorBuyBase, self).__init__(wg_manager)
        if wg_manager.add_button_style == 'grid':
            add_cb = widgets.Button(description=u'添加为寻找买入策略最优参数组合', layout=widgets.Layout(width='98%'),
                                    button_style='info')
            add_cb.on_click(self.add_buy_factor)

            add_dp = widgets.Button(description=u'添加为寻找独立买入策略最佳组合', layout=widgets.Layout(width='98%'),
                                    button_style='warning')
            add_dp.on_click(self.add_buy_factor_grid)

            self.add = widgets.VBox([add_cb, add_dp])
        else:
            self.add = widgets.Button(description=u'添加为全局买入策略', layout=widgets.Layout(width='98%'),
                                      button_style='info')
            self.add.on_click(self.add_buy_factor)
        self._init_widget() 
Example #9
Source File: viewers.py    From python-esppy with Apache License 2.0 5 votes vote down vote up
def __init__(self,visuals,connection,**kwargs):
        ViewerBase.__init__(self,visuals,connection,**kwargs)

        width = self.getOpt("width","98%")
        height = self.getOpt("height","200px")

        self._max = self.getOpt("max",50);

        self._bg = self.getOpt("bg","#f8f8f8")
        self._border = self.getOpt("border","1px solid #d8d8d8")

        components = []
        self._log = widgets.HTML(value="",layout=widgets.Layout(width=width,height=height,border=self._border,overflow="auto"))
        components.append(self._log)

        self._filter = self.getOpt("filter")
        self._regex = None

        if self._filter != None:
            self._filterText = widgets.Text(description="Filter",value=self._filter,layout=widgets.Layout(width="70%"))
            if len(self._filter) > 0:
                self._regex = re.compile(self._filter,re.I)
            setButton = widgets.Button(description="Set")
            clearButton = widgets.Button(description="Clear")
            setButton.on_click(self.filter)
            clearButton.on_click(self.clearFilter)
            components.append(widgets.HBox([self._filterText,setButton,clearButton]))

        self._box = widgets.VBox(components,layout=widgets.Layout(width="100%"))

        s = ""
        s += "<div style='width:100%;height:100%;background:" + self._bg + "'>"
        s += "</div>"
        self._log.value = s

        self._messages = []

        self._connection.getLog().addDelegate(self)
        
        self.children = [self._box] 
Example #10
Source File: interfaces.py    From notebook-molecular-visualization with Apache License 2.0 5 votes vote down vote up
def __init__(self, xface):
        self.xface = xface

        if xface.is_installed():
            if xface.version_flag:
                v = xface.get_installed_version()
            else:
                v = INSTALLED
        else:
            v = MISSING

        self.maintext = ipy.HTML(
                ('<span class="nbv-table-row nbv-width-med nbv-monospace">'
                 '           {xface.name}</span> '
                 '<span class="nbv-table-row nbv-monospace nbv-width-sm">'
                 '                {localversion}</span> '
                 '<span class="nbv-table-row nbv-monospace nbv-width-sm">'
                 '                {xface.expectedversion}</span>'
                 '<span class="nbv-width-sm nbv-table-row">&nbsp;</span>'  # empty space
                 )
                    .format(xface=xface, localversion=v))

        self.selector = ipy.ToggleButtons(options=['in docker', 'locally'],
                                          value='in docker',
                                          button_style='info')
        self.selector.add_class('nbv-width-lg')
        self.selector.add_class("nbv-table-row")

        self.selector.observe(self._toggle, 'value')
        self.path = ipy.HTML(layout=ipy.Layout(width='150px', font_size='x-small'),
                              value=xface.path if xface.path is not None else '',)

        self.save_button = ipy.Button(description='Make default', layout=ipy.Layout(width='100px'))
        self.save_button.on_click(self.save_selection)
        self.save_button.add_class('nbv-table-row')

        children = [self.maintext, self.selector, self.save_button]

        super().__init__(children=children,
                         layout=ipy.Layout(width='100%', align_items='flex-end')) 
Example #11
Source File: docker.py    From notebook-molecular-visualization with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.client = None
        self.warning = ipy.HTML(description='<b>Engine status:</b>', value=SPINNER)
        self.devmode_label = ipy.Label('Use local docker images (developer mode)',
                                       layout=ipy.Layout(width='100%'))
        self.devmode_button = ipy.Checkbox(value=mdt.compute.config.devmode,
                                           layout=ipy.Layout(width='15px'))
        self.devmode_button.observe(self.set_devmode, 'value')

        self.engine_config_description = ipy.HTML('Docker host with protocol and port'
                                                  ' (e.g., <code>http://localhost:2375</code>).'
                                                  ' If blank, this'
                                                  ' defaults to the docker engine configured at '
                                                  'your command line.',
                                                  layout=ipy.Layout(width='100%'))
        self.engine_config_value = ipy.Text('blank', layout=ipy.Layout(width='100%'))
        self.engine_config_value.add_class('nbv-monospace')

        self.image_box = ipy.Box()

        self._reset_config_button = ipy.Button(description='Reset',
                                               tooltip='Reset to applied value')
        self._apply_changes_button = ipy.Button(description='Apply',
                                                tooltip='Apply for this session')
        self._save_changes_button = ipy.Button(description='Make default',
                                               tooltip='Make this the default for new sessions')
        self._reset_config_button.on_click(self.reset_config)
        self._apply_changes_button.on_click(self.apply_config)
        self._save_changes_button.on_click(self.save_config)

        self.children = [self.warning,
                         VBox([self.engine_config_description,
                               self.engine_config_value]),
                         HBox([self._reset_config_button,
                               self._apply_changes_button,
                               self._save_changes_button]),
                         HBox([self.devmode_button, self.devmode_label]),
                         self.image_box]
        self.reset_config()
        super().__init__(children=self.children)
        self.connect_to_engine() 
Example #12
Source File: notebook_integration.py    From adaptive with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def live_info(runner, *, update_interval=0.5):
    """Display live information about the runner.

    Returns an interactive ipywidget that can be
    visualized in a Jupyter notebook.
    """
    if not _holoviews_enabled:
        raise RuntimeError(
            "Live plotting is not enabled; did you run "
            "'adaptive.notebook_extension()'?"
        )

    import ipywidgets
    from IPython.display import display

    status = ipywidgets.HTML(value=_info_html(runner))

    cancel = ipywidgets.Button(
        description="cancel runner", layout=ipywidgets.Layout(width="100px")
    )
    cancel.on_click(lambda _: runner.cancel())

    async def update():
        while not runner.task.done():
            await asyncio.sleep(update_interval)

            if should_update(status):
                status.value = _info_html(runner)
            else:
                await asyncio.sleep(0.05)

        status.value = _info_html(runner)
        cancel.layout.display = "none"

    runner.ioloop.create_task(update())

    display(ipywidgets.VBox((status, cancel))) 
Example #13
Source File: docker.py    From notebook-molecular-visualization with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        super().__init__(
                **process_widget_kwargs(dict(flex_flow='column')))
        self.repo_field = ipy.Text(description='Image repository')
        self.version_field = ipy.Text(description='Image version')

        self._reset_config_button = ipy.Button(description='Reset',
                                               tooltip='Reset to current configuration')

        self._apply_changes_button = ipy.Button(description='Apply',
                                                tooltip='Apply for this session')
        self._save_changes_button = ipy.Button(description='Make default',
                                               tooltip='Make this the default for new sessions')
        self._pull_button = ipy.Button(description='Pull images',
                                       tooltip=
                                       'Download all moldesign images to the compute engine')

        self.children = (HBox([self.repo_field, self.version_field]),
                         HBox([self._reset_config_button,
                                                self._apply_changes_button,
                                                self._pull_button]))

        self._reset_config_button.on_click(self.reset_config)
        self._apply_changes_button.on_click(self.apply_config)
        self._save_changes_button.on_click(self.save_config)
        self._test_button.on_click(self.test_connection) 
Example #14
Source File: configurator.py    From notebook-molecular-visualization with Apache License 2.0 5 votes vote down vote up
def __init__(self, paramlist, paramdefs, title=None):
        super(Configurator, self).__init__(layout=ipy.Layout(display='flex',
                                                             flex_flow='column',
                                                             align_self='flex-start',
                                                             align_items='stretch',
                                                             max_width='100%'))
        self.paramlist = paramlist
        self.paramdefs = paramdefs

        self.apply_button = ipy.Button(description='Apply')
        self.apply_button.on_click(self.apply_values)

        self.reset_button = ipy.Button(description='Reset')
        self.reset_button.on_click(self.reset_values)
        self.buttons = ipy.Box([self.reset_button, self.apply_button],
                               layout=ipy.Layout(align_self='center'))

        self.selectors = collections.OrderedDict([(p.name, ParamSelector(p)) for p in paramdefs])
        self.reset_values()

        title = utils.if_not_none(title, 'Configuration')
        self.title = ipy.HTML('<center><h4>%s</h4></center><hr>' % title,
                              align_self='center')

        self.currentconfig = ipy.Textarea(description='<i>Current params</i>',
                                          disabled=True,
                                          value=self._pretty_print_config(),
                                          layout=ipy.Layout(width='350px', min_height='300px',
                                                            max_height='500px',
                                                            display='flex', flex_flow='column'))
        self.middle = HBox([VBox(list(self.selectors.values())), self.currentconfig])
        self.children = [self.title, self.middle, self.buttons] 
Example #15
Source File: visualization.py    From minian with GNU General Public License v3.0 5 votes vote down vote up
def _widgets(self):
        w_play = pnwgt.Player(
            length=len(self._f), interval=10,
            value=0, width=650, height=90)
        def play(f):
            if not f.old == f.new:
                self.strm_f.event(f=int(self._f[f.new]))
        w_play.param.watch(play, 'value')
        w_box = pnwgt.Button(
            name='Update Mask',
            button_type='primary',
            width=100,
            height=30)
        w_box.param.watch(self._update_box, 'clicks')
        if not self._layout:
            wgt_meta = {d: pnwgt.Select(
                name=d, options=v, height=45, width=120)
                        for d, v in self.meta_dicts.items()}
            def make_update_func(meta_name):
                def _update(x):
                    self.cur_metas[meta_name] = x.new
                    self._update_subs()
                return _update
            for d, wgt in wgt_meta.items():
                cur_update = make_update_func(d)
                wgt.param.watch(cur_update, 'value')
            wgts = pn.layout.WidgetBox(
                w_box, w_play, *list(wgt_meta.values()))
        else:
            wgts = pn.layout.WidgetBox(
                w_box, w_play)
        return wgts 
Example #16
Source File: visualization.py    From minian with GNU General Public License v3.0 5 votes vote down vote up
def _widgets(self):
        dfrange = [0, self._f]
        w_frame = iwgt.IntSlider(
            value=0,
            min=dfrange[0],
            max=dfrange[1],
            continuous_update=False,
            description="Frame:",
            layout=iwgt.Layout(width='50%'))
        w_play = iwgt.Play(
            value=0,
            min=dfrange[0],
            max=dfrange[1],
            interval=1000 / self.framerate)
        iwgt.jslink((w_play, 'value'), (w_frame, 'value'))
        iwgt.interactive(self.strm_f.event, x=w_frame)
        uidrange = [0, self._u]
        w_select = iwgt.IntRangeSlider(
            value=self._cur_sel,
            min=uidrange[0],
            max=uidrange[1],
            continuous_update=False,
            description="Unit ID:",
            layout=iwgt.Layout(width='50%'))
        w_select.observe(self._set_sel, names='value')
        w_update = iwgt.Button(description="Update")
        w_update.on_click(self._update_plot)
        w_update_mov = iwgt.Checkbox(
            value=self._update_mov, description="Update Movies")
        w_update_mov.observe(self._set_update, names='value')
        w_overlay = iwgt.Checkbox(value=self._overlay, description="Overlay")
        w_overlay.observe(self._set_overlay, names='value')
        return iwgt.VBox([
            iwgt.HBox([w_frame, w_play, w_update_mov]),
            iwgt.HBox([w_select, w_update, w_overlay])
        ]) 
Example #17
Source File: ontologysearch.py    From tellurium with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.ch = bioservices.ChEBI()
        self.kegg = bioservices.KEGG()

        self.wOntologySelect = w.Dropdown(description='Ontology:', options=['ChEBI', 'KEGG.Reaction'])
        self.wSearchTerm = w.Text(description='Search Term:', value="glucose")
        self.wSearchTerm.on_submit(self.search)
        self.wSearchButton = w.Button(description='Search')
        self.wSearchButton.on_click(self.search)

        self.wResultsSelect = w.Select(description='Results:', width='100%')
        self.wResultsSelect.on_trait_change(self.selectedTerm)
        self.wResultsURL = w.Textarea(description='URL:', width='100%')
        self.wResults = w.VBox(children=[
                self.wResultsSelect,
                self.wResultsURL
        ], width='100%')
        for ch in self.wResults.children:
            ch.font_family = 'monospace'
            ch.color = '#AAAAAA'
            ch.background_color = 'black'

        # <Container>
        self.wContainer = w.VBox([
            self.wOntologySelect,
            self.wSearchTerm,
            self.wSearchButton,
            self.wResults
        ])

        # display the container
        display(self.wContainer)
        self.init_display() 
Example #18
Source File: visualization.py    From minian with GNU General Public License v3.0 5 votes vote down vote up
def _widgets(self):
        sel_anm = iwgt.Dropdown(options=self.ls_anm, description='Animal:')
        sel_ss = iwgt.Dropdown(options=self.ls_ss, description='Session:')
        bt_mask0 = iwgt.Button(description="Update Template")
        bt_mask = iwgt.Button(description="Update Target")
        bt_mask0.on_click(self._save_mask0)
        bt_mask.on_click(self._save_mask)
        iwgt.interactive(self.str_sel.event, anm=sel_anm, ss=sel_ss)
        return iwgt.HBox([sel_anm, sel_ss, bt_mask0, bt_mask]) 
Example #19
Source File: pubsub.py    From jupyter-ros with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def subscribe(topic, msg_type, callback):
    """
    Subscribes to a specific topic in another thread, but redirects output!

    @param topic The topic
    @param msg_type The message type
    @param callback The callback

    @return Jupyter output widget
    """

    if subscriber_registry.get(topic):
        print("Removing previous callback, only one redirection possible right now", file=sys.stderr)
        subscriber_registry[topic].unregister()

    out = widgets.Output(layout={'border': '1px solid gray'})
    subscriber_registry[topic] = rospy.Subscriber(topic, msg_type, callback)
    output_registry[topic] = out

    btn = widgets.Button(description='Stop')

    def stop_start_subscriber(x):
        if output_registry.get(topic) is not None:
            subscriber_registry[topic].unregister()
            del output_registry[topic]
            btn.description = 'Start'
        else:
            output_registry[topic] = out
            subscriber_registry[topic] = rospy.Subscriber(topic, msg_type, callback)
            btn.description = 'Stop'

    btn.on_click(stop_start_subscriber)
    btns = widgets.HBox((btn, ))
    vbox = widgets.VBox((btns, out))
    return vbox 
Example #20
Source File: ABuWGBRun.py    From abu with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        """构建回测需要的各个组件形成tab"""
        self.tt = WidgetRunTT()
        self.sc = WidgetSymbolChoice()
        self.bf = BuyFactorWGManager()

        self.sf = SellFactorWGManager()
        # 卖出策略管理注册买入策略接收改变
        self.sf.register(self.bf)

        self.ps = PickStockWGManager()
        # 选股策略管理注册买入策略接收改变
        self.ps.register(self.bf)

        self.pos = PosWGManager()
        # 资金管理注册买入策略接收改变
        self.pos.register(self.bf)

        # 构造裁判界面
        self.ump = WidgetUmp()

        sub_widget_tab = widgets.Tab()
        sub_widget_tab.children = [self.tt.widget, self.sc.widget, self.bf.widget, self.sf.widget, self.ps.widget,
                                   self.pos.widget, self.ump.widget]
        for ind, name in enumerate([u'基本', u'股池', u'买策', u'卖策', u'选股', u'资管', u'裁判']):
            sub_widget_tab.set_title(ind, name)

        self.run_loop_bt = widgets.Button(description=u'开始回测', layout=widgets.Layout(width='98%'),
                                          button_style='danger')
        self.run_loop_bt.on_click(self.run_loop_back)
        self.widget = widgets.VBox([sub_widget_tab, self.run_loop_bt]) 
Example #21
Source File: ABuWGDATool.py    From abu with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, tool_set):
        """初始化数据分析界面"""
        super(WidgetDATool, self).__init__(tool_set)

        da_list = []
        tip_label1 = widgets.Label(u'分析目标需要在\'分析设置\'中选择', layout=self.label_layout)
        tip_label2 = widgets.Label(u'需要设置多个分析目标进行对比', layout=self.label_layout)
        da_list.append(tip_label1)
        da_list.append(tip_label2)

        date_week_wave_bt = widgets.Button(description=u'交易日震幅对比分析', layout=widgets.Layout(width='98%'),
                                           button_style='info')
        date_week_wave_bt.on_click(self.date_week_wave)
        da_list.append(date_week_wave_bt)

        p_change_stats_bt = widgets.Button(description=u'交易日涨跌对比分析', layout=widgets.Layout(width='98%'),
                                           button_style='info')
        p_change_stats_bt.on_click(self.p_change_stats)
        da_list.append(p_change_stats_bt)

        wave_change_rate_bt = widgets.Button(description=u'振幅统计套利条件分析', layout=widgets.Layout(width='98%'),
                                             button_style='info')
        wave_change_rate_bt.on_click(self.wave_change_rate)
        da_list.append(wave_change_rate_bt)

        date_week_win_bt = widgets.Button(description=u'交易日涨跌概率分析', layout=widgets.Layout(width='98%'),
                                          button_style='info')
        date_week_win_bt.on_click(self.date_week_win)
        da_list.append(date_week_win_bt)

        bcut_change_vc_bt = widgets.Button(description=u'交易日涨跌区间分析(预定区间)', layout=widgets.Layout(width='98%'),
                                           button_style='info')
        bcut_change_vc_bt.on_click(self.bcut_change_vc)
        da_list.append(bcut_change_vc_bt)

        qcut_change_vc_bt = widgets.Button(description=u'交易日涨跌区间分析(不定区间)', layout=widgets.Layout(width='98%'),
                                           button_style='info')
        qcut_change_vc_bt.on_click(self.qcut_change_vc)
        da_list.append(qcut_change_vc_bt)

        self.widget = widgets.VBox(da_list, layout=widgets.Layout(width='58%')) 
Example #22
Source File: ABuWGStockInfo.py    From abu with GNU General Public License v3.0 5 votes vote down vote up
def other_industries_symbol(self, stock_info):
        """从股票信息查询其对应行业的其它股票,构建形势为按钮序列,暂时只取出10个相关的股票"""
        other_co_symbol = ABuIndustries.query_factorize_industry_symbol(
            stock_info.industry_factorize.values[0], market=self.symbol.market)
        other_co_bs = []
        # TODO 加载更多或者分段加载方式,暂时只取出10个相关的股票
        other_co_symbol = other_co_symbol[:10] if len(other_co_symbol) > 10 else other_co_symbol
        for symbol in other_co_symbol:
            # 通过symbol查询公司名称等信息
            stock_info = query_stock_info(symbol)
            if stock_info is None or stock_info.empty:
                continue

            # 构建button上显示的文字
            co_name_str = self._combine_stock_name(stock_info, only_name=True)
            button = widgets.Button(description=co_name_str, disabled=False)
            # 添加一个新属性symbol在button对象里,on_button_clicked使用
            button.symbol = symbol

            def on_button_clicked(bt):
                # 关闭当前整个大的widget界面,重新构建一个全新的界面
                self.widget.close()
                symbol_code = code_to_symbol(bt.symbol)
                self.symbol = symbol_code
                # 重新赋予self.widget值,即一个新的widget
                self.widget = self.stock_base_info(self.symbol)
                # 重新显示新的界面
                self.display()

            button.on_click(on_button_clicked)
            other_co_bs.append(button)

        # 将symbol button一行显示两个,2个为一组,组装子symbol button序列,
        other_co_bs = self._sub_split(other_co_bs, len(other_co_bs) / 2)
        # 将每一组加到一个行box里面
        tbs_boxs = [widgets.HBox(tbs) for tbs in other_co_bs]
        self.other_co_box = widgets.VBox(tbs_boxs)
        return self.other_co_box 
Example #23
Source File: ABuWGTLTool.py    From abu with GNU General Public License v3.0 5 votes vote down vote up
def _init_tip_label_with_step_x(self, callback_analyse, analyse_name, with_step_x=True):
        """step_x需要的地方比较多,统一构建,外部接收赋予名字"""
        if not callable(callback_analyse):
            raise TabError('callback_analyse must callable!')

        tip_label = widgets.Label(self.map_tip_target_label(n_target=1), layout=self.label_layout)
        widget_list = [tip_label]
        step_x = None
        if with_step_x:
            step_x_label = widgets.Label(u'时间步长控制参数step_x,默认1.0',
                                         layout=self.label_layout)
            step_x = widgets.FloatSlider(
                value=1.0,
                min=0.1,
                max=2.6,
                step=0.1,
                description=u'步长',
                disabled=False,
                orientation='horizontal',
                readout=True,
                readout_format='.1f',
            )
            # 返回给需要的ui,命名独有的step_x
        yield widget_list, step_x

        if with_step_x:
            # noinspection PyUnboundLocalVariable
            step_x_box = widgets.VBox([step_x_label, step_x])
            # noinspection PyTypeChecker
            widget_list.append(step_x_box)

        analyse_bt = widgets.Button(description=analyse_name, layout=widgets.Layout(width='98%'),
                                    button_style='info')
        analyse_bt.on_click(callback_analyse)
        widget_list.append(analyse_bt) 
Example #24
Source File: ABuWGBase.py    From abu with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, search_result_callable):
        """构建股票池选股ui界面"""
        if not callable(search_result_callable):
            raise TypeError('search_result_select_func must callable!')
        # symbol搜索框构建
        self.search_bt = widgets.Button(description=u'搜索:', layout=widgets.Layout(height='10%', width='7%'))
        self.search_input = widgets.Text(
            value='',
            placeholder=u'交易代码/公司名称/拼音首字母',
            description='',
            disabled=False
        )
        self.search_input.observe(self._search_input_change, names='value')

        # symbol搜索结果框
        self.search_result = widgets.SelectMultiple(
            options=[],
            description=u'搜索结果:',
            disabled=False,
            layout=widgets.Layout(width='300px', align_items='stretch', justify_content='space-between')
        )
        self.search_result.observe(search_result_callable, names='value')
        self.search_bt.on_click(self._do_search)

        # 搜索框 + 按钮 + 结果框 box拼接
        sc_hb = widgets.HBox([self.search_bt, self.search_input])
        self.widget = widgets.VBox([sc_hb, self.search_result])

    # noinspection PyUnusedLocal 
Example #25
Source File: ABuWGSFBase.py    From abu with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, wg_manager):
        super(WidgetFactorSellBase, self).__init__(wg_manager)

        if wg_manager.add_button_style == 'grid':
            add_cb = widgets.Button(description=u'添加为寻找卖出策略最优参数组合', layout=widgets.Layout(width='98%'),
                                    button_style='info')
            add_cb.on_click(self.add_sell_factor)

            add_dp = widgets.Button(description=u'添加为寻找独立卖出策略最佳组合', layout=widgets.Layout(width='98%'),
                                    button_style='warning')
            add_dp.on_click(self.add_sell_factor_grid)

            self.add = widgets.VBox([add_cb, add_dp])
        else:
            self.add = widgets.Button(description=u'添加为全局卖出策略', layout=widgets.Layout(width='98%'),
                                      button_style='info')
            # 添加全局卖出策略指令按钮
            self.add.on_click(self.add_sell_factor)

        if self.wg_manager.show_add_buy:
            # 运行混入的BFSubscriberMixin中ui初始化
            self.subscriber_ui([u'点击\'已添加的买入策略\'框中的买入策略', u'将卖出策略做为买入策略的附属卖出策略'])
            # 买入策略框点击行为:将本卖出策略加到对应的买入策略做为附属
            self.buy_factors.observe(self.add_sell_factor_to_buy_factor, names='value')
            self.accordion.set_title(0, u'添加为指定买入因子的卖出策略')
            accordion_shut(self.accordion)
            self.add_box = widgets.VBox([self.add, self.accordion])
        else:
            self.add_box = self.add

        self._init_widget() 
Example #26
Source File: ABuWGUmp.py    From abu with GNU General Public License v3.0 5 votes vote down vote up
def _init_manager_ui(self):
        """裁判数据管理界面初始化"""
        description = widgets.Textarea(
            value=u'删除选择的裁判本地数据:\n'
                  u'删除所选择的已训练好的本地裁判数据,谨慎操作!\n'
                  u'分享选择的裁判:\n'
                  u'将训练好的裁判数据分享到交易社区,供其他交易者使用\n'
                  u'下载更多的裁判:\n'
                  u'从交易社区,下载更多训练好的裁判数据\n',

            disabled=False,
            layout=widgets.Layout(height='150px')
        )

        self.manager_umps = widgets.Select(
            options=[],
            description=u'本地裁判:',
            disabled=False,
            layout=widgets.Layout(width='100%', align_items='stretch')
        )
        self.load_train_ump(self.manager_umps)
        delete_bt = widgets.Button(description=u'删除选择的裁判本地数据', layout=widgets.Layout(width='98%'),
                                   button_style='warning')
        delete_bt.on_click(self._do_delete_ump)

        share_bt = widgets.Button(description=u'分享选择的裁判', layout=widgets.Layout(width='98%'),
                                  button_style='info')
        share_bt.on_click(permission_denied)
        down_bt = widgets.Button(description=u'下载更多的裁判', layout=widgets.Layout(width='98%'),
                                 button_style='info')
        down_bt.on_click(permission_denied)

        return widgets.VBox([description, self.manager_umps, delete_bt, share_bt, down_bt]) 
Example #27
Source File: ABuWGUmp.py    From abu with GNU General Public License v3.0 5 votes vote down vote up
def _init_train_ui(self):
        """裁判特征训练面初始化"""
        description = widgets.Textarea(
            value=u'裁判特征训练:\n'
                  u'通过在\'裁判特征采集\'选中\'回测过程生成交易特征\'可在回测完成后保存当此回测结果\n'
                  u'所有回测的结果将显示在下面的\'备选回测:\'框中\n'
                  u'通过\'开始训练裁判\'进行指定的回测裁判训练,训练后的裁判在\'裁判预测拦截\'下可进行选择,选中的裁判将在对应的'
                  u'回测中生效,即开始在回测中对交易进行预测拦截等智能交易干涉行为',

            disabled=False,
            layout=widgets.Layout(height='150px')
        )

        self.abu_result = widgets.Select(
            options=[],
            description=u'备选回测:',
            disabled=False,
            layout=widgets.Layout(width='100%', align_items='stretch')
        )
        self.load_abu_result()

        train_bt = widgets.Button(description=u'开始训练裁判', layout=widgets.Layout(width='98%'),
                                  button_style='info')
        train_bt.on_click(self._do_train)
        delete_bt = widgets.Button(description=u'删除选择的备选回测本地数据', layout=widgets.Layout(width='98%'),
                                   button_style='warning')
        delete_bt.on_click(self._do_delete_abu_result)

        return widgets.VBox([description, self.abu_result, train_bt, delete_bt]) 
Example #28
Source File: ABuWGGridSearch.py    From abu with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        """构建回测需要的各个组件形成tab"""

        tip_label1 = widgets.Label(u'最优参数grid search暂不支持实时网络数据模式', layout=widgets.Layout(width='300px'))
        tip_label2 = widgets.Label(u'非沙盒模式需先用\'数据下载界面操作\'进行下载', layout=widgets.Layout(width='300px'))
        """沙盒数据与开放数据模式切换"""
        self.date_mode = widgets.RadioButtons(
            options=[u'沙盒数据模式', u'开放数据模式'],
            value=u'沙盒数据模式' if ABuEnv._g_enable_example_env_ipython else u'开放数据模式',
            description=u'数据模式:',
            disabled=False
        )
        self.date_mode.observe(self.on_data_mode_change, names='value')
        date_mode_box = widgets.VBox([tip_label1, tip_label2, self.date_mode])

        self.sc = WidgetSymbolChoice()
        self.bf = BuyFactorWGManager(add_button_style='grid')
        self.sf = SellFactorWGManager(show_add_buy=False, add_button_style='grid')

        sub_widget_tab = widgets.Tab()
        sub_widget_tab.children = [self.bf.widget, self.sf.widget, self.sc.widget]
        for ind, name in enumerate([u'买策', u'卖策', u'股池']):
            sub_widget_tab.set_title(ind, name)

        self.begin_grid_search = widgets.Button(description=u'开始寻找策略最优参数组合', layout=widgets.Layout(width='98%'),
                                                button_style='danger')
        self.begin_grid_search.on_click(self.run_grid_search)

        self.widget = widgets.VBox([date_mode_box, sub_widget_tab, self.begin_grid_search]) 
Example #29
Source File: widgets.py    From paramnb with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self._select = Dropdown(*args,**kwargs)
        self._edit = Button(description='...',
                            layout=Layout(width='15px'))
        self._composite = HBox([self._select,self._edit])
        super(DropdownWithEdit, self).__init__()
        self.layout = self._composite.layout
        # so that others looking at this widget's value get the
        # dropdown's value
        traitlets.link((self._select,'value'),(self,'value'))
        self._edit.on_click(lambda _: editor(self._select.value))
        self._select.observe(lambda e: self._set_editable(e['new']),'value')
        self._set_editable(self._select.value) 
Example #30
Source File: TSEBIPythonInterface.py    From pyTSEB with GNU General Public License v3.0 5 votes vote down vote up
def resistances_image(self):
        '''Widgets for resistance model selection'''

        self.w_res = widgets.ToggleButtons(
            description='Select TSEB model to run:',
            options={
                'Kustas & Norman 1999': 0,
                'Choudhury & Monteith 1988': 1,
                'McNaughton & Van der Hurk': 2},
            value=self.res,
            width=300)

        self.w_PT_But = widgets.Button(
            description='Browse Initial alphaPT Image')
        self.w_PT = widgets.Text(description=' ', value=str(self.max_PT), width=500)

        self.w_KN_b_But = widgets.Button(description='Browse Resistance Parameter b Image')
        self.w_KN_b = widgets.Text(
            value=str(self.KN_b), description=' ', width=500)
        self.w_KN_c_But = widgets.Button(description=('Browse Resistance Parameter c image'))
        self.w_KN_c = widgets.Text(
            value=str(self.KN_c), description='(m s-1 K-1/3)', width=500)
        self.w_KN_C_dash_But = widgets.Button(description=("Browse Resistance Parameter C' Image"))
        self.w_KN_C_dash = widgets.Text(
            value=str(self.KN_C_dash), description="s1/2 m-1", width=500)
        self.KN_params_box = widgets.VBox([widgets.HTML('Select resistance parameter b image or type a constant value'),
                                           widgets.HBox([self.w_KN_b_But, self.w_KN_b]),
                                           widgets.HTML('Select resistance parameter c image or type a constant value'),
                                           widgets.HBox([self.w_KN_c_But, self.w_KN_c]),
                                           widgets.HTML('Select resistance parameter C\' image or type a constant value'),
                                           widgets.HBox([self.w_KN_C_dash_But, self.w_KN_C_dash])], background_color='#EEE')
        self.res_page = widgets.VBox([self.w_res, self.KN_params_box], background_color='#EEE')

        self.w_KN_b_But.on_click(
            lambda b: self._on_input_clicked(b, 'Resistance Parameter b', self.w_KN_b))
        self.w_KN_c_But.on_click(
            lambda b: self._on_input_clicked(b, 'Resistance Parameter c', self.w_KN_c))
        self.w_KN_C_dash_But.on_click(
            lambda b: self._on_input_clicked(b, 'Resistance Parameter C\'', self.w_KN_C_dash))