Пример #1
0
 def draw_map_image(self):
     df = pd.read_csv(
         'https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv'
     )
     fig = go.Figure(data=go.Choropleth(
         locations=df['CODE'],
         z=self.df['cluster'],
         text=self.df['country'],
         colorscale='Blues',
         autocolorscale=False,
         reversescale=True,
         marker_line_color='darkgray',
         marker_line_width=0.5,
         colorbar_title='Cluster Group',
     ))
     fig.update_layout(title_text='K Means Clustering Visualization',
                       geo=dict(showframe=True,
                                showcoastlines=False,
                                projection_type='equirectangular'),
                       annotations=[
                           dict(x=0.55,
                                y=0.1,
                                xref='paper',
                                yref='paper',
                                showarrow=False)
                       ])
     py.sign_in("shirbendor", "ByDLoTeQOewal6U26ATM")
     py.image.save_as(fig, filename="./map.png")
Пример #2
0
def init_plotly_stream():
    # init credentials
    with open('./credentials.json') as credentials_file:
        plotly_user_config = json.load(credentials_file)

    # authenticate with provided credentials
    plot.sign_in(plotly_user_config["plotly_username"],
                 plotly_user_config["plotly_api_key"])

    # configure the plot
    url = plot.plot([{
        'x': [],
        'y': [],
        'type': 'scatter',
        'mode': 'lines+markers',
        'stream': {
            'token': plotly_user_config['plotly_streaming_tokens'][0],
            'maxpoints': 200
        },
    }],
                    filename='MS-Temperature')

    print("View your streaming graph here: ", url)

    # attach a stream to the plot
    stream = plot.Stream(plotly_user_config['plotly_streaming_tokens'][0])

    return stream
Пример #3
0
    def test_stream_unstreamable(self):

        # even though `name` isn't streamable, we don't validate it --> pass

        py.sign_in(un, ak)
        my_stream = py.Stream(tk)
        my_stream.open()
        my_stream.write(Scatter(x=[1], y=[10], name="nope"))
        my_stream.close()
Пример #4
0
 def test_initialize_stream_plot(self):
     py.sign_in(un, ak)
     stream = Stream(token=tk, maxpoints=50)
     url = py.plot([Scatter(x=[], y=[], mode='markers', stream=stream)],
                   auto_open=False,
                   world_readable=True,
                   filename='stream-test')
     assert url == 'https://plot.ly/~PythonAPI/461'
     time.sleep(.5)
Пример #5
0
 def test_sign_in(self):
     un = 'anyone'
     ak = 'something'
     # TODO, add this!
     # si = ['this', 'and-this']
     py.sign_in(un, ak)
     creds = py.get_credentials()
     self.assertEqual(creds['username'], un)
     self.assertEqual(creds['api_key'], ak)
Пример #6
0
 def test_initialize_stream_plot(self):
     py.sign_in(un, ak)
     stream = Stream(token=tk, maxpoints=50)
     url = py.plot([Scatter(x=[], y=[], mode='markers', stream=stream)],
                   auto_open=False,
                   world_readable=True,
                   filename='stream-test')
     assert url == 'https://plot.ly/~PythonAPI/461'
     time.sleep(.5)
Пример #7
0
    def test_stream_unstreamable(self):

        # even though `name` isn't streamable, we don't validate it --> pass

        py.sign_in(un, ak)
        my_stream = py.Stream(tk)
        my_stream.open()
        my_stream.write(Scatter(x=[1], y=[10], name='nope'))
        my_stream.close()
Пример #8
0
 def test_sign_in(self):
     un = 'anyone'
     ak = 'something'
     # TODO, add this!
     # si = ['this', 'and-this']
     py.sign_in(un, ak)
     creds = py.get_credentials()
     self.assertEqual(creds['username'], un)
     self.assertEqual(creds['api_key'], ak)
Пример #9
0
 def test_sign_in(self):
     un = "anyone"
     ak = "something"
     # TODO, add this!
     # si = ['this', 'and-this']
     py.sign_in(un, ak)
     creds = py.get_credentials()
     self.assertEqual(creds["username"], un)
     self.assertEqual(creds["api_key"], ak)
