Example #1
0
    def add_traces(self):

        self.fig.add_trace(
            Scatter(x=self.x,
                    y=self.lower,
                    line_color='rgb(220, 220, 220)',
                    showlegend=False,
                    mode='lines',
                    name='Нижняя граница (95%-й интервал)'))

        self.fig.add_trace(
            Scatter(x=self.x,
                    y=self.y,
                    name='Прогноз',
                    mode='lines',
                    line=dict(color=self.colors[0]),
                    showlegend=True))

        self.fig.add_trace(
            Scatter(x=self.x,
                    y=self.upper,
                    fill='tonexty',
                    fillcolor='rgba(250, 250, 250, 0.4)',
                    line_color='rgb(220, 220, 220)',
                    showlegend=False,
                    mode='lines',
                    name='Верхняя граница (95%-й интервал)'))

        return self
Example #2
0
def get_figure(edges, nodes):
    edge_trace = Scatter(x=[x for x, _ in edges],
                         y=[x for _, x in edges],
                         line=dict(width=0.5, color='#888'),
                         hoverinfo='none',
                         mode='lines')

    node_trace = Scatter(x=[x[0] for x in nodes.values()],
                         y=[x[1] for x in nodes.values()],
                         customdata=[(x, y[3]) for x, y in nodes.items()],
                         text=[x[3] for x in nodes.values()],
                         mode='markers',
                         hoverinfo='text',
                         marker=dict(showscale=False,
                                     color=[x[2] for x in nodes.values()],
                                     size=15))

    figure = Figure(
        data=[edge_trace, node_trace],
        layout=Layout(showlegend=False,
                      hovermode='closest',
                      margin=dict(b=20, l=5, r=5, t=40),
                      xaxis=dict(showgrid=False,
                                 zeroline=False,
                                 showticklabels=False),
                      yaxis=dict(showgrid=False,
                                 zeroline=False,
                                 showticklabels=True),
                      paper_bgcolor='rgba(0,0,0,0)',
                      plot_bgcolor='rgba(0,0,0,0)'),
    )
    return figure
Example #3
0
    def countries_shifted_scatters(self, countries: list, column: str, threshold: int = 100, mode: str = None, showlegend: bool=True) -> Figure:
        countries_df = self.countries_dataframe(countries=countries, column=column, threshold=threshold)
        countries_df.dropna(axis="index", how="all", inplace=True)
        countries_df = countries_df.apply(lambda x: Series(x.dropna().values))

        engine = inflect.engine()

        fig = Figure()

        for country in countries:
            fig.add_trace(
                Scatter(
                    x=countries_df.index,
                    y=countries_df[country],
                    name=country,
                    mode=mode,
                    line_color=self.color.get(country, "black"),
                    opacity=0.9,
                    showlegend=showlegend,
                )
            )

        fig.update_layout(yaxis_type="log")
        fig.update_layout(title_text="Days since \"{}\" column above {} {}".format(column, threshold, engine.plural_noun("occurence", threshold)))

        return fig
def main():
    # Data File Name and file path
    filename = 'us-counties.csv'
    filepath = os.path.join('./data/raw', filename)

    # Import data into DataFrame and rename columns
    df = read_csv(filepath, dtype={'fips': str})
    df.columns = ['date', 'county', 'state', 'zip', 'cases', 'deaths']

    print(df.dtypes)
    print(f'Number of total cases:  {df.cases.sum()}')
    print(f'Number of total deaths:  {df.deaths.sum()}')

    # Extract Year, Month and Date and place in separate columns
    df['year'] = DatetimeIndex(df.date, yearfirst=True).year
    df['month'] = DatetimeIndex(df.date, yearfirst=True).month_name()

    # States and Counties
    states = df.state.unique()
    counties = df.county.unique()

    # Sum of Grouped Dats
    grp_dates = df.groupby(['date', 'state'])['cases', 'deaths'].sum()
    print(grp_dates.sum())

    # Plot Scatter plot of Cases vs Deaths
    renderers.default = 'browser'

    fig = Figure(data=Scatter(x=df.cases, y=df.deaths, mode='markers'))

    fig.show()

    return
Example #5
0
    def countries_scatters(self, countries: list, column: str, mode: str=None, showlegend: bool=True) -> Figure:
        fig = Figure()

        ratio_re = re.compile(r"(?x: \b Ratio \b )")
        daily_re = re.compile(r"(?x: \b Daily \b )")

        if ratio_re.search(column) is not None:
            fig.update_layout(yaxis=dict(tickformat="%.format.%3f"))

        for country in countries:
            country_df = self.main_df.loc[[country]].reset_index(level=0, drop=True)

            if daily_re.search(column) is not None:
                country_df = country_df[1:]

            fig.add_trace(
                Scatter(
                    x=country_df.index,
                    y=country_df[column],
                    name=country,
                    mode=mode,
                    line_color=self.color.get(country, "black"),
                    opacity=0.9,
                    showlegend=showlegend,
                )
            )

        fig.update_layout(title_text=column)

        return fig
