def slack_stock_price(msg: CommandMessage, config: Dict): if len(msg.text) > 1: try: response = BarchartClient(config.get('api_key', '')) \ .get_history(msg.text.upper()) except: # API request error # Already logged in BarchartClient, so just return error message. return "Something went wrong with %s" % msg.text else: try: open_prices = [] high_prices = [] low_prices = [] close_prices = [] dates = [] volumes = [] for result in response['results']: open_prices.append(result['open']) high_prices.append(result['high']) low_prices.append(result['low']) close_prices.append(result['close']) dates.append(result['tradingDay']) volumes.append(result['volume']) candle_graph_url = plotly.plot( FigureFactory.create_candlestick(open_prices, high_prices, low_prices, close_prices, dates=dates), filename="barchart/price_" + dates[-1], vadlidate=False) volume_graph_url = plotly.plot( Data([Scatter(x=dates, y=volumes)])) attachments = [ MessageAttachment(fallback="stock price history", title="stock price history", title_link=candle_graph_url, image_url=candle_graph_url + ".png"), MessageAttachment(fallback="volume history", title="volume history", title_link=volume_graph_url, image_url=volume_graph_url + ".png")] return SlackMessage( text="Stock price history for %s" % msg.text, attachments=attachments) except Exception as e: # Response handling error logging.error(e) return "Something went wrong with %s" % msg.text else: return "Please enter ticker symbol."
def test_plot_sharing_invalid_argument(self): # Raise an error if sharing argument is incorrect # correct arguments {'public, 'private', 'secret'} kwargs = {'filename': 'invalid-sharing-argument', 'sharing': 'privste'} with self.assertRaisesRegexp(PlotlyError, 'sharing'): py.plot(self.simple_figure, **kwargs)
def test_plot_valid(self): fig = { 'data': [ { 'x': [1, 2, 3], 'y': [2, 1, 2] } ] } py.plot(fig, auto_open=False, filename='plot_valid')
def test_plot_valid(): fig = { 'data': [ { 'x': [1, 2, 3], 'y': [2, 1, 2] } ] } py.plot(fig, auto_open=False, filename='plot_valid')
def test_plot_world_readable_sharing_conflict_1(self): # Raise an error if world_readable=False but sharing='public' kwargs = {'filename': 'invalid-privacy-setting', 'world_readable': False, 'sharing': 'public'} with self.assertRaisesRegexp(PlotlyError, 'sharing'): py.plot(self.simple_figure, **kwargs)
def test_plot_invalid(self): fig = { 'data': [ { 'x': [1, 2, 3], 'y': [2, 1, 2], 'z': [3, 4, 1] } ] } py.plot(fig, auto_open=False, filename='plot_invalid')
def test_plot_invalid(self): fig = { 'data': [ { 'x': [1, 2, 3], 'y': [2, 1, 2], 'z': [3, 4, 1] } ] } with self.assertRaises(ValueError): py.plot(fig, auto_open=False, filename='plot_invalid')
def test_plot_world_readable_sharing_conflict_2(self): # Raise an error if world_readable=True but sharing='secret' kwargs = {'filename': 'invalid-privacy-setting', 'world_readable': True, 'sharing': 'secret'} with self.assertRaisesRegexp( PlotlyError, 'setting your plot privacy to both public and private.'): py.plot(self.simple_figure, **kwargs)
def test_plot_world_readable_sharing_conflict_1(self): # Raise an error if world_readable=False but sharing='public' kwargs = { 'filename': 'invalid-privacy-setting', 'world_readable': False, 'sharing': 'public' } with self.assertRaisesRegexp(PlotlyError, 'sharing'): py.plot(self.simple_figure, **kwargs)
def test_plot_invalid(): fig = { 'data':[ { 'x':[1,2,3], 'y':[2,1,2], 'z':[3,4,1] } ] } url = py.plot(fig, auto_open=False, filename='plot_invalid')
def test_plot_valid(): py.sign_in('PlotlyImageTest', '786r5mecv0') fig = { 'data':[ { 'x':[1,2,3], 'y':[2,1,2] } ] } url = py.plot(fig, auto_open=False, filename='plot_valid')
def test_plot_url_response_given_sharing_key(self): # Given share_key is requested, get request of the url should # be 200 kwargs = {'filename': 'is_share_key_included', 'fileopt': 'overwrite', 'auto_open': False, 'world_readable': False, 'sharing': 'secret'} plot_url = py.plot(self.simple_figure, **kwargs) response = requests.get(plot_url) self.assertEqual(response.status_code, 200)
def test_plot_valid(self): fig = { 'data': [ { 'x': (1, 2, 3), 'y': (2, 1, 2) } ], 'layout': {'title': 'simple'} } url = py.plot(fig, auto_open=False, filename='plot_valid') saved_fig = py.get_figure(url) self.assertEqual(saved_fig['data'][0]['x'], fig['data'][0]['x']) self.assertEqual(saved_fig['data'][0]['y'], fig['data'][0]['y']) self.assertEqual(saved_fig['layout']['title'], fig['layout']['title'])
def test_plot_url_response_given_sharing_key(self): # Given share_key is requested, get request of the url should # be 200 kwargs = { 'filename': 'is_share_key_included', 'fileopt': 'overwrite', 'auto_open': False, 'world_readable': False, 'sharing': 'secret' } plot_url = py.plot(self.simple_figure, **kwargs) response = requests.get(plot_url) self.assertEqual(response.status_code, 200)
def test_plot_url_response_given_sharing_key(self): # Given share_key is requested, get request of the url should # be 200 kwargs = {'filename': 'is_share_key_included', 'fileopt': 'overwrite', 'auto_open': False, 'world_readable': False, 'sharing': 'secret'} plot_url = py.plot(self.simple_figure, **kwargs) # shareplot basically always gives a 200 if even if permission denied # embedplot returns an actual 404 embed_url = plot_url.split('?')[0] + '.embed?' + plot_url.split('?')[1] response = requests.get(embed_url) self.assertEqual(response.status_code, 200)
def _handle_msg(self, message): """Handle a msg from the front-end. Args: content (dict): Content of the msg. """ content = message['content']['data']['content'] if content.get('event', '') == 'pong': self._graphId = content['graphId'] # ready to recieve - pop out all of the items in the deque while self._clientMessages: _message = self._clientMessages.popleft() _message['graphId'] = self._graphId _message = _json.dumps(_message) self._message = _message if content.get('event', '') in ['click', 'hover', 'zoom']: # De-nest the message if content['event'] == 'click' or content['event'] == 'hover': message = content['message']['points'] elif content['event'] == 'zoom': message = content['message']['ranges'] self._event_handlers[content['event']](self, message) if content.get('event', '') == 'getAttributes': self._attributes = content.get('response', {}) # there might be a save pending, use the plotly module to save if self._flags['save_pending']: self._flags['save_pending'] = False url = py.plot(self._attributes, auto_open=False, filename=self._filename, validate=False) self._new_url = url self._fade_to('slow', 1)
def _handle_msg(self, message): """Handle a msg from the front-end. Args: content (dict): Content of the msg. """ content = message['content']['data']['content'] if content.get('event', '') == 'pong': self._graphId = content['graphId'] # ready to recieve - pop out all of the items in the deque while self._clientMessages: _message = self._clientMessages.popleft() _message['graphId'] = self._graphId _message = json.dumps(_message) self._message = _message if content.get('event', '') in ['click', 'hover', 'zoom']: # De-nest the message if content['event'] == 'click' or content['event'] == 'hover': message = content['message']['points'] elif content['event'] == 'zoom': message = content['message']['ranges'] self._event_handlers[content['event']](self, message) if content.get('event', '') == 'getAttributes': self._attributes = content.get('response', {}) # there might be a save pending, use the plotly module to save if self._flags['save_pending']: self._flags['save_pending'] = False url = py.plot(self._attributes, auto_open=False, filename=self._filename, validate=False) self._new_url = url self._fade_to('slow', 1)
def test_plot_invalid_args_1(): url = py.plot(x=[1,2,3], y=[2,1,2], auto_open=False, filename='plot_invalid')
def test_plot_invalid_args_2(self): py.plot([1, 2, 3], [2, 1, 2], auto_open=False, filename='plot_invalid')
def test_plot_empty_data(self): py.sign_in('PlotlyImageTest', '786r5mecv0') with self.assertRaises(PlotlyEmptyDataError): py.plot([], filename='plot_invalid')
def plot_predictions(predictions, summary_words_vectors, movie_names, movie_genres): X = np.array(summary_words_vectors) X_embedded = TSNE(n_components=3).fit_transform(X) colors = [] x = [] y = [] z = [] text = [] for i in range(len(X_embedded)): x.append(X_embedded[i][0]) y.append(X_embedded[i][1]) z.append(X_embedded[i][2]) text.append(movie_names[i] + " " + str(movie_genres[i])) plotly.tools.set_credentials_file(username='******', api_key='CpYDoCrtBF2T8k04VaRf') data = [] groups_count = 3 colors = ['rgb(0,0,255)', 'rgb(0,255,0)', 'rgb(255,0,0)'] '''colors = [] for i in range(groups_count): color_red = random.randint(0, 255) color_green = random.randint(0, 255) color_blue = random.randint(0, 255) colors.append('rgb('+ str(color_red) + ',' + str(color_green) + ',' + str(color_blue) + ')')''' x_groups = [[] for i in range(groups_count)] y_groups = [[] for i in range(groups_count)] z_groups = [[] for i in range(groups_count)] text_groups = [[] for i in range(groups_count)] for i in range(len(X_embedded)): x_groups[predictions[i][0]].append(X_embedded[i][0]) y_groups[predictions[i][0]].append(X_embedded[i][1]) z_groups[predictions[i][0]].append(X_embedded[i][2]) text_groups[predictions[i][0]].append(movie_names[i] + " " + str(movie_genres[i])) for i in range(groups_count): data.append( go.Scatter3d(x=x_groups[i], y=y_groups[i], z=z_groups[i], mode='markers', text=text_groups[i], marker=dict(color=colors[i], size=12, symbol='circle', line=dict(color='rgb(204, 204, 204)', width=1), opacity=0.9))) #print(data) layout = go.Layout(margin=dict(l=0, r=0, b=0, t=0)) fig_comp = go.Figure(data=data, layout=layout) py.plot(fig_comp, filename='ssimple-3d-slcatter')
def test_plot_invalid_args_1(self): with self.assertRaises(TypeError): py.plot(x=[1, 2, 3], y=[2, 1, 2], auto_open=False, filename='plot_invalid')
def test_plot_invalid_args_2(): py.plot([1, 2, 3], [2, 1, 2], auto_open=False, filename='plot_invalid')
def test_plot_invalid_args_2(self): with self.assertRaises(ValueError): py.plot([1, 2, 3], [2, 1, 2], auto_open=False, filename='plot_invalid')