Пример #10
0
def plot_graph(test_accuracy):
    py.sign_in('VikramShenoy', 'x1Un4yD3HDRT838vRkFA')
    training_accuracy = []
    history = np.load("history.npy", allow_pickle=True)
    training_loss = history.item().get('train_loss')
    train_accuracy = history.item().get('train_accuracy')
    epochs = list(range(1, len(training_loss) + 1))
    for i in range(0, len(train_accuracy)):
        training_accuracy.append(train_accuracy[i].item() / 100)
    testing_accuracy = 98.64  #test_accuracy
    trace0 = go.Scatter(x=epochs,
                        y=training_accuracy,
                        mode="lines",
                        name="Training Accuracy")

    trace1 = go.Scatter(x=epochs,
                        y=training_loss,
                        mode="lines",
                        name="Training Loss")
    data = go.Data([trace0, trace1])
    layout = go.Layout()
    fig = go.Figure(data=data, layout=layout)
    fig['layout']['xaxis'].update(title="Number of Epochs",
                                  range=[min(epochs), max(epochs)],
                                  dtick=len(epochs) / 10,
                                  showline=True,
                                  zeroline=True,
                                  mirror='ticks',
                                  linecolor='#636363',
                                  linewidth=2)
    fig['layout']['yaxis'].update(title="Training Loss and Accuracy",
                                  range=[0, 1.05],
                                  dtick=0.1,
                                  showline=True,
                                  zeroline=True,
                                  mirror='ticks',
                                  linecolor='#636363',
                                  linewidth=2)
    py.image.save_as(fig, filename="Training_Graph.png")

    print("Training Graph Created")

    x_axis = ["Training", "Testing"]
    y_axis = [training_accuracy[-1] * 100, testing_accuracy]
    trace2 = go.Bar(x=x_axis, y=y_axis, width=[0.3, 0.3])
    data = [trace2]
    layout = go.Layout()
    fig = go.Figure(data=data, layout=layout)
    fig['layout']['xaxis'].update(title="Mode", showline=True)
    fig['layout']['yaxis'].update(title="Accuracy")
    py.image.save_as(fig, filename="Accuracy_Graph.png")
    print("Accuracy Graph Created")

    return
Пример #11
0
 def test_initialize_stream_plot(self):
     py.sign_in(un, ak)
     stream = Stream(token=tk, maxpoints=50)
     url = py.plot(
         [Scatter(x=[], y=[], mode="markers", stream=stream)],
         auto_open=False,
         world_readable=True,
         filename="stream-test2",
     )
     self.assertTrue(url.startswith("https://plot.ly/~PythonAPI/"))
     time.sleep(0.5)
Пример #12
0
def gen_plotly_url():
    # Sign in to plotly if you haven't done so
    py.sign_in('<YOUR-USERNAME>', '<YOUR-PASSWORD>')  # Be careful with this, don't put it on Github!!!

    # Get current working directory
    cwd = os.getcwd()

    # Load config
    with open(cwd+"/config/config.yml", 'r') as f:
        config = yaml.load(f, Loader=yaml.FullLoader)

    # Load test file
    df = pd.read_csv(cwd+config['data_processed_path'], sep=",")

    # Load the predictions
    est_dict = {'date': [df[-1:]['date'].values[0]],
                'forecast': [df[-1:]['adj_close'].values[0]]}
    day = 1
    with open(cwd+'/out/est_' + str(date.today()) + '.csv') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        for row in csv_reader:
            est_dict['date'].append(str(date.today() + timedelta(days=day)))
            est_dict['forecast'].append(float(row[0]))
            day = day + 1
    est_df = pd.DataFrame(est_dict)

    # Plot with plotly
    miny = min(min(df[-63:]['adj_close']), min(est_df['forecast']))-1 # min y-value of the plot
    maxy = max(max(df[-63:]['adj_close']), max(est_df['forecast']))+1 # max y-value of the plot
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=df[-63:]['date'],
                             y=df[-63:]['adj_close'],
                             mode='lines',
                             name='actual',
                             line=dict(color='blue')))
    fig.add_trace(go.Scatter(x=est_df['date'],
                             y=est_df['forecast'],
                             mode='lines',
                             name='predictions',
                             line=dict(color='red')))
    fig.add_trace(go.Scatter(x=[str(date.today()), str(date.today())],
                             y=[miny, maxy],
                             mode='lines',
                             line=dict(color='black', dash="dot"),
                             showlegend=False))
    fig.update_layout(yaxis=dict(title='USD'),
                      xaxis=dict(title='date'))
    fig.update_yaxes(range=[miny, maxy])
    
    url=py.plot(fig, filename='est_'+str(date.today()), auto_open=False)
    
    return url