Example #6
0
def compare_models(labels_of_models, accuracies, losses):
    global MODELS_DIR
    for i in range(0, len(labels_of_models)):
        labels_of_models[i] = labels_of_models[i].replace(MODELS_DIR, '')
        labels_of_models[i] = labels_of_models[i].replace('/', '')
        labels_of_models[i] = labels_of_models[i].replace('cnn_', '')
        labels_of_models[i] = labels_of_models[i].replace('.model', '')
    figure = make_subplots(rows=1, cols=2)
    figure.add_trace(
        Scatter(x=labels_of_models, y=accuracies, name='Accuracies', mode='lines'),
        row=1, col=1)
    figure.add_trace(
        Scatter(x=labels_of_models, y=losses, name='Losses', mode='lines'),
        row=1, col=2)
    figure.update_layout(title_text='Best LR and BS {lr : bs}')
    figure.show()
Example #7
0
def _plot_line(xs, ys_population, title, path=''):
    max_colour, mean_colour, std_colour, transparent = 'rgb(0, 132, 180)', 'rgb(0, 172, 237)', 'rgba(29, 202, 255, 0.2)', 'rgba(0, 0, 0, 0)'

    ys = torch.tensor(ys_population, dtype=torch.float32)
    ys_min, ys_max, ys_mean, ys_std = ys.min(1)[0].squeeze(), ys.max(
        1)[0].squeeze(), ys.mean(1).squeeze(), ys.std(1).squeeze()
    ys_upper, ys_lower = ys_mean + ys_std, ys_mean - ys_std

    trace_max = Scatter(x=xs,
                        y=ys_max.numpy(),
                        line=Line(color=max_colour, dash='dash'),
                        name='Max')
    trace_upper = Scatter(x=xs,
                          y=ys_upper.numpy(),
                          line=Line(color=transparent),
                          name='+1 Std. Dev.',
                          showlegend=False)
    trace_mean = Scatter(x=xs,
                         y=ys_mean.numpy(),
                         fill='tonexty',
                         fillcolor=std_colour,
                         line=Line(color=mean_colour),
                         name='Mean')
    trace_lower = Scatter(x=xs,
                          y=ys_lower.numpy(),
                          fill='tonexty',
                          fillcolor=std_colour,
                          line=Line(color=transparent),
                          name='-1 Std. Dev.',
                          showlegend=False)
    trace_min = Scatter(x=xs,
                        y=ys_min.numpy(),
                        line=Line(color=max_colour, dash='dash'),
                        name='Min')

    plotly.offline.plot(
        {
            'data':
            [trace_upper, trace_mean, trace_lower, trace_min, trace_max],
            'layout':
            dict(title=title,
                 xaxis={'title': 'Episode'},
                 yaxis={'title': title})
        },
        filename=os.path.join(path, title + '.html'),
        auto_open=False)
Example #8
0
 def in_team_trace(player_eps: DF) -> Scatter:
     return Scatter(
         x=player_eps['Current Cost'],
         y=player_eps['Expected Points ' + horizon],
         mode='markers',
         marker={'size': MAX_POINT_SIZE, 'color': 'white', 'line': {'width': 1}},
         name='In Team',
         text=player_eps['Label'])
Example #9
0
 def event_capture_trace(player_eps: DF) -> Scatter:
     return Scatter(
         x=player_eps['Current Cost'],
         y=player_eps['Expected Points ' + horizon],
         mode='markers',
         opacity=0,
         marker={'size': player_eps['Size'], 'color': 'white', 'opacity': 1.0},
         name='Player',
         text=player_eps['Label'])
Example #10
0
def run_backtester(ticker, degree, n_ticks):
    good_data = get_ticker_data_2(ticker)
    good_data['time'] = good_data.index  
    start = good_data['time'][0]
    time = np.array([pd.Timedelta(x-start).total_seconds() for x in good_data['time']])
    bt = Backtest(good_data, SmaCross, cash=10_000, commission=.002)
    stats = bt.optimize(n1=range(5, 50, 5),
            n2=range(10, 200, 5),
            maximize='Equity Final [$]',
            constraint=lambda param: param.n1 < param.n2)
    eq_curve = stats._equity_curve
    eq_curve['time'] = eq_curve.index
    fig5 = px.line(eq_curve,x='time',y='Equity',template='simple_white')
    fig1 = px.scatter(good_data,x='time',y='Open',template='simple_white',title='Time Series')
    fig1.update_traces(marker={'size': 4})
    fig1.add_trace(Scatter(x=good_data['time'],y=SMA(good_data['Open'],stats._strategy.n1),name='Short MA'))
    fig1.add_trace(Scatter(x=good_data['time'],y=SMA(good_data['Open'],stats._strategy.n2),name='Long MA'))
    return fig5, fig1
Example #11
0
 def trace(player_eps: DF, position: str) -> Scatter:
     return Scatter(
         x=player_eps['Current Cost'],
         y=player_eps['Expected Points ' + horizon],
         name=position,
         mode='markers',
         marker={'color': POSITION_COLORS[position],
                 'opacity': player_eps['Opacity'],
                 'size': player_eps['Size']},
         text=player_eps['Label'])
