Hướng dẫn generate html python - tạo html python

Python HTML báo cáo trong Python/V3

Cách thực hiện các báo cáo HTML với Python, Gandas và đồ thị Plotly.


Lưu ý: Trang này là một phần của tài liệu cho phiên bản 3 của Plotly.py, đây không phải là phiên bản gần đây nhất. Xem Hướng dẫn di chuyển phiên bản 4 của chúng tôi để biết thông tin về cách nâng cấp. this page is part of the documentation for version 3 of Plotly.py, which is not the most recent version.
See our Version 4 Migration Guide for information about how to upgrade.

Tạo các báo cáo HTML với D3 Biểu đồ Python, Plotly và Pandasusing Python, Plotly, and Pandas

D3.js là một thư viện JavaScript tuyệt vời để tạo đồ họa và biểu đồ trực tuyến tương tác. Plotly cho phép bạn tạo biểu đồ D3.js bằng Python, R hoặc Matlab. Cuốn sổ ghi chép IPYTHON này chỉ cho bạn cách nhúng các biểu đồ này vào báo cáo HTML mà sau đó bạn có thể chia sẻ qua email hoặc máy chủ trên một trang web.

In [153]:

import plotly as py
import pandas as pd
import numpy as np

from datetime import datetime
from datetime import time as dt_tm
from datetime import date as dt_date

import plotly.plotly as py
import plotly.tools as plotly_tools
import plotly.graph_objs as go

import os
import tempfile
os.environ['MPLCONFIGDIR'] = tempfile.mkdtemp()
from matplotlib.finance import quotes_historical_yahoo
import matplotlib.pyplot as plt

from scipy.stats import gaussian_kde

from IPython.display import HTML

Bước 1: Tạo 2 biểu đồ và 2 bảng

Biểu đồ đầu tiên: Dữ liệu cổ phiếu Apple 2014 với Trung bình Di chuyển

In [154]:

x = []
y = []
ma = []

def moving_average(interval, window_size):
    window = np.ones(int(window_size))/float(window_size)
    return np.convolve(interval, window, 'same')

date1 = dt_date( 2014, 1, 1 )
date2 = dt_date( 2014, 12, 12 )
quotes = quotes_historical_yahoo('AAPL', date1, date2)
if len(quotes) == 0:
    print "Couldn't connect to yahoo trading database"
else:
    dates = [q[0] for q in quotes]
    y = [q[1] for q in quotes]
    for date in dates:
        x.append(datetime.fromordinal(int(date))\
                .strftime('%Y-%m-%d')) # Plotly timestamp format
    ma = moving_average(y, 10)

In [155]:

xy_data = go.Scatter( x=x, y=y, mode='markers', marker=dict(size=4), name='AAPL' )
# vvv clip first and last points of convolution
mov_avg = go.Scatter( x=x[5:-4], y=ma[5:-4], \
                  line=dict(width=2,color='red',opacity=0.5), name='Moving average' )
data = [xy_data, mov_avg]

py.iplot(data, filename='apple stock moving average')

Lưu URL cốt truyện - chúng tôi sẽ sử dụng nó khi tạo báo cáo sau.

In [157]:

first_plot_url = py.plot(data, filename='apple stock moving average', auto_open=False,)
print first_plot_url

https://plotly.com/~jackp/1841

Biểu đồ thứ hai: Ma trận phân tán công nghệ năm 2014 và cổ phiếu CPG

Hãy sử dụng gói gandas và các ô phụ âm mưu để so sánh các công nghệ khác nhau. và cổ phiếu CPG vào năm 2014. Biểu đồ này được lấy cảm hứng từ cuốn sổ tay IPYTHON và người dùng GitHub Twiecki này.
This graph was inspired by this IPython notebook and GitHub user twiecki.

In [5]:

tickers = ['AAPL', 'GE', 'IBM', 'KO', 'MSFT', 'PEP']
prices = []
for ticker in tickers:
    quotes = quotes_historical_yahoo(ticker, date1, date2)
    prices.append( [q[1] for q in quotes] )

Chúng tôi có tất cả các giá cổ phiếu trong một danh sách các danh sách - sử dụng đoạn mã bên dưới để chuyển đổi nó thành một khung dữ liệu gấu trúc.

In [6]:

df = pd.DataFrame( prices ).transpose()
df.columns = tickers
df.head()