Пример #13
0
 def test_stream_multiple_points(self):
     py.sign_in(un, ak)
     stream = Stream(token=tk, maxpoints=50)
     url = py.plot([Scatter(x=[], y=[], mode='markers', stream=stream)],
                   auto_open=False,
                   world_readable=True,
                   filename='stream-test')
     time.sleep(.5)
     my_stream = py.Stream(tk)
     my_stream.open()
     my_stream.write(Scatter(x=[1, 2, 3, 4], y=[2, 1, 2, 5]))
     time.sleep(.5)
     my_stream.close()
Пример #14
0
 def test_stream_multiple_points(self):
     py.sign_in(un, ak)
     stream = Stream(token=tk, maxpoints=50)
     url = py.plot([Scatter(x=[], y=[], mode='markers', stream=stream)],
                   auto_open=False,
                   world_readable=True,
                   filename='stream-test')
     time.sleep(.5)
     my_stream = py.Stream(tk)
     my_stream.open()
     my_stream.write(Scatter(x=[1, 2, 3, 4], y=[2, 1, 2, 5]))
     time.sleep(.5)
     my_stream.close()
Пример #15
0
 def test_stream_single_points(self):
     py.sign_in(un, ak)
     stream = Stream(token=tk, maxpoints=50)
     res = py.plot(
         [Scatter(x=[], y=[], mode="markers", stream=stream)],
         auto_open=False,
         world_readable=True,
         filename="stream-test2",
     )
     time.sleep(0.5)
     my_stream = py.Stream(tk)
     my_stream.open()
     my_stream.write(Scatter(x=[1], y=[10]))
     time.sleep(0.5)
     my_stream.close()
Пример #16
0
 def test_sign_in_with_config(self):
     username = '******'
     api_key = 'place holder'
     plotly_domain = 'test domain'
     plotly_streaming_domain = 'test streaming domain'
     plotly_ssl_verification = False
     py.sign_in(username,
                api_key,
                plotly_domain=plotly_domain,
                plotly_streaming_domain=plotly_streaming_domain,
                plotly_ssl_verification=plotly_ssl_verification)
     config = py.get_config()
     self.assertEqual(config['plotly_domain'], plotly_domain)
     self.assertEqual(config['plotly_streaming_domain'],
                      plotly_streaming_domain)
     self.assertEqual(config['plotly_ssl_verification'],
                      plotly_ssl_verification)
Пример #17
0
 def test_stream_layout(self):
     py.sign_in(un, ak)
     stream = Stream(token=tk, maxpoints=50)
     url = py.plot([Scatter(x=[], y=[], mode='markers', stream=stream)],
                   auto_open=False,
                   world_readable=True,
                   filename='stream-test')
     time.sleep(.5)
     title_0 = "some title i picked first"
     title_1 = "this other title i picked second"
     my_stream = py.Stream(tk)
     my_stream.open()
     my_stream.write(Scatter(x=[1], y=[10]), layout=Layout(title=title_0))
     time.sleep(.5)
     my_stream.close()
     my_stream.open()
     my_stream.write(Scatter(x=[1], y=[10]), layout=Layout(title=title_1))
     my_stream.close()