Example #12
0
    def create_traces(self):

        # ---------------------------------------------------------------------
        # Colors for cells background theme

        colors = ['rgb(144, 144, 144)', 'rgb(190, 190, 190)']

        # ---------------------------------------------------------------------
        # Scatter plot with fact and predict time series

        trace_1 = Scatter(x=self.create_index(),
                          y=self.y_pred,
                          name='Прогноз',
                          mode='lines',
                          line=dict(color=colors[0]),
                          showlegend=True)

        trace_2 = Scatter(x=self.create_index(),
                          y=self.y,
                          name='Факт',
                          mode='lines',
                          line=dict(color=colors[1]),
                          showlegend=True)

        # ---------------------------------------------------------------------
        # Tables with stats params

        table_1 = self.create_table(self.table_metrics)
        table_2 = self.create_table(self.table_params)

        # ---------------------------------------------------------------------
        # add all objects to figure

        self.fig.add_trace(trace_1, row=1, col=1)
        self.fig.add_trace(trace_2, row=1, col=1)

        self.fig.add_trace(table_1, row=2, col=1)
        self.fig.add_trace(table_2, row=3, col=1)

        return self
Example #13
0
    def _draw_point(self, radius, color, name, center=[0, 0, 0] * u.km):
        x_center, y_center = self._project(
            center[None])  # Indexing trick to add one extra dimension

        trace = Scatter(
            x=x_center.to(u.km).value,
            y=y_center.to(u.km).value,
            mode="markers",
            marker=dict(size=10, color=color),
            name=name,
        )
        self._figure.add_trace(trace)

        return trace
Example #14
0
    def create_traces(self, y_pred, y_fact, row, col):

        colors = ['rgb(144, 144, 144)', 'rgb(190, 190, 190)']

        index = array(list(range(0, len(y_fact))))

        trace_1 = Scatter(x=index,
                          y=y_pred,
                          mode='lines',
                          line=dict(color=colors[0]),
                          name='Прогноз',
                          showlegend=False)

        trace_2 = Scatter(x=index,
                          y=y_fact,
                          mode='lines',
                          line=dict(color=colors[1]),
                          name='Факт',
                          showlegend=False)

        self.fig.add_trace(trace_1, row=row, col=col)
        self.fig.add_trace(trace_2, row=row, col=col)

        return self
Example #15
0
    def _plot_trajectory(self, trajectory, label, color, dashed):
        if self._frame is None:
            raise ValueError("A frame must be set up first, please use "
                             "set_frame(*orbit.pqw()) or plot(orbit).")

        rr = trajectory.represent_as(CartesianRepresentation).xyz.transpose()
        x, y = self._project(rr)

        trace = Scatter(
            x=x.to(u.km).value,
            y=y.to(u.km).value,
            name=label,
            line=dict(color=color, width=2,
                      dash="dash" if dashed else "solid"),
            hoverinfo="none",  # TODO: Review
            mode="lines",  # Boilerplate
        )
        self._figure.add_trace(trace)

        return trace
Example #16
0
    def _get_2d_domain_lines(draw_domains) -> List[Scatter]:
        """
        Returns a list of Scatter objects tracing the domain lines on a
        2-dimensional chemical potential diagram.
        """
        x, y = [], []

        for pts in draw_domains.values():
            x.extend(pts[:, 0].tolist() + [None])
            y.extend(pts[:, 1].tolist() + [None])

        lines = [
            Scatter(
                x=x,
                y=y,
                mode="lines+markers",
                line=dict(color="black", width=3),
                showlegend=False,
            )
        ]
        return lines
Example #17
0
def update_graph_live(n):
    count_list = sorted([this for this in list(count.items()) if this[0].lower() not in set(stop_word)],
                        key=lambda x: x[1], reverse=True, )
    to_show = {count_item[0]: count_item[1] for count_item in count_list[:token_count]}
    word_cloud = WordCloud().generate_from_frequencies(frequencies=to_show, max_font_size=max_font_size, )
    max_size = max(this[1] for this in word_cloud.layout_)
    min_size = min(this[1] for this in word_cloud.layout_)
    logger.info('cloud min count: {}'.format(min([count[this[0][0]] for this in word_cloud.layout_])))

    return Figure(data=[Scatter(mode='text', text=[this[0][0] if '/' not in this[0][0] else this[0][0].split('/')[0]
                                                   for this in word_cloud.layout_], hoverinfo='text',
                                hovertext=['{}: {}'.format(this[0][0], count[this[0][0]], ) for this in
                                           word_cloud.layout_],
                                x=[this[2][0] for this in word_cloud.layout_],
                                y=[this[2][1] for this in word_cloud.layout_], textfont=dict(
            # todo make the sizes less disparate
            color=[float_color_to_hex(int((this[1] - min_size) * 255 / max_size), cm.get_cmap(plotly_colormap))
                   for this in word_cloud.layout_],
            size=[2 * this[1] for this in word_cloud.layout_], ))],
                  layout=Layout(autosize=True, height=800, width=1800, xaxis=dict(showticklabels=False),
                                yaxis=dict(showticklabels=False), ))
Example #18
0
    def _plot_coordinates(self, coordinates, label, colors, dashed):
        if self._frame is None:
            raise ValueError("A frame must be set up first, please use "
                             "set_orbit_frame(orbit) or plot(orbit)")

        rr = coordinates.xyz.transpose()
        x, y = self._project(rr)

        trace = Scatter(
            x=x.to(u.km).value,
            y=y.to(u.km).value,
            name=label,
            line=dict(color=colors[0],
                      width=2,
                      dash="dash" if dashed else "solid"),
            hoverinfo="none",  # TODO: Review
            mode="lines",  # Boilerplate
        )
        self._figure.add_trace(trace)

        return trace
