SlideShare ist ein Scribd-Unternehmen logo
1 von 31
Downloaden Sie, um offline zu lesen
APIs de Visualização em
Python
TDC 2014
Wilson Freitas
http://aboutwilson.net
@aboutwilson
Visualização
Visualização + Python
seaborn
bokeh
ggplot
prettyplotlib
Vincent
Vega
(Trifacta)
JavascriptSupport
Pandas Support
ggplot
seaborn
● Biblioteca de visualização baseada no matplotlib
" seaborn is a library for making attractive and
informative statistical graphics in Python "
● Boa para análise exploratória de dados
● Fortemente integrada com pandas e numpy
" Bringing Matplotlib to the Browser "
● Integra matplotlib com D3js
● Cria visualização de dados interativa no
navegador
mpld3
Vincent
" A Python to Vega translator "
" Vega is a visualization grammar, a declarative
format for creating, saving and sharing visualization
designs. "
● Estruturas de dados Python
● Visualização em JavaScript
● Integração com pandas
Bokeh
● Biblioteca de visualização interativa
● Integração com pandas
● Foco: explorar a visualização dos navegadores
dados: Top 100 Wines of the
World 2014
DataFrame pandas: wty
Quantos vinhos por País?
ggplot(wty, aes("Country")) + geom_bar(fill="red", colour="black") +
theme(axis_text_x=element_text(angle=90))
Quantos vinhos por País? (com estilo)
ggplot(wty, aes("Country")) + geom_bar(fill="red", colour="black") +
theme_xkcd() + theme(axis_text_x=element_text(angle=90))
Qual a relação entre Pontos e Prêmios?
ggplot(wty, aes(x='Prizes', y='Points')) + geom_point()
Qual a relação entre Pontos e Prêmios?
ggplot(wty, aes(y="Points", x="Prizes")) + geom_point(size=60, shape=6) +
stat_smooth(method='lm', colour='red')
Qual a relação entre Pontos e Prêmios por País?
idx = (wty.Country == 'AUSTRALIA') |
(wty.Country == 'FRANCE') |
(wty.Country == 'SPAIN') |
(wty.Country == 'USA') |
(wty.Country == 'ARGENTINA')
gplot(wty[idx], aes(x="Prizes", y="Points")) +
geom_point() +
stat_smooth(method='lm', color='blue') +
facet_wrap("Country", scales="fixed")
Como se distribuem os prêmios por País?
wty_country_prizes = wty['Prizes'].groupby(wty['Country'])
idx = wty_country_prizes.count() == 1
wty_t = wty.ix[[c not in idx[idx].index for c in wty.Country], 
['Country','Prizes']]
wty_t_country_mean = wty_t.groupby(wty_t.Country).mean()
country_names = wty_t_country_mean.Prizes.sort(inplace=False).index
import seaborn as sb
sb.set(style="ticks")
f, ax = plt.subplots()
sb.offset_spines()
sb.violinplot(wty_t['Prizes'], wty_t['Country'], order=country_names)
locs, labels = plt.xticks()
plt.setp(labels, rotation=45)
sb.despine(trim=True)
wty_country = wty.groupby('Country')
country_count = wty_country['Wine'].aggregate(len)
country_count.sort(inplace=True)
fig, ax = plt.subplots(figsize=(12,8))
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left()
plt.subplot(221)
g = wty_country['Prizes'].count()
x = np.arange(len(g))
countries = list(g.index.values)
y = g.values
plt.bar(x+1, y, align='center', width=0.5, alpha=0.4)
plt.xticks(x+1, [' ']*10, rotation=90)
plt.title('Contagem')
plt.ylabel('Prizes')
plt.subplot(222)
g = wty_country['Prizes'].mean()
y = g.values
plt.bar(x+1, y, align='center', color='red', width=0.5, alpha=0.4)
plt.xticks(x+1, [' ']*10, rotation=90);
plt.title(u'Média')
plt.subplot(223)
g = wty_country['Prizes'].max()
y = g.values
plt.bar(x+1, y, align='center', color='darkgreen', width=0.5, alpha=0.4)
plt.xticks(x+1, countries, rotation=90);
plt.title(u'Máx')
plt.ylabel('Prizes')
plt.subplot(224)
g = wty_country['Prizes'].min()
y = g.values
plt.bar(x+1, y, align='center', color='magenta', width=0.5, alpha=0.4)
plt.xticks(x+1, countries, rotation=90);
plt.title(u'Mín')
Mas qual País possui o melhor vinho?
>>> mpld3.save_html(fig, 'fig.html')
<div id="fig_el672345700473765832459779"></div>
<script>
function mpld3_load_lib(url, callback){
var s = document.createElement('script');
s.src = url;
s.async = true;
s.onreadystatechange = s.onload = callback;
s.onerror = function(){console.warn("failed to load library " + url);};
document.getElementsByTagName("head")[0].appendChild(s);
}
if(typeof(mpld3) !== "undefined" && mpld3._mpld3IsLoaded){
// already loaded: just create the figure
!function(mpld3){
...
mpld3 salva fig em html
import Quandl
tickers = [
"GOOG/BVMF_BOVA11.4",
"YAHOO/SA_PETR3.6",
"GOOG/BVMF_VALE5.4",
"GOOG/BVMF_BBDC4.4",
"GOOG/BVMF_BBAS3.4",
"GOOG/BVMF_ITUB4.4"]
series = Quandl.get(tickers,
trim_start="2013-01-01",
trim_end="2013-12-31")
series.columns = [
"BOVESPA",
"PETROBRAS",
"VALE",
"BRADESCO",
"BB",
"ITAU"]
series.dropna(inplace=True)
dados: Ações (Quandl)
>>> print series
BOVESPA PETROBRAS VALE BRADESCO BB ITAU
Date
2013-01-02 61.27 19.00 42.60 36.02 25.80 31.3
2013-01-03 61.92 19.70 42.09 38.12 26.31 32.2
2013-01-04 61.32 19.77 41.17 37.45 26.00 31.9
2013-01-07 60.75 19.51 40.35 37.29 26.15 31.5
2013-01-08 59.91 18.96 40.10 37.42 26.45 31.6
2013-01-09 60.25 19.15 40.30 37.90 26.70 32.1
2013-01-10 60.49 19.27 40.57 37.40 26.30 31.7
2013-01-11 60.30 19.32 39.53 37.27 25.98 31.8
2013-01-14 60.75 19.21 39.77 37.88 26.93 32.2
2013-01-15 60.52 19.27 39.65 37.30 26.70 31.8
2013-01-16 60.54 19.34 39.68 37.49 26.86 32.1
2013-01-17 61.01 19.21 39.75 38.11 26.81 32.6
2013-01-18 60.79 19.05 39.20 38.25 26.20 32.7
2013-01-21 60.75 18.87 39.15 38.09 25.93 32.5
2013-01-22 60.55 19.12 39.59 38.40 25.64 32.9
...
Visualização de Séries de Preço
import vincent as v
line = v.Line(series)
line.axis_titles(x='Date', y='Price')
line.legend(title='Series')
Exporta a Gramática de Gráficos
>>> print line.to_json()
{
"axes": [
{ "scale": "x", "title": "Date", "type": "x" },
{ "scale": "y", "title": "Price", "type": "y" }
],
"data": [
{
"name": "table",
"values": [
{ "col": "BOVESPA", "idx": 1357092000000, "val": 61.27 },
{ "col": "PETROBRAS","idx": 1357092000000, "val": 19.0 },
{ "col": "VALE", "idx": 1357092000000, "val": 42.6 },
...
Variação acumulada
logreturns = np.log(series).diff().dropna(inplace=False)
cumreturns = np.cumprod(np.exp(logreturns))
line = v.Line(cumreturns)
line.axis_titles(x='Date', y='')
line.legend(title='Series')
Séries de Preço Empilhadas
stacked = v.StackedArea(series)
stacked.axis_titles(x='Date', y='Price')
stacked.legend(title='Series')
stacked.colors(brew='Spectral')
Qual a correlação entre séries?
# com seaborn
sb.corrplot(np.log(series).diff().dropna())
Mais no detalhe
sb.jointplot("VALE", "BOVESPA",
series, kind="kde");
sb.jointplot("VALE", "BOVESPA",
series, kind="reg");
Rentabilidade de ações
● Qual a rentabilidade de cada ação por mês?
● Como visualizar tudo no mesmo gráfico?
● Como fazer isso higienicamente?
● Vamos considerar 18 ações no ano de 2013
Rentabilidade de ações
from bokeh.plotting import *
output_notebook()
import numpy as np
import Quandl
import pandas as pd
from collections import OrderedDict
tickers = ["GOOG/BVMF_BOVA11.4", "GOOG/BVMF_PETR3.4", "GOOG/BVMF_VALE5.4", 'GOOG/BVMF_BBDC4.4', 'GOOG/BVMF_BBAS3.4', 'GOOG/BVMF_ITUB4.4', 'GOOG/BVMF_USIM5.4', 'GOOG/BVMF_CIEL3.
4', 'GOOG/BVMF_CMIG4.4', 'GOOG/BVMF_CTIP3.4', 'GOOG/BVMF_CPLE6.4', 'GOOG/BVMF_ELET6.4', 'GOOG/BVMF_GGBR4.4', 'GOOG/BVMF_GOLL4.4', 'GOOG/BVMF_HGTX3.4', 'GOOG/BVMF_JBSS3.4',
'GOOG/BVMF_MRFG3.4', 'GOOG/BVMF_PDGR3.4']
series = Quandl.get(tickers, trim_start="2013-01-01", trim_end="2013-12-31", authtoken="nJ1NhTYdEs2p3MsS4CVd")
series.columns = ['BOVESPA', 'PETROBRAS', 'VALE', 'BRADESCO', 'BB', 'ITAU', 'USIMINAS', 'CIELO', 'CEMIG', 'CETIP', 'COPEL', 'ELETROPAULO', 'GERDAU', 'GOL', 'HERING', 'JBS',
'MAFRIG', 'PDGR']
series.dropna(inplace=True)
logreturns = np.log(series).diff().dropna()
months = ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"]
series_mr = logreturns.resample('M', how=sum)*100
series_mr['Month'] = [months[d.month-1] for d in series_mr.index]
series_mr.set_index('Month', inplace=True)
months = list(series_mr.index)
stocks = list(series_mr.columns)
import brewer2mpl
bmap = brewer2mpl.get_map('RdYlGn', 'diverging', 3)
colors = bmap.hex_colors
levels = np.array([0, 1])
month = []
stock = []
color = []
rate = []
for y in stocks:
for m in months:
month.append(m)
stock.append(y)
monthly_rate = series_mr[y][m]
rate.append(monthly_rate)
color.append(colors[sum(levels < monthly_rate)])
source = ColumnDataSource(data=dict(month=month, year=stock, color=color, rate=rate, ))
figure()
rect('year', 'month', 0.95, 0.95, source=source, x_range=stocks, y_range=list(reversed(months)), color='color', line_color=None, tools="resize,hover,save", title="Rentabilidade
de ações", plot_width=300, plot_height=400)
grid().grid_line_color = None
axis().axis_line_color = None
axis().major_tick_line_color = None
axis().major_label_text_font_size = "5pt"
axis().major_label_standoff = 0
xaxis().location = "top"
xaxis().major_label_orientation = np.pi/3
from bokeh.objects import HoverTool
hover = [t for t in curplot().tools if isinstance(t, HoverTool)][0]
hover.tooltips = OrderedDict([('date', '@month'), ('rate', '@rate'),])
show()
Rentabilidade de ações
Esse gráfico já não é tão simples!
;-)
Referências
● seaborn (github)
● vincent (github)
○ Trifacta - vega
● ggplot (github)
○ ggplot tutorial
○ ggplot2 no R
● AboutWilson.net: Refinando o estilo do matplotlib
● AboutWilson.net: Refinando o estilo do matplotlib com seaborn
● EuroPython 2014: Combining the powerful worlds of Python and R
● EuroPython 2014: Scientific Visualization with GR
● bokeh (github)
● mpld3 (github)
● prettyplotlib (github)
● plot.ly
● Quandl
● brewer2mpl (github)
https://github.com/wilsonfreitas/tdc-2014
Wilson Freitas
http://aboutwilson.net
@aboutwilson

Weitere ähnliche Inhalte

Andere mochten auch

Web Crawling Modeling with Scrapy Models #TDC2014
Web Crawling Modeling with Scrapy Models #TDC2014Web Crawling Modeling with Scrapy Models #TDC2014
Web Crawling Modeling with Scrapy Models #TDC2014Bruno Rocha
 
(2014-08-09) [TDC] AudioLazy 0.6 will robotize you!
(2014-08-09) [TDC] AudioLazy 0.6 will robotize you!(2014-08-09) [TDC] AudioLazy 0.6 will robotize you!
(2014-08-09) [TDC] AudioLazy 0.6 will robotize you!Danilo J. S. Bellini
 
Testando Aplicações Django: Quando, Como e Onde?
Testando Aplicações Django: Quando, Como e Onde?Testando Aplicações Django: Quando, Como e Onde?
Testando Aplicações Django: Quando, Como e Onde?Bernardo Fontes
 
import pybr12: experiencias de inclusión en la última PyCon Brazil
import pybr12: experiencias de inclusión en la última PyCon Brazilimport pybr12: experiencias de inclusión en la última PyCon Brazil
import pybr12: experiencias de inclusión en la última PyCon BrazilFATEC São José dos Campos
 

Andere mochten auch (7)

Web Crawling Modeling with Scrapy Models #TDC2014
Web Crawling Modeling with Scrapy Models #TDC2014Web Crawling Modeling with Scrapy Models #TDC2014
Web Crawling Modeling with Scrapy Models #TDC2014
 
(2014-08-09) [TDC] AudioLazy 0.6 will robotize you!
(2014-08-09) [TDC] AudioLazy 0.6 will robotize you!(2014-08-09) [TDC] AudioLazy 0.6 will robotize you!
(2014-08-09) [TDC] AudioLazy 0.6 will robotize you!
 
Algoritmos Genéticos
Algoritmos GenéticosAlgoritmos Genéticos
Algoritmos Genéticos
 
Testando Aplicações Django: Quando, Como e Onde?
Testando Aplicações Django: Quando, Como e Onde?Testando Aplicações Django: Quando, Como e Onde?
Testando Aplicações Django: Quando, Como e Onde?
 
TDD com Python
TDD com PythonTDD com Python
TDD com Python
 
import pybr12: experiencias de inclusión en la última PyCon Brazil
import pybr12: experiencias de inclusión en la última PyCon Brazilimport pybr12: experiencias de inclusión en la última PyCon Brazil
import pybr12: experiencias de inclusión en la última PyCon Brazil
 
Curso de Python e Django
Curso de Python e DjangoCurso de Python e Django
Curso de Python e Django
 

Ähnlich wie APIs de Visualização em Python

Getting more out of Matplotlib with GR
Getting more out of Matplotlib with GRGetting more out of Matplotlib with GR
Getting more out of Matplotlib with GRJosef Heinen
 
DevFest Kuala Lumpur - Implementing Google Analytics - 2011-09-29.ppt
DevFest Kuala Lumpur - Implementing Google Analytics - 2011-09-29.pptDevFest Kuala Lumpur - Implementing Google Analytics - 2011-09-29.ppt
DevFest Kuala Lumpur - Implementing Google Analytics - 2011-09-29.pptVinoaj Vijeyakumaar
 
Digital analytics with R - Sydney Users of R Forum - May 2015
Digital analytics with R - Sydney Users of R Forum - May 2015Digital analytics with R - Sydney Users of R Forum - May 2015
Digital analytics with R - Sydney Users of R Forum - May 2015Johann de Boer
 
GTUG Philippines - Implementing Google Analytics - 2011-10-11
GTUG Philippines - Implementing Google Analytics - 2011-10-11GTUG Philippines - Implementing Google Analytics - 2011-10-11
GTUG Philippines - Implementing Google Analytics - 2011-10-11Vinoaj Vijeyakumaar
 
Google Optimize for testing and personalization
Google Optimize for testing and personalizationGoogle Optimize for testing and personalization
Google Optimize for testing and personalizationOWOX BI
 
Supercharge your data analytics with BigQuery
Supercharge your data analytics with BigQuerySupercharge your data analytics with BigQuery
Supercharge your data analytics with BigQueryMárton Kodok
 
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache AirflowBusiness Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache AirflowRomain Dorgueil
 
DevFest Chiang Mai - Implementing Google Analytics - 2011-09-24.ppt
DevFest Chiang Mai - Implementing Google Analytics - 2011-09-24.pptDevFest Chiang Mai - Implementing Google Analytics - 2011-09-24.ppt
DevFest Chiang Mai - Implementing Google Analytics - 2011-09-24.pptVinoaj Vijeyakumaar
 
implemetning google analytics - 2011-09-24 Google Devfest Chiangmai
implemetning google analytics - 2011-09-24 Google Devfest Chiangmaiimplemetning google analytics - 2011-09-24 Google Devfest Chiangmai
implemetning google analytics - 2011-09-24 Google Devfest ChiangmaiPawoot (Pom) Pongvitayapanu
 
A Big (Query) Frog in a Small Pond, Jakub Motyl, BuffPanel
A Big (Query) Frog in a Small Pond, Jakub Motyl, BuffPanelA Big (Query) Frog in a Small Pond, Jakub Motyl, BuffPanel
A Big (Query) Frog in a Small Pond, Jakub Motyl, BuffPanelData Science Club
 
Google BigQuery for Everyday Developer
Google BigQuery for Everyday DeveloperGoogle BigQuery for Everyday Developer
Google BigQuery for Everyday DeveloperMárton Kodok
 
Apache Pinot Meetup Sept02, 2020
Apache Pinot Meetup Sept02, 2020Apache Pinot Meetup Sept02, 2020
Apache Pinot Meetup Sept02, 2020Mayank Shrivastava
 
Behaviour Driven Development
Behaviour Driven DevelopmentBehaviour Driven Development
Behaviour Driven DevelopmentRichard Ruiter
 
EP2016 - Moving Away From Nodejs To A Pure Python Solution For Assets
EP2016 - Moving Away From Nodejs To A Pure Python Solution For AssetsEP2016 - Moving Away From Nodejs To A Pure Python Solution For Assets
EP2016 - Moving Away From Nodejs To A Pure Python Solution For AssetsAlessandro Molina
 
Criteo Infrastructure (Platform) Meetup
Criteo Infrastructure (Platform) MeetupCriteo Infrastructure (Platform) Meetup
Criteo Infrastructure (Platform) MeetupIbrahim Abubakari
 
How to Realize an Additional 270% ROI on Snowflake
How to Realize an Additional 270% ROI on SnowflakeHow to Realize an Additional 270% ROI on Snowflake
How to Realize an Additional 270% ROI on SnowflakeAtScale
 
web design company in bangalore
web design company in bangaloreweb design company in bangalore
web design company in bangaloretechgreen solution
 
Real time ecommerce analytics with MongoDB at Gilt Groupe (Michael Bryzek & M...
Real time ecommerce analytics with MongoDB at Gilt Groupe (Michael Bryzek & M...Real time ecommerce analytics with MongoDB at Gilt Groupe (Michael Bryzek & M...
Real time ecommerce analytics with MongoDB at Gilt Groupe (Michael Bryzek & M...MongoSF
 
Google Analytics for Beginners - Training
Google Analytics for Beginners - TrainingGoogle Analytics for Beginners - Training
Google Analytics for Beginners - TrainingRuben Vezzoli
 

Ähnlich wie APIs de Visualização em Python (20)

Code Management
Code ManagementCode Management
Code Management
 
Getting more out of Matplotlib with GR
Getting more out of Matplotlib with GRGetting more out of Matplotlib with GR
Getting more out of Matplotlib with GR
 
DevFest Kuala Lumpur - Implementing Google Analytics - 2011-09-29.ppt
DevFest Kuala Lumpur - Implementing Google Analytics - 2011-09-29.pptDevFest Kuala Lumpur - Implementing Google Analytics - 2011-09-29.ppt
DevFest Kuala Lumpur - Implementing Google Analytics - 2011-09-29.ppt
 
Digital analytics with R - Sydney Users of R Forum - May 2015
Digital analytics with R - Sydney Users of R Forum - May 2015Digital analytics with R - Sydney Users of R Forum - May 2015
Digital analytics with R - Sydney Users of R Forum - May 2015
 
GTUG Philippines - Implementing Google Analytics - 2011-10-11
GTUG Philippines - Implementing Google Analytics - 2011-10-11GTUG Philippines - Implementing Google Analytics - 2011-10-11
GTUG Philippines - Implementing Google Analytics - 2011-10-11
 
Google Optimize for testing and personalization
Google Optimize for testing and personalizationGoogle Optimize for testing and personalization
Google Optimize for testing and personalization
 
Supercharge your data analytics with BigQuery
Supercharge your data analytics with BigQuerySupercharge your data analytics with BigQuery
Supercharge your data analytics with BigQuery
 
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache AirflowBusiness Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
 
DevFest Chiang Mai - Implementing Google Analytics - 2011-09-24.ppt
DevFest Chiang Mai - Implementing Google Analytics - 2011-09-24.pptDevFest Chiang Mai - Implementing Google Analytics - 2011-09-24.ppt
DevFest Chiang Mai - Implementing Google Analytics - 2011-09-24.ppt
 
implemetning google analytics - 2011-09-24 Google Devfest Chiangmai
implemetning google analytics - 2011-09-24 Google Devfest Chiangmaiimplemetning google analytics - 2011-09-24 Google Devfest Chiangmai
implemetning google analytics - 2011-09-24 Google Devfest Chiangmai
 
A Big (Query) Frog in a Small Pond, Jakub Motyl, BuffPanel
A Big (Query) Frog in a Small Pond, Jakub Motyl, BuffPanelA Big (Query) Frog in a Small Pond, Jakub Motyl, BuffPanel
A Big (Query) Frog in a Small Pond, Jakub Motyl, BuffPanel
 
Google BigQuery for Everyday Developer
Google BigQuery for Everyday DeveloperGoogle BigQuery for Everyday Developer
Google BigQuery for Everyday Developer
 
Apache Pinot Meetup Sept02, 2020
Apache Pinot Meetup Sept02, 2020Apache Pinot Meetup Sept02, 2020
Apache Pinot Meetup Sept02, 2020
 
Behaviour Driven Development
Behaviour Driven DevelopmentBehaviour Driven Development
Behaviour Driven Development
 
EP2016 - Moving Away From Nodejs To A Pure Python Solution For Assets
EP2016 - Moving Away From Nodejs To A Pure Python Solution For AssetsEP2016 - Moving Away From Nodejs To A Pure Python Solution For Assets
EP2016 - Moving Away From Nodejs To A Pure Python Solution For Assets
 
Criteo Infrastructure (Platform) Meetup
Criteo Infrastructure (Platform) MeetupCriteo Infrastructure (Platform) Meetup
Criteo Infrastructure (Platform) Meetup
 
How to Realize an Additional 270% ROI on Snowflake
How to Realize an Additional 270% ROI on SnowflakeHow to Realize an Additional 270% ROI on Snowflake
How to Realize an Additional 270% ROI on Snowflake
 
web design company in bangalore
web design company in bangaloreweb design company in bangalore
web design company in bangalore
 
Real time ecommerce analytics with MongoDB at Gilt Groupe (Michael Bryzek & M...
Real time ecommerce analytics with MongoDB at Gilt Groupe (Michael Bryzek & M...Real time ecommerce analytics with MongoDB at Gilt Groupe (Michael Bryzek & M...
Real time ecommerce analytics with MongoDB at Gilt Groupe (Michael Bryzek & M...
 
Google Analytics for Beginners - Training
Google Analytics for Beginners - TrainingGoogle Analytics for Beginners - Training
Google Analytics for Beginners - Training
 

Mehr von Wilson Freitas

bizdays: Dias Úteis em Qualquer Calendário
bizdays: Dias Úteis em Qualquer Calendáriobizdays: Dias Úteis em Qualquer Calendário
bizdays: Dias Úteis em Qualquer CalendárioWilson Freitas
 
Análise dos campeões da Corrida de São Silvestre com Python
Análise dos campeões da Corrida de São Silvestre com PythonAnálise dos campeões da Corrida de São Silvestre com Python
Análise dos campeões da Corrida de São Silvestre com PythonWilson Freitas
 
Um modelo de formação de preços para um mercado artificial com redes neurais ...
Um modelo de formação de preços para um mercado artificial com redes neurais ...Um modelo de formação de preços para um mercado artificial com redes neurais ...
Um modelo de formação de preços para um mercado artificial com redes neurais ...Wilson Freitas
 
Sobre o comportamento endógeno do mercado de ações: simulações e experimentos
Sobre o comportamento endógeno do mercado de ações: simulações e experimentosSobre o comportamento endógeno do mercado de ações: simulações e experimentos
Sobre o comportamento endógeno do mercado de ações: simulações e experimentosWilson Freitas
 
Apreçando Opções Utilizando a Função Característica
Apreçando Opções Utilizando a Função CaracterísticaApreçando Opções Utilizando a Função Característica
Apreçando Opções Utilizando a Função CaracterísticaWilson Freitas
 
Redes neurais em finanças
Redes neurais em finançasRedes neurais em finanças
Redes neurais em finançasWilson Freitas
 
Expansão em caos polinomial
Expansão em caos polinomialExpansão em caos polinomial
Expansão em caos polinomialWilson Freitas
 

Mehr von Wilson Freitas (7)

bizdays: Dias Úteis em Qualquer Calendário
bizdays: Dias Úteis em Qualquer Calendáriobizdays: Dias Úteis em Qualquer Calendário
bizdays: Dias Úteis em Qualquer Calendário
 
Análise dos campeões da Corrida de São Silvestre com Python
Análise dos campeões da Corrida de São Silvestre com PythonAnálise dos campeões da Corrida de São Silvestre com Python
Análise dos campeões da Corrida de São Silvestre com Python
 
Um modelo de formação de preços para um mercado artificial com redes neurais ...
Um modelo de formação de preços para um mercado artificial com redes neurais ...Um modelo de formação de preços para um mercado artificial com redes neurais ...
Um modelo de formação de preços para um mercado artificial com redes neurais ...
 
Sobre o comportamento endógeno do mercado de ações: simulações e experimentos
Sobre o comportamento endógeno do mercado de ações: simulações e experimentosSobre o comportamento endógeno do mercado de ações: simulações e experimentos
Sobre o comportamento endógeno do mercado de ações: simulações e experimentos
 
Apreçando Opções Utilizando a Função Característica
Apreçando Opções Utilizando a Função CaracterísticaApreçando Opções Utilizando a Função Característica
Apreçando Opções Utilizando a Função Característica
 
Redes neurais em finanças
Redes neurais em finançasRedes neurais em finanças
Redes neurais em finanças
 
Expansão em caos polinomial
Expansão em caos polinomialExpansão em caos polinomial
Expansão em caos polinomial
 

Kürzlich hochgeladen

Vip Mumbai Call Girls Marol Naka Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Marol Naka Call On 9920725232 With Body to body massage...Vip Mumbai Call Girls Marol Naka Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Marol Naka Call On 9920725232 With Body to body massage...amitlee9823
 
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...amitlee9823
 
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangaloreamitlee9823
 
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Standamitlee9823
 
Capstone Project on IBM Data Analytics Program
Capstone Project on IBM Data Analytics ProgramCapstone Project on IBM Data Analytics Program
Capstone Project on IBM Data Analytics ProgramMoniSankarHazra
 
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% SecureCall me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% SecurePooja Nehwal
 
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...amitlee9823
 
➥🔝 7737669865 🔝▻ Dindigul Call-girls in Women Seeking Men 🔝Dindigul🔝 Escor...
➥🔝 7737669865 🔝▻ Dindigul Call-girls in Women Seeking Men  🔝Dindigul🔝   Escor...➥🔝 7737669865 🔝▻ Dindigul Call-girls in Women Seeking Men  🔝Dindigul🔝   Escor...
➥🔝 7737669865 🔝▻ Dindigul Call-girls in Women Seeking Men 🔝Dindigul🔝 Escor...amitlee9823
 
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...amitlee9823
 
➥🔝 7737669865 🔝▻ mahisagar Call-girls in Women Seeking Men 🔝mahisagar🔝 Esc...
➥🔝 7737669865 🔝▻ mahisagar Call-girls in Women Seeking Men  🔝mahisagar🔝   Esc...➥🔝 7737669865 🔝▻ mahisagar Call-girls in Women Seeking Men  🔝mahisagar🔝   Esc...
➥🔝 7737669865 🔝▻ mahisagar Call-girls in Women Seeking Men 🔝mahisagar🔝 Esc...amitlee9823
 
Call Girls Indiranagar Just Call 👗 9155563397 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 9155563397 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 9155563397 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 9155563397 👗 Top Class Call Girl Service B...only4webmaster01
 
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...SUHANI PANDEY
 
Detecting Credit Card Fraud: A Machine Learning Approach
Detecting Credit Card Fraud: A Machine Learning ApproachDetecting Credit Card Fraud: A Machine Learning Approach
Detecting Credit Card Fraud: A Machine Learning ApproachBoston Institute of Analytics
 
April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysismanisha194592
 
Call Girls Jalahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service Ban...
Call Girls Jalahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service Ban...Call Girls Jalahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service Ban...
Call Girls Jalahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service Ban...amitlee9823
 
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...amitlee9823
 

Kürzlich hochgeladen (20)

Vip Mumbai Call Girls Marol Naka Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Marol Naka Call On 9920725232 With Body to body massage...Vip Mumbai Call Girls Marol Naka Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Marol Naka Call On 9920725232 With Body to body massage...
 
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
 
Predicting Loan Approval: A Data Science Project
Predicting Loan Approval: A Data Science ProjectPredicting Loan Approval: A Data Science Project
Predicting Loan Approval: A Data Science Project
 
(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7
(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7
(NEHA) Call Girls Katra Call Now 8617697112 Katra Escorts 24x7
 
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
 
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bellandur ☎ 7737669865 🥵 Book Your One night Stand
 
Capstone Project on IBM Data Analytics Program
Capstone Project on IBM Data Analytics ProgramCapstone Project on IBM Data Analytics Program
Capstone Project on IBM Data Analytics Program
 
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% SecureCall me @ 9892124323  Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
Call me @ 9892124323 Cheap Rate Call Girls in Vashi with Real Photo 100% Secure
 
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
Vip Mumbai Call Girls Thane West Call On 9920725232 With Body to body massage...
 
➥🔝 7737669865 🔝▻ Dindigul Call-girls in Women Seeking Men 🔝Dindigul🔝 Escor...
➥🔝 7737669865 🔝▻ Dindigul Call-girls in Women Seeking Men  🔝Dindigul🔝   Escor...➥🔝 7737669865 🔝▻ Dindigul Call-girls in Women Seeking Men  🔝Dindigul🔝   Escor...
➥🔝 7737669865 🔝▻ Dindigul Call-girls in Women Seeking Men 🔝Dindigul🔝 Escor...
 
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
 
➥🔝 7737669865 🔝▻ mahisagar Call-girls in Women Seeking Men 🔝mahisagar🔝 Esc...
➥🔝 7737669865 🔝▻ mahisagar Call-girls in Women Seeking Men  🔝mahisagar🔝   Esc...➥🔝 7737669865 🔝▻ mahisagar Call-girls in Women Seeking Men  🔝mahisagar🔝   Esc...
➥🔝 7737669865 🔝▻ mahisagar Call-girls in Women Seeking Men 🔝mahisagar🔝 Esc...
 
Abortion pills in Jeddah | +966572737505 | Get Cytotec
Abortion pills in Jeddah | +966572737505 | Get CytotecAbortion pills in Jeddah | +966572737505 | Get Cytotec
Abortion pills in Jeddah | +966572737505 | Get Cytotec
 
Call Girls Indiranagar Just Call 👗 9155563397 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 9155563397 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 9155563397 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 9155563397 👗 Top Class Call Girl Service B...
 
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
 
Detecting Credit Card Fraud: A Machine Learning Approach
Detecting Credit Card Fraud: A Machine Learning ApproachDetecting Credit Card Fraud: A Machine Learning Approach
Detecting Credit Card Fraud: A Machine Learning Approach
 
April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysis
 
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Call Girls Jalahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service Ban...
Call Girls Jalahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service Ban...Call Girls Jalahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service Ban...
Call Girls Jalahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service Ban...
 
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
Call Girls Indiranagar Just Call 👗 7737669865 👗 Top Class Call Girl Service B...
 

APIs de Visualização em Python

  • 1. APIs de Visualização em Python TDC 2014 Wilson Freitas http://aboutwilson.net @aboutwilson
  • 3.
  • 6. seaborn ● Biblioteca de visualização baseada no matplotlib " seaborn is a library for making attractive and informative statistical graphics in Python " ● Boa para análise exploratória de dados ● Fortemente integrada com pandas e numpy
  • 7. " Bringing Matplotlib to the Browser " ● Integra matplotlib com D3js ● Cria visualização de dados interativa no navegador mpld3
  • 8. Vincent " A Python to Vega translator " " Vega is a visualization grammar, a declarative format for creating, saving and sharing visualization designs. " ● Estruturas de dados Python ● Visualização em JavaScript ● Integração com pandas
  • 9. Bokeh ● Biblioteca de visualização interativa ● Integração com pandas ● Foco: explorar a visualização dos navegadores
  • 10. dados: Top 100 Wines of the World 2014
  • 12. Quantos vinhos por País? ggplot(wty, aes("Country")) + geom_bar(fill="red", colour="black") + theme(axis_text_x=element_text(angle=90))
  • 13. Quantos vinhos por País? (com estilo) ggplot(wty, aes("Country")) + geom_bar(fill="red", colour="black") + theme_xkcd() + theme(axis_text_x=element_text(angle=90))
  • 14. Qual a relação entre Pontos e Prêmios? ggplot(wty, aes(x='Prizes', y='Points')) + geom_point()
  • 15. Qual a relação entre Pontos e Prêmios? ggplot(wty, aes(y="Points", x="Prizes")) + geom_point(size=60, shape=6) + stat_smooth(method='lm', colour='red')
  • 16. Qual a relação entre Pontos e Prêmios por País? idx = (wty.Country == 'AUSTRALIA') | (wty.Country == 'FRANCE') | (wty.Country == 'SPAIN') | (wty.Country == 'USA') | (wty.Country == 'ARGENTINA') gplot(wty[idx], aes(x="Prizes", y="Points")) + geom_point() + stat_smooth(method='lm', color='blue') + facet_wrap("Country", scales="fixed")
  • 17. Como se distribuem os prêmios por País? wty_country_prizes = wty['Prizes'].groupby(wty['Country']) idx = wty_country_prizes.count() == 1 wty_t = wty.ix[[c not in idx[idx].index for c in wty.Country], ['Country','Prizes']] wty_t_country_mean = wty_t.groupby(wty_t.Country).mean() country_names = wty_t_country_mean.Prizes.sort(inplace=False).index import seaborn as sb sb.set(style="ticks") f, ax = plt.subplots() sb.offset_spines() sb.violinplot(wty_t['Prizes'], wty_t['Country'], order=country_names) locs, labels = plt.xticks() plt.setp(labels, rotation=45) sb.despine(trim=True)
  • 18. wty_country = wty.groupby('Country') country_count = wty_country['Wine'].aggregate(len) country_count.sort(inplace=True) fig, ax = plt.subplots(figsize=(12,8)) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_visible(False) ax.get_xaxis().tick_bottom() ax.get_yaxis().tick_left() plt.subplot(221) g = wty_country['Prizes'].count() x = np.arange(len(g)) countries = list(g.index.values) y = g.values plt.bar(x+1, y, align='center', width=0.5, alpha=0.4) plt.xticks(x+1, [' ']*10, rotation=90) plt.title('Contagem') plt.ylabel('Prizes') plt.subplot(222) g = wty_country['Prizes'].mean() y = g.values plt.bar(x+1, y, align='center', color='red', width=0.5, alpha=0.4) plt.xticks(x+1, [' ']*10, rotation=90); plt.title(u'Média') plt.subplot(223) g = wty_country['Prizes'].max() y = g.values plt.bar(x+1, y, align='center', color='darkgreen', width=0.5, alpha=0.4) plt.xticks(x+1, countries, rotation=90); plt.title(u'Máx') plt.ylabel('Prizes') plt.subplot(224) g = wty_country['Prizes'].min() y = g.values plt.bar(x+1, y, align='center', color='magenta', width=0.5, alpha=0.4) plt.xticks(x+1, countries, rotation=90); plt.title(u'Mín') Mas qual País possui o melhor vinho?
  • 19. >>> mpld3.save_html(fig, 'fig.html') <div id="fig_el672345700473765832459779"></div> <script> function mpld3_load_lib(url, callback){ var s = document.createElement('script'); s.src = url; s.async = true; s.onreadystatechange = s.onload = callback; s.onerror = function(){console.warn("failed to load library " + url);}; document.getElementsByTagName("head")[0].appendChild(s); } if(typeof(mpld3) !== "undefined" && mpld3._mpld3IsLoaded){ // already loaded: just create the figure !function(mpld3){ ... mpld3 salva fig em html
  • 20. import Quandl tickers = [ "GOOG/BVMF_BOVA11.4", "YAHOO/SA_PETR3.6", "GOOG/BVMF_VALE5.4", "GOOG/BVMF_BBDC4.4", "GOOG/BVMF_BBAS3.4", "GOOG/BVMF_ITUB4.4"] series = Quandl.get(tickers, trim_start="2013-01-01", trim_end="2013-12-31") series.columns = [ "BOVESPA", "PETROBRAS", "VALE", "BRADESCO", "BB", "ITAU"] series.dropna(inplace=True) dados: Ações (Quandl) >>> print series BOVESPA PETROBRAS VALE BRADESCO BB ITAU Date 2013-01-02 61.27 19.00 42.60 36.02 25.80 31.3 2013-01-03 61.92 19.70 42.09 38.12 26.31 32.2 2013-01-04 61.32 19.77 41.17 37.45 26.00 31.9 2013-01-07 60.75 19.51 40.35 37.29 26.15 31.5 2013-01-08 59.91 18.96 40.10 37.42 26.45 31.6 2013-01-09 60.25 19.15 40.30 37.90 26.70 32.1 2013-01-10 60.49 19.27 40.57 37.40 26.30 31.7 2013-01-11 60.30 19.32 39.53 37.27 25.98 31.8 2013-01-14 60.75 19.21 39.77 37.88 26.93 32.2 2013-01-15 60.52 19.27 39.65 37.30 26.70 31.8 2013-01-16 60.54 19.34 39.68 37.49 26.86 32.1 2013-01-17 61.01 19.21 39.75 38.11 26.81 32.6 2013-01-18 60.79 19.05 39.20 38.25 26.20 32.7 2013-01-21 60.75 18.87 39.15 38.09 25.93 32.5 2013-01-22 60.55 19.12 39.59 38.40 25.64 32.9 ...
  • 21. Visualização de Séries de Preço import vincent as v line = v.Line(series) line.axis_titles(x='Date', y='Price') line.legend(title='Series')
  • 22. Exporta a Gramática de Gráficos >>> print line.to_json() { "axes": [ { "scale": "x", "title": "Date", "type": "x" }, { "scale": "y", "title": "Price", "type": "y" } ], "data": [ { "name": "table", "values": [ { "col": "BOVESPA", "idx": 1357092000000, "val": 61.27 }, { "col": "PETROBRAS","idx": 1357092000000, "val": 19.0 }, { "col": "VALE", "idx": 1357092000000, "val": 42.6 }, ...
  • 23. Variação acumulada logreturns = np.log(series).diff().dropna(inplace=False) cumreturns = np.cumprod(np.exp(logreturns)) line = v.Line(cumreturns) line.axis_titles(x='Date', y='') line.legend(title='Series')
  • 24. Séries de Preço Empilhadas stacked = v.StackedArea(series) stacked.axis_titles(x='Date', y='Price') stacked.legend(title='Series') stacked.colors(brew='Spectral')
  • 25. Qual a correlação entre séries? # com seaborn sb.corrplot(np.log(series).diff().dropna())
  • 26. Mais no detalhe sb.jointplot("VALE", "BOVESPA", series, kind="kde"); sb.jointplot("VALE", "BOVESPA", series, kind="reg");
  • 27. Rentabilidade de ações ● Qual a rentabilidade de cada ação por mês? ● Como visualizar tudo no mesmo gráfico? ● Como fazer isso higienicamente? ● Vamos considerar 18 ações no ano de 2013
  • 29. from bokeh.plotting import * output_notebook() import numpy as np import Quandl import pandas as pd from collections import OrderedDict tickers = ["GOOG/BVMF_BOVA11.4", "GOOG/BVMF_PETR3.4", "GOOG/BVMF_VALE5.4", 'GOOG/BVMF_BBDC4.4', 'GOOG/BVMF_BBAS3.4', 'GOOG/BVMF_ITUB4.4', 'GOOG/BVMF_USIM5.4', 'GOOG/BVMF_CIEL3. 4', 'GOOG/BVMF_CMIG4.4', 'GOOG/BVMF_CTIP3.4', 'GOOG/BVMF_CPLE6.4', 'GOOG/BVMF_ELET6.4', 'GOOG/BVMF_GGBR4.4', 'GOOG/BVMF_GOLL4.4', 'GOOG/BVMF_HGTX3.4', 'GOOG/BVMF_JBSS3.4', 'GOOG/BVMF_MRFG3.4', 'GOOG/BVMF_PDGR3.4'] series = Quandl.get(tickers, trim_start="2013-01-01", trim_end="2013-12-31", authtoken="nJ1NhTYdEs2p3MsS4CVd") series.columns = ['BOVESPA', 'PETROBRAS', 'VALE', 'BRADESCO', 'BB', 'ITAU', 'USIMINAS', 'CIELO', 'CEMIG', 'CETIP', 'COPEL', 'ELETROPAULO', 'GERDAU', 'GOL', 'HERING', 'JBS', 'MAFRIG', 'PDGR'] series.dropna(inplace=True) logreturns = np.log(series).diff().dropna() months = ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"] series_mr = logreturns.resample('M', how=sum)*100 series_mr['Month'] = [months[d.month-1] for d in series_mr.index] series_mr.set_index('Month', inplace=True) months = list(series_mr.index) stocks = list(series_mr.columns) import brewer2mpl bmap = brewer2mpl.get_map('RdYlGn', 'diverging', 3) colors = bmap.hex_colors levels = np.array([0, 1]) month = [] stock = [] color = [] rate = [] for y in stocks: for m in months: month.append(m) stock.append(y) monthly_rate = series_mr[y][m] rate.append(monthly_rate) color.append(colors[sum(levels < monthly_rate)]) source = ColumnDataSource(data=dict(month=month, year=stock, color=color, rate=rate, )) figure() rect('year', 'month', 0.95, 0.95, source=source, x_range=stocks, y_range=list(reversed(months)), color='color', line_color=None, tools="resize,hover,save", title="Rentabilidade de ações", plot_width=300, plot_height=400) grid().grid_line_color = None axis().axis_line_color = None axis().major_tick_line_color = None axis().major_label_text_font_size = "5pt" axis().major_label_standoff = 0 xaxis().location = "top" xaxis().major_label_orientation = np.pi/3 from bokeh.objects import HoverTool hover = [t for t in curplot().tools if isinstance(t, HoverTool)][0] hover.tooltips = OrderedDict([('date', '@month'), ('rate', '@rate'),]) show() Rentabilidade de ações Esse gráfico já não é tão simples! ;-)
  • 30. Referências ● seaborn (github) ● vincent (github) ○ Trifacta - vega ● ggplot (github) ○ ggplot tutorial ○ ggplot2 no R ● AboutWilson.net: Refinando o estilo do matplotlib ● AboutWilson.net: Refinando o estilo do matplotlib com seaborn ● EuroPython 2014: Combining the powerful worlds of Python and R ● EuroPython 2014: Scientific Visualization with GR ● bokeh (github) ● mpld3 (github) ● prettyplotlib (github) ● plot.ly ● Quandl ● brewer2mpl (github)