Пример #18
0
 def test_stream_layout(self):
     py.sign_in(un, ak)
     stream = Stream(token=tk, maxpoints=50)
     url = py.plot([Scatter(x=[], y=[], mode='markers', stream=stream)],
                   auto_open=False,
                   world_readable=True,
                   filename='stream-test')
     time.sleep(.5)
     title_0 = "some title i picked first"
     title_1 = "this other title i picked second"
     my_stream = py.Stream(tk)
     my_stream.open()
     my_stream.write(Scatter(x=[1], y=[10]), layout=Layout(title=title_0))
     time.sleep(.5)
     my_stream.close()
     my_stream.open()
     my_stream.write(Scatter(x=[1], y=[10]), layout=Layout(title=title_1))
     my_stream.close()
Пример #19
0
    def test_stream_no_scheme(self):

        # If no scheme is used in the plotly_streaming_domain, port 80
        # should be used for streaming and ssl_enabled should be False

        py.sign_in(un, ak, **{'plotly_streaming_domain': 'stream.plot.ly'})
        my_stream = py.Stream(tk)
        expected_streaming_specs = {
            'server': 'stream.plot.ly',
            'port': 80,
            'ssl_enabled': False,
            'ssl_verification_enabled': False,
            'headers': {
                'Host': 'stream.plot.ly',
                'plotly-streamtoken': tk
            }
        }
        actual_streaming_specs = my_stream.get_streaming_specs()
        self.assertEqual(expected_streaming_specs, actual_streaming_specs)
Пример #20
0
    def test_stream_no_scheme(self):

        # If no scheme is used in the plotly_streaming_domain, port 80
        # should be used for streaming and ssl_enabled should be False

        py.sign_in(un, ak, **{"plotly_streaming_domain": "stream.plot.ly"})
        my_stream = py.Stream(tk)
        expected_streaming_specs = {
            "server": "stream.plot.ly",
            "port": 80,
            "ssl_enabled": False,
            "ssl_verification_enabled": False,
            "headers": {
                "Host": "stream.plot.ly",
                "plotly-streamtoken": tk
            },
        }
        actual_streaming_specs = my_stream.get_streaming_specs()
        self.assertEqual(expected_streaming_specs, actual_streaming_specs)
Пример #21
0
def plot_data_by_state():
    us_states = pd.read_csv("us_state_list.csv")
    us_state_list = us_states['Abbreviation']
    state_numbers = []
    for state in us_state_list:
        filters = {
            "state": [state],
            "site_year": {
                "min": 2014.0,
                "max": 2014.08333
            }
        }
        eui_dict = histogram(group_by=["electric_eui"], filters=filters)
        num_buildings = eui_dict['totals']['number_of_matching_buildings']
        state_numbers.append(num_buildings)

    us_states['Count'] = state_numbers

    data = [
        dict(type='choropleth',
             autocolorscale=False,
             locations=us_states['Abbreviation'],
             z=us_states['Count'].astype(float),
             locationmode='USA-states',
             marker=dict(line=dict(color='rgb(255,255,255)', width=2)),
             colorbar=dict(title="Millions USD"))
    ]

    layout = dict(
        title='Number of buildings in the BPD database by state',
        geo=dict(
            scope='usa',
            projection=dict(type='albers usa'),
            showlakes=True,
            lakecolor='rgb(255, 255, 255)',
        ),
    )

    fig = dict(data=data, layout=layout)

    py.sign_in('Anna8128', '46zTykSNwaQwgnc6LM7Y')

    py.plot(fig)
Пример #22
0
    def test_stream_no_scheme(self):

        # If no scheme is used in the plotly_streaming_domain, port 80
        # should be used for streaming and ssl_enabled should be False

        py.sign_in(un, ak, **{'plotly_streaming_domain': 'stream.plot.ly'})
        my_stream = py.Stream(tk)
        expected_streaming_specs = {
            'server': 'stream.plot.ly',
            'port': 80,
            'ssl_enabled': False,
            'ssl_verification_enabled': False,
            'headers': {
                'Host': 'stream.plot.ly',
                'plotly-streamtoken': tk
            }
        }
        actual_streaming_specs = my_stream.get_streaming_specs()
        self.assertEqual(expected_streaming_specs, actual_streaming_specs)