Example #19
0
    def _draw_marker(self,
                     symbol,
                     size,
                     color,
                     name=None,
                     center=[0, 0, 0] * u.km):
        x_center, y_center = self._project(
            center[None])  # Indexing trick to add one extra dimension

        showlegend = False if name is None else True

        trace = Scatter(
            x=x_center.to_value(self._unit),
            y=y_center.to_value(self._unit),
            mode="markers",
            marker=dict(size=size, color=color, symbol=symbol),
            name=name,
            showlegend=showlegend,
        )
        self._figure.add_trace(trace)

        return trace
Example #20
0
    def _get_2d_domain_lines(domains: Dict[str, np.ndarray],
                             elements: List[Element]) -> List[Scatter]:
        """Returns a list of Scatter objects tracing the domain lines on a
        2-dimensional chemical potential diagram"""
        x, y = [], []
        elems = set(elements)
        for formula, pts in domains.items():
            formula_elems = set(Composition(formula).elements)
            if not formula_elems.issubset(elems):
                continue

            x.extend(pts[:, 0].tolist() + [None])
            y.extend(pts[:, 1].tolist() + [None])

        lines = [
            Scatter(
                x=x,
                y=y,
                mode="lines+markers",
                line=dict(color="black", width=3),
                showlegend=False,
            )
        ]
        return lines