Out[6]:

AAPLGEIBMKOMSFTPep
0 77.746778 26.907695 182.770157 39.926650 36.354938 80.626950
1 77.352163 26.578632 181.429182 39.493584 36.212300 79.843327
2 75.193398 26.716354 182.712734 39.303899 35.870869 79.922217
3 76.158839 26.543525 181.968752 39.297371 35.362131 80.323900
4 75.389380 26.415215 184.837731 39.265478 35.043624 81.017502

Sử dụng thói quen get_subplots () của Plotly để tạo ra một ma trận trống của các ô con 6x6. Chúng tôi sẽ điền vào những thứ này bằng cách vẽ tất cả các kết hợp đánh dấu vào cổ phiếu với nhau (nghĩa là cổ phiếu điện chung so với cổ phiếu Apple)

In [122]:

fig = plotly_tools.get_subplots(rows=6, columns=6, print_grid=True, horizontal_spacing= 0.05, vertical_spacing= 0.05)

This is the format of your plot grid!
[31]	[32]	[33]	[34]	[35]	[36]
[25]	[26]	[27]	[28]	[29]	[30]
[19]	[20]	[21]	[22]	[23]	[24]
[13]	[14]	[15]	[16]	[17]	[18]
[7]	[8]	[9]	[10]	[11]	[12]
[1]	[2]	[3]	[4]	[5]	[6]

In [143]:

def kde_scipy(x, x_grid, bandwidth=0.4, **kwargs):
    """Kernel Density Estimation with Scipy"""
    # From https://jakevdp.github.io/blog/2013/12/01/kernel-density-estimation/
    # Note that scipy weights its bandwidth by the covariance of the
    # input data.  To make the results comparable to the other methods,
    # we divide the bandwidth by the sample standard deviation here.
    kde = gaussian_kde(x, bw_method=bandwidth / x.std(ddof=1), **kwargs)
    return kde.evaluate(x_grid)

subplots = range(1,37)
sp_index = 0
data = []
for i in range(1,7):
    x_ticker = df.columns[i-1]
    for j in range(1,7):
        y_ticker = df.columns[j-1]
        if i==j:
            x = df[x_ticker]
            x_grid = np.linspace(x.min(), x.max(), 100)
            sp = [ go.Histogram( x=x, histnorm='probability density' ), \
                  go.Scatter( x=x_grid, y=kde_scipy( x.as_matrix(), x_grid ), \
                          line=dict(width=2,color='red',opacity='0.5') ) ]
        else:
            sp = [ go.Scatter( x=df[x_ticker], y=df[y_ticker], mode='markers', marker=dict(size=3) ) ]

        for ea in sp:
            ea.update( name='{0} vs {1}'.format(x_ticker,y_ticker),\
                      xaxis='x{}'.format(subplots[sp_index]),\
                      yaxis='y{}'.format(subplots[sp_index])
            )
        sp_index+=1
        data += sp

# Add x and y labels
left_index = 1
bottom_index = 1
for tk in tickers:
    fig['layout']['xaxis{}'.format(left_index)].update( title=tk )
    fig['layout']['yaxis{}'.format(bottom_index)].update( title=tk )
    left_index=left_index+1
    bottom_index=bottom_index+6

# Remove legend by updating 'layout' key
fig['layout'].update(showlegend=False,height=1000,width=1000, title='Major technology and CPG stock prices in 2014')
fig['data'] = data
py.iplot(fig, height=1000, width=1000, filename='Major technology and CPG stock prices in 2014 - scatter matrix')

Lưu URL cốt truyện - chúng tôi sẽ sử dụng nó khi tạo báo cáo sau.

In [145]:

x = []
y = []
ma = []

def moving_average(interval, window_size):
    window = np.ones(int(window_size))/float(window_size)
    return np.convolve(interval, window, 'same')

date1 = dt_date( 2014, 1, 1 )
date2 = dt_date( 2014, 12, 12 )
quotes = quotes_historical_yahoo('AAPL', date1, date2)
if len(quotes) == 0:
    print "Couldn't connect to yahoo trading database"
else:
    dates = [q[0] for q in quotes]
    y = [q[1] for q in quotes]
    for date in dates:
        x.append(datetime.fromordinal(int(date))\
                .strftime('%Y-%m-%d')) # Plotly timestamp format
    ma = moving_average(y, 10)