Пример #23
0
 def test_sign_in_with_config(self):
     username = "******"
     api_key = "place holder"
     plotly_domain = "test domain"
     plotly_streaming_domain = "test streaming domain"
     plotly_ssl_verification = False
     py.sign_in(
         username,
         api_key,
         plotly_domain=plotly_domain,
         plotly_streaming_domain=plotly_streaming_domain,
         plotly_ssl_verification=plotly_ssl_verification,
     )
     config = py.get_config()
     self.assertEqual(config["plotly_domain"], plotly_domain)
     self.assertEqual(config["plotly_streaming_domain"],
                      plotly_streaming_domain)
     self.assertEqual(config["plotly_ssl_verification"],
                      plotly_ssl_verification)
Пример #24
0
    def create_country_map(self):
        df_countries = pd.read_csv('country_codes_iso_3.csv')
        fig = go.Figure(data=go.Choropleth(
            locations=df_countries['code'],
            z=self.data_frame['k-means'],
            colorscale='rainbow',
            autocolorscale=False,
            reversescale=True,
            marker_line_color='darkgray',
            marker_line_width=0.5,
            colorbar_title='K-Means',
        ))

        fig.update_layout(title_text='K Means Clustering',
                          geo=dict(showframe=False,
                                   showcoastlines=False,
                                   projection_type='equirectangular'))

        py.sign_in('euguman', '3Zb8TzOCWAs0JmBmNERB')
        py.image.save_as(fig, filename='country_map.png')
Пример #25
0
    def get_graphs(self, k_means):
        """ Build scatter and choropleth graph from the predictions made by the KMeans model """

        # First graph prep
        fig, ax = plt.subplots()
        sc = ax.scatter(self.proc_data['Social support'].values,
                        self.proc_data['Generosity'].values,
                        c=k_means.labels_.astype(np.float),
                        edgecolor='k')
        fig.colorbar(sc, ax=ax)

        ax.set_xlabel('Social support', fontsize=12)
        ax.set_ylabel('Generosity', fontsize=12)
        fig.suptitle('K-Means clustering: Generosity - Social support',
                     fontsize=12,
                     fontweight='bold')
        dir_path = self.path[:self.path.rfind('/')]
        first_path = dir_path + '/Graph1.png'
        plt.savefig(first_path)
        plt.close(fig)

        # Second graph prep
        countries_data = pd.read_csv('countries_codes.csv')
        countries_dict = dict([
            (country, code)
            for country, code in zip(countries_data['Country'].to_numpy(),
                                     countries_data['Alpha-3code'].to_numpy())
        ])
        self.proc_data['country id'] = \
            [countries_dict[x] if x in countries_dict else x for x in self.proc_data['country'].values]

        choro_map = plex.choropleth(
            self.proc_data,
            locations="country id",
            color="cluster",
            color_continuous_scale=plex.colors.sequential.Aggrnyl,
            title='K-Means clustering by countries')
        pltly.sign_in('sfreiman', 'tQTEO9EOznyYp5HEu5Or')
        second_path = dir_path + '/Graph2.png'
        pltly.image.save_as(choro_map, filename=second_path)
        return first_path, second_path