Example #21
0
                 target_df[column],
                 c='gray',
                 label='forecast',
                 marker='x',
             )
     elif plot_method == plot_methods[1]:
         for col in range(1, 3):
             # todo fix name/legend
             for window in range(1, window_count + 1):
                 column = 'projected_{}'.format(window)
                 figure.add_trace(
                     Scatter(
                         marker=dict(color='Gray'),
                         marker_symbol='x',
                         mode='markers',
                         name='forecast',
                         showlegend=False,
                         x=target_df['date'],
                         y=target_df[column],
                     ),
                     col=col,
                     row=1,
                 )
 else:
     if plot_method == plot_methods[0]:
         for window in range(1, window_count + 1):
             column = 'projected_{}'.format(window)
             axes.scatter(
                 target_df['date'],
                 target_df[column],
                 c='gray',
def return_figures(df):
    figures = []

    # visualize imbalance of classes
    if os.path.isfile('data/df_class_imbalance.pkl'):
        graph_one = []
        data_stat = joblib.load('data/df_class_imbalance.pkl')

        graph_one.append(
            Bar(name='0',
                x=data_stat['Disaster message category'],
                y=data_stat['Distribution ratio - 0']))
        graph_one.append(
            Bar(name='1',
                x=data_stat['Disaster message category'],
                y=data_stat['Distribution ratio - 1']))

        layout_one = dict(
            barmode='group',
            title='Distribution ratio of messages for each disaster category',
            yaxis=dict(title="Percentage"),
            xaxis=dict(title="Category", tickangle=-45),
            margin=dict(b=160))

        figures.append(dict(data=graph_one, layout=layout_one))

    # visualize average message length
    if os.path.isfile('data/df_word_length.pkl'):
        graph_two = []
        data_length = joblib.load('data/df_word_length.pkl')

        graph_two.append(
            Scatter(
                name='direct',
                x=data_length[data_length['genre'] == 'direct']['index'],
                y=data_length[data_length['genre'] == 'direct']['length'],
                showlegend=True,
                mode='markers',
            ))
        graph_two.append(
            Scatter(
                name='news',
                x=data_length[data_length['genre'] == 'news']['index'],
                y=data_length[data_length['genre'] == 'news']['length'],
                showlegend=True,
                mode='markers',
            ))
        graph_two.append(
            Scatter(
                name='social',
                x=data_length[data_length['genre'] == 'social']['index'],
                y=data_length[data_length['genre'] == 'social']['length'],
                showlegend=True,
                mode='markers',
            ))

        layout_two = dict(title='Average number of words per message',
                          yaxis=dict(title="Average length"),
                          xaxis=dict(visible=False, title="Message id"))

        figures.append(dict(data=graph_two, layout=layout_two))

    # visualize count per genre
    graph_three = []
    genre_counts = df.groupby('genre').count()['message']
    genre_names = list(genre_counts.index)

    graph_three.append(Bar(
        x=genre_names,
        y=genre_counts,
    ), )

    layout_three = dict(title='Distribution of Message Genres',
                        yaxis=dict(title="Count"),
                        xaxis=dict(title="Genre"))

    figures.append(dict(data=graph_three, layout=layout_three))

    # visualize category correlation heat map
    graph_four = []
    data_corr = df.iloc[:, 4:]
    corr_list = []
    correl_val = data_corr.corr().values
    for row in correl_val:
        corr_list.append(list(row))

    graph_four.append(
        Heatmap(z=corr_list,
                x=data_corr.columns,
                y=data_corr.columns,
                colorscale='Viridis'))

    layout_four = dict(title='Correlation map of the categories',
                       height=900,
                       margin=dict(l=130, b=160))

    figures.append(dict(data=graph_four, layout=layout_four))

    # visualize most frequent word per category
    if os.path.isfile('data/df_pop_word.pkl'):
        graph_five = []
        pop_word = joblib.load('data/df_pop_word.pkl')
        most_used_words = pop_word['first_word'].unique()
        color_item = build_color_palette(most_used_words)
        colors = get_color_scale(color_item, pop_word['first_word'])

        graph_five.append(
            Bar(x=pop_word['category'],
                y=pop_word['first_word_count'],
                text=pop_word['first_word'],
                textposition='outside',
                textangle=-60,
                textfont={'size': 10},
                marker={'color': colors}))

        layout_five = dict(
            title='Most used word in all messages for each category',
            yaxis=dict(title="Count of messages"),
            xaxis=dict(tickangle=-45, title="Category"),
            height=900,
            margin=dict(l=130, b=140))

        figures.append(dict(data=graph_five, layout=layout_five))

    return figures
Example #23
0
def get_figure(hypothesis: Expr, gradient: MutableDenseMatrix, eta0: float,
               origin: np.ndarray, style: str, showlabels: bool,
               showgradient: bool, showcomponents: bool) -> Figure:

    # Function Lambdifying
    theta0, theta1 = symbols("theta0 theta1")
    f, grad = lambdify([theta0, theta1],
                       hypothesis), lambdify([theta0, theta1], gradient)

    # Parameter and Contour Generation
    x = y = np.arange(start=-12, stop=12, step=0.25)
    meshgrid: List[np.ndarray] = np.meshgrid(x, y)
    Z = f(meshgrid[0], meshgrid[1])
    point: np.ndarray = origin - eta0 * grad(origin[0], origin[1]).reshape(
        origin.shape)

    # Figure Meta Data
    markercolor = labelcolor = arrowcolor = "white" if style == "fill" else "black"

    # Figure Generation
    fig: Figure = Figure()
    fig.add_trace(
        Contour(x=x,
                y=y,
                z=Z,
                showscale=False,
                autocontour=False,
                contours={
                    "showlabels": showlabels,
                    "labelfont": {
                        "color": labelcolor
                    },
                    "start": 0,
                    "end": np.max(Z),
                    "size": 20,
                    "coloring": style
                }))
    fig.add_trace(
        Scatter(x=[*origin[0:1]],
                y=[*origin[1:2]],
                mode="markers",
                marker=dict(symbol="x", color=markercolor, size=10)))
    if showgradient:
        fig.add_trace(
            Scatter(x=[*point[0:1]],
                    y=[*point[1:2]],
                    mode="markers",
                    marker=dict(symbol="x", color=markercolor, size=10)))
        fig.add_annotation(ax=origin[0],
                           ay=origin[1],
                           x=point[0],
                           y=point[1],
                           xref="x",
                           yref="y",
                           axref="x",
                           ayref="y",
                           showarrow=True,
                           arrowhead=4,
                           arrowsize=1.5,
                           arrowwidth=2,
                           arrowcolor=arrowcolor)
    if showcomponents:
        fig.add_annotation(ax=origin[0],
                           ay=origin[1] - 0.5,
                           x=origin[0],
                           y=point[1],
                           xref="x",
                           yref="y",
                           axref="x",
                           ayref="y",
                           showarrow=True,
                           arrowhead=4,
                           arrowsize=1.5,
                           arrowwidth=2,
                           arrowcolor=arrowcolor,
                           opacity=0.5)
        fig.add_annotation(ax=origin[0],
                           ay=origin[1],
                           x=point[0],
                           y=origin[1],
                           xref="x",
                           yref="y",
                           axref="x",
                           ayref="y",
                           showarrow=True,
                           arrowhead=4,
                           arrowsize=1.5,
                           arrowwidth=2,
                           arrowcolor=arrowcolor,
                           opacity=0.5)
    fig.update_layout(showlegend=False, margin=dict(l=0, r=0, t=0, b=0))
    fig.update_xaxes(title="Parameter 0")
    fig.update_yaxes(title="Parameter 1")

    return fig
    def _get_plotly_figure(self) -> Figure:
        """Returns a Plotly figure of reaction kinks diagram"""
        kinks = map(list, zip(*self.get_kinks()))
        _, x, energy, reactions, _ = kinks

        lines = Scatter(
            x=x,
            y=energy,
            mode="lines",
            name="Lines",
            line=dict(color="navy", dash="solid", width=5.0),
            hoverinfo="none",
        )

        annotations = self._get_plotly_annotations(x, energy,
                                                   reactions)  # type: ignore

        min_idx = energy.index(min(energy))  # type: ignore

        x_min = x.pop(min_idx)
        e_min = energy.pop(min_idx)
        rxn_min = reactions.pop(min_idx)

        labels = [
            rf"{htmlify(str(r))} <br>" + "\u0394" +
            f"E<sub>rxn</sub> = {round(e, 3)} eV/atom"  # type: ignore
            for r, e in zip(reactions, energy)
        ]

        markers = Scatter(
            x=x,
            y=energy,
            mode="markers",
            name="Reactions",
            hoverinfo="text",
            hovertext=labels,
            marker=dict(
                color="black",
                size=12,
                opacity=0.8,
                line=dict(color="black", width=3),
            ),
            hoverlabel=dict(bgcolor="navy"),
        )

        min_label = (
            rf"{htmlify(str(rxn_min))} <br>" + "\u0394" +
            f"E<sub>rxn</sub> = {round(e_min, 3)} eV/atom"  # type: ignore
        )

        minimum = Scatter(
            x=[x_min],
            y=[e_min],
            mode="markers",
            hoverinfo="text",
            hovertext=[min_label],
            marker=dict(color="darkred", size=24, symbol="star"),
            name="Suggested reaction",
        )

        data = [lines, markers, minimum]

        layout = plotly_layouts["default_interface_rxn_layout"]
        layout["xaxis"]["title"] = self._get_xaxis_title(latex=False)
        layout["annotations"] = annotations

        fig = Figure(data=data, layout=layout)
        return fig
Example #25
0
    def update_figure(time_value, y_column_name, x_column_name, json_data,
                      marks, mdata):
        """This callback handles updating the graph in response to user
        actions."""
        # Prevents updates without data
        if None in [json_data, x_column_name, y_column_name, mdata]:
            raise PreventUpdate(
                "Graph could not load data -- either this is at startup, or the Storage component isn't storing the data"
            )

        if time_value == None:
            time_value = int(mdata.get("time_min"))

        # Loads dataframe at specific time value by getting the time as a key from a dictionary,
        # then evaluates it to turn it into a python dictionary, and then loads it as a dataframe
        try:
            df_by_time = pd.DataFrame.from_dict(
                literal_eval(json.loads(json_data).get(str(time_value))))
        except ValueError:
            pass

        server.logger.debug("✅ dataframe filtered by time")

        x_range = list(mdata.get("ranges").get(x_column_name))
        y_range = list(mdata.get("ranges").get(y_column_name))

        server.logger.debug("✅ X and Y axis ranges created")

        scatterplot = Scatter(
            x=df_by_time[x_column_name],
            y=df_by_time[y_column_name],
            mode="markers",
            opacity=0.7,
            marker={
                "size": 15,
                "line": {
                    "width": 0.5,
                    "color": "white"
                }
            },
            hovertext=df_by_time["Subject"],
        )

        traces_data = list()
        traces_data.append(scatterplot)

        server.logger.debug("✅ Bubble Chart Scatterplot appended for graphing")

        figure = {
            "data":
            traces_data,
            "layout":
            dict(
                xaxis={
                    "title": " ".join(x_column_name.split("_")).title(),
                    "range": x_range,
                },
                yaxis={
                    "title": " ".join(y_column_name.split("_")).title(),
                    "range": y_range,
                },
                margin={
                    "l": 40,
                    "b": 40,
                    "t": 10,
                    "r": 10
                },
                legend={
                    "x": 0,
                    "y": 1
                },
                hovermode="closest",
                # Defines transition behaviors
                transition={
                    "duration": 500,
                    "easing": "cubic-in-out"
                },
            ),
        }

        server.logger.debug("✅ Bubble Chart figure created")

        return figure
Example #26
0
    def update_line_chart(ticker, degree):
        good_data = results[ticker]
        try:
            good_data['time'] = good_data.index
            start = good_data['time'][0]
            time = np.array([
                pd.Timedelta(x - start).total_seconds()
                for x in good_data['time']
            ])
            fig1 = px.scatter(good_data,
                              x='time',
                              y='Open',
                              template='simple_white',
                              title='Time Series')
            fig1.update_traces(marker={'size': 4})
            bt = Backtest(results[ticker],
                          SmaCross,
                          cash=10_000,
                          commission=.002)
            stats = bt.optimize(n1=range(5, 50, 5),
                                n2=range(10, 200, 5),
                                maximize='Equity Final [$]',
                                constraint=lambda param: param.n1 < param.n2)
            eq_curve = stats._equity_curve
            eq_curve['time'] = eq_curve.index
            fig5 = px.line(eq_curve,
                           x='time',
                           y='Equity',
                           template='simple_white')
            smac = str(stats._strategy)
            fig1.add_trace(
                Scatter(x=good_data['time'],
                        y=SMA(good_data['Open'], stats._strategy.n1),
                        name='Short MA'))
            fig1.add_trace(
                Scatter(x=good_data['time'],
                        y=SMA(good_data['Open'], stats._strategy.n2),
                        name='Long MA'))

            print(
                np.nan_to_num(
                    np.array(SMA(good_data['Open'], stats._strategy.n1))))
            coefs = np.polyfit(
                time,
                np.nan_to_num(
                    np.array(SMA(good_data['Open'], stats._strategy.n1))),
                degree)
            print(coefs)
            print(np.polyval(time, coefs))
            coef_df = pd.DataFrame.from_dict({
                'time': time,
                'coeffs': np.polyval(coefs, time),
                'original_t': good_data['time']
            })
            fig2 = px.line(coef_df,
                           x='original_t',
                           y='coeffs',
                           template='simple_white',
                           title='Polynomial Fit')
            der1 = np.polyder(coefs, 1)
            print('der1: ', der1)
            der1_df = pd.DataFrame.from_dict({
                'time': time,
                'der1': np.polyval(der1, time),
                'original_t': good_data['time']
            })
            fig3 = px.line(der1_df,
                           x='original_t',
                           y='der1',
                           template='simple_white',
                           title='First Derivative')
            der2 = np.polyder(coefs, 2)
            print('der2: ', der2)
            der2_df = pd.DataFrame.from_dict({
                'time': time,
                'der2': np.polyval(der2, time),
                'original_t': good_data['time']
            })
            fig4 = px.line(der2_df,
                           x='original_t',
                           y='der2',
                           template='simple_white',
                           title='Second Derivative')

            coefs = np.polyfit(time, np.array(good_data['Open']), degree)
            print('coefs: ', coefs)
            coef_df = pd.DataFrame.from_dict({
                'time': time,
                'coeffs': np.polyval(coefs, time),
                'original_t': good_data['time']
            })
        except exceptions.YahooFinanceError:
            fig1, fig2, fig3, fig4, fig5 = 'No Ticker Available'
        return fig1, fig2, fig3, fig4, fig5, coefs, smac
Example #27
0
filepath = "twstockyear2018.csv"
if os.path.isfile(filepath):
    title = ["日期", "成交股數", "成交金額", "開盤價", "最高價", "最低價", "收盤價", "漲跌價差", "成交筆數"]
    outputfile = open(filepath, "a", newline="", encoding="big5")
    outputwriter = csv.writer(outputfile)
    for i in range(12, 13):
        stock = twstock.Stock("2317")
        stocklist = stock.fetch(2018, i)
        data = []
        for stock in stocklist:
            strdate = stock.date.strftime("%Y-%m-%d")
            li = [
                strdate, stock.capacity, stock.turnover, stock.open,
                stock.high, stock.low, stock.close, stock.change,
                stock.transaction
            ]
            data.append(li)
        """if i==1:
            outputwriter.writerow(title) """
        for dataline in (data):
            outputwriter.writerow(dataline)
        time.sleep(1)
    outputfile.close()
pdstock = pd.read_csv(filepath, encoding="big5")
pdstock["日期"] = pd.to_datetime(pdstock["日期"])
data1 = [
    Scatter(x=pdstock["日期"], y=["收盤價"], name="收盤價"),
    Scatter(x=pdstock["日期"], y=["最低價"], name="最低價"),
    Scatter(x=pdstock["日期"], y=["最高價"], name="最高價")
]
plot({"data": data1, "layout": Layout(title="2018年個股統計圖")}, auto_open=True)
Example #28
0
    def update_line_plots(left_value, right_value, json_data, mdata):
        """Generates line plots from given data values

        Args:
            y_value (str):y dropdown column name
            x_value (str): x dropdown column name
            json_data (dict): loaded json data from redis
            mdata (dict): extracted metadata from redis
        """
        if None in [left_value, right_value, json_data, mdata]:
            raise PreventUpdate

        # Generates ranges for x and y dropdowns dependent values
        x_range = list(mdata.get("ranges").get(right_value))
        y_range = list(mdata.get("ranges").get(left_value))

        # Left and right scatterplot lists
        left_traces, right_traces = list(), list()

        # Populates lists of scatterplots by iterating over id
        for subject in literal_eval(json_data).keys():
            df = pd.DataFrame.from_dict(
                literal_eval(json.loads(json_data).get(str(subject))))
            left_traces.append(
                Scatter(x=df["X"],
                        y=df[left_value],
                        mode="lines",
                        name=f"Subject: {subject}"))
            right_traces.append(
                Scatter(x=df["X"],
                        y=df[right_value],
                        mode="lines",
                        name=f"Subject: {subject}"))
        # Generates title from column names
        dependentTitle = lambda value: " ".join(value.split("_")).title()
        return [
            {
                "data":
                left_traces,
                "layout":
                dict(
                    xaxis={
                        "title": "Time",
                        "autorange": "true"
                    },
                    yaxis={
                        "title": dependentTitle(left_value),
                        "autorange": "true",
                    },
                    title={
                        "text": f"{dependentTitle(left_value)} vs Time",
                        "y": 0.9,
                        "x": 0.5,
                        "xanchor": "center",
                        "yanchor": "top",
                    },
                    margin={
                        "l": 40,
                        "b": 40,
                        "t": 10,
                        "r": 10
                    },
                    legend={
                        "x": 0,
                        "y": 1
                    },
                    hovermode="closest",
                    # Defines transition behaviors
                    transition={
                        "duration": 500,
                        "easing": "cubic-in-out"
                    },
                ),
            },
            {
                "data":
                right_traces,
                "layout":
                dict(
                    xaxis={
                        "title": "Time",
                        "autorange": "true",
                    },
                    yaxis={
                        "title": dependentTitle(right_value),
                        "autorange": "true",
                    },
                    title={
                        "text": f"{dependentTitle(right_value)} vs Time",
                        "y": 0.9,
                        "x": 0.5,
                        "xanchor": "center",
                        "yanchor": "top",
                    },
                    margin={
                        "l": 40,
                        "b": 40,
                        "t": 10,
                        "r": 10
                    },
                    legend={
                        "x": 0,
                        "y": 1
                    },
                    hovermode="closest",
                    # Defines transition behaviors
                    transition={
                        "duration": 500,
                        "easing": "cubic-in-out"
                    },
                ),
            },
        ]
    word_cloud = WordCloud().generate_from_frequencies(
        frequencies=to_show, max_font_size=max_font_size)

    output_file_root = './output/demo_wordcloud.'
    colormap = cm.get_cmap(plotly_colormap)
    max_size = max(item[1] for item in word_cloud.layout_)
    min_size = min(item[1] for item in word_cloud.layout_)

    figure = Figure(
        Scatter(mode='text',
                text=[item[0][0] for item in word_cloud.layout_],
                x=[item[2][0] for item in word_cloud.layout_],
                y=[item[2][1] for item in word_cloud.layout_],
                textfont=dict(
                    color=[
                        float_color_to_hex(
                            int((item[1] - min_size) * 255 / max_size),
                            colormap) for item in word_cloud.layout_
                    ],
                    size=[item[1] for item in word_cloud.layout_],
                )))

    app.layout = html.Div([
        dcc.Graph(
            id='basic-interactions',
            figure=figure,
        ),
        html.Div(dcc.Input(id='input-box', type='text')),
        html.Button('Submit', id='button'),
        html.Div(id='output-container-button',
                 children='Enter a value and press submit'),
Example #30
0
    def display_eps(player_gw_eps: DF) -> Widget:
        data = (player_gw_eps
                .reset_index()
                .sort_values(['Season', 'Game Week']))

        data_formatted = data.pipe(ctx.dd.format)
        data = (data.assign(**{'Label': 'FDR: ' + data_formatted['Fixture Short Name FDR'] + ', '
                                        + 'Rel. Strength: ' + data_formatted['Rel Strength'] + ', '
                                        + 'Cost: ' + data_formatted['Fixture Cost']})
                .assign(**{'Game Week': lambda df: 'GW ' + df['Game Week'].apply('{:.0f}'.format)})
                .assign(**{'Season Game Week': lambda df: df['Season'] + ', GW ' + df['Game Week']}))

        x_axis = [data['Season'], data['Game Week']]

        eps_trace = Scatter(x=x_axis,
                            y=data['Expected Points'],
                            name='Expected Points',
                            line=dict(color='rgb(255, 127, 14)'),
                            mode='lines')

        ftp_trace = Scatter(x=x_axis,
                            y=data['Fixture Total Points'],
                            name='Actual Points',
                            line=dict(color='rgba(44, 160, 44, 0.3)'),
                            mode='lines')

        ftpr_trace = Scatter(x=x_axis,
                             y=data['Rolling Avg Game Points'],
                             name='Rolling Actual Points',
                             line=dict(color='rgb(44, 160, 44)'),
                             line_shape='spline',
                             mode='lines')

        fs_trace = Scatter(x=x_axis,
                           y=data['Expected Points'],
                           name='Rel. Strength',
                           mode='markers',
                           marker=dict(color=(data['Team FDR'].fillna(3)), colorscale=FDR_COLOR_SCALE),
                           text=data['Label'])

        last_gw = [ctx.current_season, f'GW {ctx.next_gw - 1}']
        first_gw = [ctx.current_season, 'GW 1']
        last_season_gws_color = 'rgb(230, 230, 230)'
        past_gws_color = 'rgb(240, 240, 240)'

        last_season_shape = Shape(type='rect', yref='paper', x0=-6, x1=first_gw, y0=0, y1=1, fillcolor=last_season_gws_color, layer='below', line_width=0, opacity=0.5)
        past_shape = Shape(type='rect', yref='paper', x0=first_gw, x1=last_gw, y0=0, y1=1, fillcolor=past_gws_color, layer='below', line_width=0, opacity=0.5)
        start_shape = Shape(type='line', yref='paper', x0=first_gw, x1=first_gw, y0=0, y1=1, line=dict(width=2, color='DarkGrey'), layer='below')
        current_gw_shape = Shape(type='line', yref='paper', x0=last_gw, x1=last_gw, y0=0, y1=1, line=dict(width=2, color='DarkGrey'), layer='below')

        max_points = max(max(data['Expected Points'].max(), data['Fixture Total Points'].max()) + 1, 15)
        min_points = min(data['Expected Points'].min(), data['Fixture Total Points'].min()) - 1

        layout = dict(
            yaxis=dict(title=f'Points', showspikes=True, range=[min_points, max_points]),
            xaxis=dict(tickfont=dict(size=8)),
            shapes=[last_season_shape, start_shape, past_shape, current_gw_shape],
            hovermode='closest',
            legend=dict(yanchor='top', xanchor='left', x=0, y=1, bgcolor='rgba(0,0,0,0)'),
            height=300,
            margin=dict(l=20, r=0, t=5, b=20, pad=0),
            annotations=[
                dict(x=last_gw, y=0.9, yref='paper', text='Last Game Week', ax=80, ay=0),
                dict(x=first_gw, y=0.9, yref='paper', text='Start of Season', ax=-80, ay=0)
            ]
        )
        return VBox([HTML('<h3>Expected Points vs Actual Points</h3>'),
                     FigureWidget([ftp_trace, ftpr_trace, eps_trace, fs_trace], layout=layout)])