0

x = []
y = []
ma = []

def moving_average(interval, window_size):
    window = np.ones(int(window_size))/float(window_size)
    return np.convolve(interval, window, 'same')

date1 = dt_date( 2014, 1, 1 )
date2 = dt_date( 2014, 12, 12 )
quotes = quotes_historical_yahoo('AAPL', date1, date2)
if len(quotes) == 0:
    print "Couldn't connect to yahoo trading database"
else:
    dates = [q[0] for q in quotes]
    y = [q[1] for q in quotes]
    for date in dates:
        x.append(datetime.fromordinal(int(date))\
                .strftime('%Y-%m-%d')) # Plotly timestamp format
    ma = moving_average(y, 10)
1

Biểu đồ thứ hai: Ma trận phân tán công nghệ năm 2014 và cổ phiếu CPG

Hãy sử dụng gói gandas và các ô phụ âm mưu để so sánh các công nghệ khác nhau. và cổ phiếu CPG vào năm 2014. Biểu đồ này được lấy cảm hứng từ cuốn sổ tay IPYTHON và người dùng GitHub Twiecki này.

In [175]:

x = []
y = []
ma = []

def moving_average(interval, window_size):
    window = np.ones(int(window_size))/float(window_size)
    return np.convolve(interval, window, 'same')

date1 = dt_date( 2014, 1, 1 )
date2 = dt_date( 2014, 12, 12 )
quotes = quotes_historical_yahoo('AAPL', date1, date2)
if len(quotes) == 0:
    print "Couldn't connect to yahoo trading database"
else:
    dates = [q[0] for q in quotes]
    y = [q[1] for q in quotes]
    for date in dates:
        x.append(datetime.fromordinal(int(date))\
                .strftime('%Y-%m-%d')) # Plotly timestamp format
    ma = moving_average(y, 10)
2

Chúng tôi có tất cả các giá cổ phiếu trong một danh sách các danh sách - sử dụng đoạn mã bên dưới để chuyển đổi nó thành một khung dữ liệu gấu trúc.

In [135]:

x = []
y = []
ma = []

def moving_average(interval, window_size):
    window = np.ones(int(window_size))/float(window_size)
    return np.convolve(interval, window, 'same')

date1 = dt_date( 2014, 1, 1 )
date2 = dt_date( 2014, 12, 12 )
quotes = quotes_historical_yahoo('AAPL', date1, date2)
if len(quotes) == 0:
    print "Couldn't connect to yahoo trading database"
else:
    dates = [q[0] for q in quotes]
    y = [q[1] for q in quotes]
    for date in dates:
        x.append(datetime.fromordinal(int(date))\
                .strftime('%Y-%m-%d')) # Plotly timestamp format
    ma = moving_average(y, 10)
3

AAPLas a string and write to file

GE
Notice that the Bootstrap css library is included in the for styling.

IBM

x = []
y = []
ma = []

def moving_average(interval, window_size):
    window = np.ones(int(window_size))/float(window_size)
    return np.convolve(interval, window, 'same')

date1 = dt_date( 2014, 1, 1 )
date2 = dt_date( 2014, 12, 12 )
quotes = quotes_historical_yahoo('AAPL', date1, date2)
if len(quotes) == 0:
    print "Couldn't connect to yahoo trading database"
else:
    dates = [q[0] for q in quotes]
    y = [q[1] for q in quotes]
    for date in dates:
        x.append(datetime.fromordinal(int(date))\
                .strftime('%Y-%m-%d')) # Plotly timestamp format
    ma = moving_average(y, 10)
4

KO

In [185]:

x = []
y = []
ma = []

def moving_average(interval, window_size):
    window = np.ones(int(window_size))/float(window_size)
    return np.convolve(interval, window, 'same')

date1 = dt_date( 2014, 1, 1 )
date2 = dt_date( 2014, 12, 12 )
quotes = quotes_historical_yahoo('AAPL', date1, date2)
if len(quotes) == 0:
    print "Couldn't connect to yahoo trading database"
else:
    dates = [q[0] for q in quotes]
    y = [q[1] for q in quotes]
    for date in dates:
        x.append(datetime.fromordinal(int(date))\
                .strftime('%Y-%m-%d')) # Plotly timestamp format
    ma = moving_average(y, 10)
5

Hướng dẫn generate html python - tạo html python