Пример #26
0
    def __init__(self,
                 key='',
                 username='',
                 plotUrl='',
                 sharing=['public', 'private', 'secret'],
                 fileopt=['new', 'overwrite', 'extend', 'append']):
        ''' Constructor.

            fn (string) -- the name that will be associated with this figure
            fileopt ('new' | 'overwrite' | 'extend' | 'append') -- 'new' creates a
                'new': create a new, unique url for this plot
                'overwrite': overwrite the file associated with `filename` with this
                'extend': add additional numbers (data) to existing traces
                'append': add additional traces to existing data lists
            world_readable (default=True) -- make this figure private/public
            auto_open (default=True) -- Toggle browser options
                True: open this plot in a new browser tab
                False: do not open plot in the browser, but do return the unique url
            sharing ('public' | 'private' | 'sharing') -- Toggle who can view this graph
                - 'public': Anyone can view this graph. It will appear in your profile 
                    and can appear in search engines. You do not need to be 
                    logged in to Plotly to view this chart.
                - 'private': Only you can view this plot. It will not appear in the
                    Plotly feed, your profile, or search engines. You must be
                    logged in to Plotly to view this graph. You can privately
                    share this graph with other Plotly users in your online
                    Plotly account and they will need to be logged in to
                    view this plot.
                - 'secret': Anyone with this secret link can view this chart. It will
                    not appear in the Plotly feed, your profile, or search
                    engines. If it is embedded inside a webpage or an IPython
                    notebook, anybody who is viewing that page will be able to
                    view the graph. You do not need to be logged in to view
                    this plot.
        '''
        DomainBehavior.__init__(self)

        if key != '' and username != '':
            py.sign_in(username, key)
        self.plotUrl = ''
        self.state = {'status': 'IDLE', 'sigma': INFINITY}
Пример #27
0
 def draw_map(self):
     self.create_codes()
     fig = go.Figure(data=go.Choropleth(
         locations=self.dataset['CODE'],
         z=self.dataset['Cluster'],
         text=self.dataset['country'],
         colorscale='Blues',
         autocolorscale=False,
         reversescale=True,
         marker_line_color='darkgray',
         marker_line_width=0.5,
         colorbar_title='Countries Clusters',
     ))
     fig.update_layout(
         title_text='Countries Clusters',
         geo=dict(showframe=False,
                  showcoastlines=False,
                  projection_type='equirectangular'),
     )
     py.sign_in("nivgold", "CmHRBPCSQCYksweD8KNu")
     py.image.save_as(fig, filename='Countries Clusters.png')
Пример #28
0
 def test_sign_in_with_config(self):
     username = '******'
     api_key = 'place holder'
     plotly_domain = 'test domain'
     plotly_streaming_domain = 'test streaming domain'
     plotly_ssl_verification = False
     py.sign_in(
         username,
         api_key,
         plotly_domain=plotly_domain,
         plotly_streaming_domain=plotly_streaming_domain,
         plotly_ssl_verification=plotly_ssl_verification
     )
     config = py.get_config()
     self.assertEqual(config['plotly_domain'], plotly_domain)
     self.assertEqual(
         config['plotly_streaming_domain'], plotly_streaming_domain
     )
     self.assertEqual(
         config['plotly_ssl_verification'], plotly_ssl_verification
     )
Пример #29
0
    def cluster(self):
        if (self.wrongInput is True):
            mb.showerror("K Means Clustering", "wrong input")
        else:
            try:
                model = clustering.clustering.kmeans(self, self.df,
                                                     self.ClustersBox.get(),
                                                     self.runsBox.get())
                fig = plt.figure(figsize=(4, 4))
                plt.scatter(model['Social support'],
                            model['Generosity'],
                            c=model['clusters'],
                            cmap='jet')
                plt.title('Generosity as a function of social support')
                plt.xlabel('social support')
                plt.ylabel('generosity')
                canvas = FigureCanvasTkAgg(fig, master=root)
                canvas.draw()
                canvas.get_tk_widget().grid(row=6,
                                            column=1,
                                            ipadx=20,
                                            ipady=20)

                newDF = self.addCodeCountries(model)
                fig = px.choropleth(
                    newDF,
                    locations="CODE",
                    color="clusters",
                    hover_name="COUNTRY",
                    color_continuous_scale=px.colors.sequential.Plasma)

                py.sign_in('chenshor', 'vK4Ro730ZZHKIVCzFSBH')
                py.image.save_as(fig, filename='country.png')
                self.showImage()
                MsgBox = mb.askokcancel("K Means Clustering",
                                        "clustering completed successfully!")
            except ValueError:
                self.wrongInput = True
Пример #30
0
    def test_stream_https(self):

        # If the https scheme is used in the plotly_streaming_domain, port 443
        # should be used for streaming, ssl_enabled should be True,
        # and ssl_verification_enabled should equal plotly_ssl_verification

        ssl_stream_config = {
            'plotly_streaming_domain': 'https://stream.plot.ly',
            'plotly_ssl_verification': True
        }
        py.sign_in(un, ak, **ssl_stream_config)
        my_stream = py.Stream(tk)
        expected_streaming_specs = {
            'server': 'stream.plot.ly',
            'port': 443,
            'ssl_enabled': True,
            'ssl_verification_enabled': True,
            'headers': {
                'Host': 'stream.plot.ly',
                'plotly-streamtoken': tk
            }
        }
        actual_streaming_specs = my_stream.get_streaming_specs()
        self.assertEqual(expected_streaming_specs, actual_streaming_specs)
Пример #31
0
    def test_stream_https(self):

        # If the https scheme is used in the plotly_streaming_domain, port 443
        # should be used for streaming, ssl_enabled should be True,
        # and ssl_verification_enabled should equal plotly_ssl_verification

        ssl_stream_config = {
            'plotly_streaming_domain': 'https://stream.plot.ly',
            'plotly_ssl_verification': True
        }
        py.sign_in(un, ak, **ssl_stream_config)
        my_stream = py.Stream(tk)
        expected_streaming_specs = {
            'server': 'stream.plot.ly',
            'port': 443,
            'ssl_enabled': True,
            'ssl_verification_enabled': True,
            'headers': {
                'Host': 'stream.plot.ly',
                'plotly-streamtoken': tk
            }
        }
        actual_streaming_specs = my_stream.get_streaming_specs()
        self.assertEqual(expected_streaming_specs, actual_streaming_specs)
Пример #32
0
    def test_stream_https(self):

        # If the https scheme is used in the plotly_streaming_domain, port 443
        # should be used for streaming, ssl_enabled should be True,
        # and ssl_verification_enabled should equal plotly_ssl_verification

        ssl_stream_config = {
            "plotly_streaming_domain": "https://stream.plot.ly",
            "plotly_ssl_verification": True,
        }
        py.sign_in(un, ak, **ssl_stream_config)
        my_stream = py.Stream(tk)
        expected_streaming_specs = {
            "server": "stream.plot.ly",
            "port": 443,
            "ssl_enabled": True,
            "ssl_verification_enabled": True,
            "headers": {
                "Host": "stream.plot.ly",
                "plotly-streamtoken": tk
            },
        }
        actual_streaming_specs = my_stream.get_streaming_specs()
        self.assertEqual(expected_streaming_specs, actual_streaming_specs)
Пример #33
0
# import plotly.express as px
import pandas as pd
import chart_studio
import chart_studio.tools as tls
import plotly.graph_objs as go
import chart_studio.plotly as py
import os, sys
import matplotlib
import base64
from matplotlib import cm
import math
from matplotlib import pyplot as plt
import numpy as np
from matplotlib.patches import Circle, Wedge, Rectangle
# py.sign_in('nikhile' ,'OkrregXQ8kgWtuZEcuOI')
py.sign_in('aditya2019', 'O1AXV3C7JqJm5D2egggr')

# In[ ]:

# Establishing connection with MongoDB with specified database
app = Flask(__name__)
CORS(app)
app.config[
    'MONGO_URI'] = "mongodb+srv://headstrait_1:[email protected]/stockbazaar?retryWrites=true&w=majority"
mongo = PyMongo(app)
# Specifying the collection name
collection = mongo.db.stocks_data_2


# Plotting OHLC graph for indices
@app.route("/ohlcindices/<ticker_id>", methods=["GET"])
def plotly_setup():
    user = os.environ['plotly_user']
    key = os.environ['plotly_key']
    py.sign_in(username=user, api_key=key)
    set_config_file(plotly_domain="https://plotly.com",
                    plotly_api_domain="https://api.plotly.com")
Пример #35
0
import streamlit as st
import pandas as pd
import plotly.express as px
from datetime import date
from datetime import timedelta
import plotly
import chart_studio.plotly as py
import numpy as np
py.sign_in('nishtha697', 'RgHrQxWQq9hp2PQofsUg')
import plotly.graph_objs as go


@st.cache(ttl=60 * 5, max_entries=20)
def load_state_daily():
    state_daily = pd.read_csv(
        "https://api.covid19india.org/csv/latest/state_wise.csv")
    return state_daily


state_daily = load_state_daily()


@st.cache(ttl=60 * 5, max_entries=20)
def load_district_data():
    district_data = pd.read_csv(
        "https://api.covid19india.org/csv/latest/district_wise.csv")
    return district_data


district_data = load_district_data()
Пример #36
0
import chart_studio.plotly as py
#import plotly.graph_objs
from plotly.graph_objs import *
py.sign_in('Happy_Das', 'v3MozO2Qhlwcpd95upsf')

samples = [100, 500, 1000, 1500, 2000, 2500, 3000, 4000, 5000, 8000]
xi1_error = [
    0.0183079, 0.00288071, 0.00280302, 0.00082023, 0.00019435, 0.00061994,
    0.00011266, 0.00065684, 0.00033986, 0.00008628
]
xi2_error = [
    0.1892245, 0.12299614, 0.03353519, 0.04834064, 0.02900468, 0.02863002,
    0.04124718, 0.01890743, 0.01965981, 0.02786769
]


def visualize(sample, averagexi1, averagexi2):
    samp, avg_xi1, avg_xi2 = [], [], []
    for a, b, c in zip(sample, averagexi1, averagexi2):
        samp.append(a)
        avg_xi1.append(b)
        avg_xi2.append(c)

    data1 = {
        "x": samp,
        "y": avg_xi1,
        "name": "$\\hat\\xi_{1e}$ ",
        "type": "scatter"
    }
    data2 = {
        "x": samp,
Пример #37
0
import chart_studio.plotly as py
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from numpy.ma import var

py.sign_in("Muffles", "n7fnqiXZVX9eIO8YVhOq")

customer_list = []
useful_customer = []
fileName = None
unique_states = []
state_count = []
moneylist = []


def reset():
    customer_list.clear()
    useful_customer.clear()
    unique_states.clear()
    state_count.clear()
    moneylist.clear()


def get_map():
    df = pd.read_csv("State_List.csv")
    for col in df.columns:
        df[col] = df[col].astype(str)

    scl = [[0.0, 'rgb(255, 255, 255)'], [1.0, 'rgb(255, 0, 0)']]
Пример #38
0
 def setUp(self):
     super(MetaTest, self).setUp()
     py.sign_in('PythonTest', 'xnyU0DEwvAQQCwHVseIL')
                       mode='lines',
                       name=model_name))

    print(
        'Now plot--------------------------------------------------------------'
    )

# Edit the layout
layout = dict(
    title='Testing Accuracy across Models for various {0} Filtering'.format(
        name),
    xaxis=dict(title='Feature Count'),
    yaxis=dict(title='Testing Accuracy (%)'),
)

fig = dict(data=data_graph, layout=layout)
#use plotly online
py.sign_in('Avi-141', '0vBYQs5NNzyATMxW5m0P')
py.iplot(fig, filename='line-mode')

# done
#get report of 4k pages
#repeat the exp. with individual csv of serc labels
#. Mohit 150,

# done
#calculate gcs for new pages >> in progress
#calculate similarity score >>
#     input security group URLs
#        WIKI-SEED URL, C3 in progress
Пример #40
0
 def setUp(self):
     super(FolderAPITestCase, self).setUp()
     py.sign_in('PythonTest', 'xnyU0DEwvAQQCwHVseIL')
Пример #41
0
 def test_sign_in_cannot_validate(self):
     self.users_current_mock.side_effect = exceptions.PlotlyRequestError(
         'msg', 400, 'foobar'
     )
     with self.assertRaisesRegexp(_plotly_utils.exceptions.PlotlyError, 'Sign in failed'):
         py.sign_in('foo', 'bar')
Пример #42
0
 def setUp(self):
     super(TestStreaming, self).setUp()
     py.sign_in(un, ak, **config)