p.359

12.Plotly套件

plotly | Graphing Libraries

Chapter Summary

• Discrete color and continuous color

p.360

Introduction

Plotly : Open Source Graphing Libraries

Plotly 的 Python 繪圖庫製作互動式、出版質量的圖表。在本章中,我們將重點介紹此模組的數據分析。

plotly | Graphing Libraries

Plotly : Dash Open Source Dash Enterprise

Dash 是原始的低代碼框架,用於在 Python、R、Julia 和 F#(實驗性)中快速構建數據應用程式。

Dash 建立在 Plotly.js 和 React.js 之上,非常適合構建和部署具有定製使用者介面的數據應用程式。它特別適合任何與數據打交匯的人。

安装

pip install plotly

import plotly.express as px

plotly | Graphing Libraries

p.361

Getting start

我們將使用一些plotly內建樣本DataFrame,如iris for plot demo.

import plotly.express as px
df = px.data.iris()
df.sample(5)
sepal_length sepal_width petal_length petal_width species species_id
47 4.6 3.2 1.4 0.2 setosa 1
26 5.0 3.4 1.6 0.4 setosa 1
143 6.8 3.2 5.9 2.3 virginica 3
49 5.0 3.3 1.4 0.2 setosa 1
67 5.8 2.7 4.1 1.0 versicolor 2

px.scatter - bubble chart

import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", size='petal_length', hover_data=['petal_width'])
fig.show()

沿著繪圖移動指標以查看內容互動表示在plotly.

p.361 互動圖表(可點圖例切換物種、縮放、懸停)

p.362

Interactive graphing

species setosa versicolor virginica

您可以切換物種以分離一種或多種物種。

Drag the x-axis left or right

發現互動式圖表

Use the Pan to drag the graph

Setting size and colour with column names

import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", size='petal_length', hover_data=['petal_width'])
fig.show()

Scatter plots with variable-sized

circular markers are often known

as bubble charts. 请注意,

colour and size 數據將添加到懸停資訊

中。您可以添加其他列以使

用 hover_data argument of px.scatter.

p.363

Discrete Color and Continuous Color

tip = px.data.tips()
tip.info()
<class "pandas.core.frame.DataFrame">
RangeIndex: 244 entries, 0 to 243
Data columns (total): 3 columns
<h3 id="h-363-Column-Non-Null-Count-Dtype">Column Non-Null Count Dtype</h3>
0 total_bill 244 non-null float64
1 tip 244 non-null float64
2 sex 244 non-null object
3 @ smoker 244 non-null object
4 day 244 non-null object
5 time 244 non-null object
6 size 244 non-null int64
dtype: float64(2), int64(1), object(4)
memory usage: 13.5+ KB

Plotly 將數據值分配

給discrete colors if the data is non- numeric.

df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", color="smoker", title="String 'smoker' values mean discrete colors")
fig.show()

p.363 互動圖表(Plotly:可縮放、懸停、切換圖例)

String 'smoker' values mean discrete colors

tips = px.data.tips()
tips.info()
<class "pandas.core.frame.DataFrame">
RangeIndex: 244 entries, 0 to 243
Data columns (total 7 columns):
Column Non-Null Count Dtype
total_bill 244 non-null float64
1 sex 244 non-null object 10
2 smoker 244 non-null object
4 day 244 non-null object
5 time 244 non-null object
6 @size 244 non-null int64
dtypes: float64(2), int64(1), object(4)
memory usage: 13.5+ KB

如果數據是numeric, the color 將自動被考慮continuous.

1 fig = px.scatter(df, x="total_bill", y="tip", color="size", title="Numeric 'size' values mean continuous color")

Numeric 'size' values mean continuous color

p.364

Symbol argument

The symbol argument 可以映射到列並更改形狀。

The symbol 也可以自定義。

df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", symbol="species")
fig.show()

p.364 互動圖表(Plotly:可縮放、懸停、切換圖例)

Customized symbol

Customized the symbol with .update_trace()

p.365

Linear Regression Line

fig = px.scatter(tips, x="total_bill", y="tip", trendline="ols")
fig.show()

p.365 互動圖表(Plotly:可縮放、懸停、切換圖例)

Hover on the line, you can see the line function and R2

1 df_gold.sample(3)

GoldSpot Zijin Zhaojin

Date

2013-09-05 1367.48 1.96 7.34

2014-01-20 1254.35 1.70 4.66

2014-07-09 1327.83 1.77 4.72

繪製兩條回歸線Zjjin-vs-Gold and Zhaojin-vs-Gold.

您可能會看到R² of each line. 為了更好地展示,您可以繪製 資產的log return 而不是價格。

fig = px.scatter(df_gold, x="GoldSpot", y=["zijin", "Zhaojin"], trendline="ols")  
fig.show()

⚠️ 本頁有 1 段未能本地執行(#2: NameError: name 'df_gold' is not defined),原因見 OCR_run_report.md

p.366

Facet plots - facet_col

Facet plots are figures made up of multiple subplots which have the same set of axes,其中每個子圖顯示數據的一個子集。facet_col用於將值與其他值區分開來。

1 fig = px.scatter(tips, x="total_bill", y="tip", color="smoker", facet_col="sex")

3 fig.show()

Facet plots - facet_row

fig = px.scatter(tips, x="total_bill", y="tip", color="smoker", facet_col="sex", facet_row="time")
fig.show()

p.366 互動圖表(Plotly:可縮放、懸停、切換圖例)

facet_row 用於顯示行基數上的差異。

facet_row 這裏顯示了 lunch and dinner.

p.367

Facet plot - facet_col_wrap

facet_col_wrap is the column per row argument. 這可以應用於其他類型的繪圖。

p.367 原掃描圖
p.367 原掃描圖

px.box - Box plot

1 fig = px.box(tips, x="day", y="total_bill", color="smoker")

2 fig.update_traces(quartilemethod="exclusive") # or "inclusive", or "linear" by default

3 fig.show()

The exclusive algorithm uses the median 將有序數據集分成兩半。如果樣本是奇數,則它不包括任一半的中位數。Q1 是下半部分的中位數,Q3 是上半部分的中位數。

p.367 原掃描圖
p.367 原掃描圖

p.368

Adding lines and rectangles to facet plots

fig = px.line(df_stock, facet_col="company", facet_col_wrap=2)
fig.add_hline(y=1, line_dash="dot",
    annotation_text="Jan 1, 2018 baseline",
    annotation_position="bottom right")
fig.add_vrect(x0="2018-09-24", x1="2018-12-18", col=1,
    annotation_text="decline", annotation_position="top left",
    fillcolor="green", opacity=0.25, line_width=0)
fig.show()

可以使用以下方法將標記的水平線和垂直線以及矩形添加到分面圖中

.add_hline(), add_vline(), add_hrect() or .add_vrect().預設 row and col values 是 "all"但這可以被覆蓋,就像下面的矩形一樣,它只出現在第一列中。

Line plots

1 df_life = px.data.gapminder().query("continent == 'Oceania'")

2 fig = px.line(df_life, x='year', y='lifeExp', color='country', markers=True)

3 fig.show()

countrycontinentyearlifeExppopgdpPercapiso_slphaiso_num
65AustraliaOceania197773.491407410018334.19751AUS 36
64AustraliaOceania197271.931317700016788.62948AUS 36
60AustraliaOceania195269.12869121210039.59564AUS 36

⚠️ 本頁有 1 段未能本地執行(#1: NameError: name 'df_stock' is not defined),原因見 OCR_run_report.md

p.369

Line plots with Datetime index

df_gold = pd.read_csv("gold_goldstock.csv")
df_gold['Date'] = pd.to_datetime(df_gold['Date'], dayfirst=True)
df_gold = df_gold.set_index('Date')
fig = px.line(df_gold, x=df_gold.index, y=['Zijin', 'Zhaojin'], title='Gold Stock')
fig.show()

因為 plotly 認識 DF in Pandas format, the index 將不是 Date 如果設置為 index. 同樣的事情也在 Numpy or 其他 Library.

p.369 原掃描圖
p.369 原掃描圖

Large range variables

在某些情況下,某些變數中的值可能比其他變數大得多。

很難在規模上視覺化。

GoldSpot: $16xx.xx

Zijin: $3.xx

Zhaojin: $13.xx

p.369 原掃描圖
p.369 原掃描圖

⚠️ 本頁有 1 段未能本地執行(#1: - passing format='mixed', and the format will be inferred for ea),原因見 OCR_run_report.md

p.370

Enable log scale

fig = px.line(df_gold, x=df_gold.index, y=['GoldSpot', "zijin", "Zhaojin'], log_y=True, title='Gold Stock')
fig.show()

Set log_y=True 调整中的值 log10 规格. 同様的想法也適用於:x-axis (然後使用 logx=True).

px.pie - Pie Chart

fig = px.pie(tips, values='tip', names='day')
fig.show()

p.370 互動圖表(Plotly:可縮放、懸停、切換圖例)

Values: 數值數據

Names: 類別數據

p.371

px.sunburst - Sunburst of a rectangular DF

fig = px.sunburst(tips, path=['day', 'time', 'sex'], values='total_bill')
fig.show()

p.371 互動圖表(Plotly:可縮放、懸停、切換圖例)

Sunburst 是層次結構子類別的餅形圖。

Path 定義每個層次結構的級別。

px.funnel_area - Funnel plot

fig = px.funnel_area(names=['Site Visitor', "Product View", "Wish List", "Shopping Cart", "Order Paid"], values=[500, 200, 50, 35, 201])
fig.show()

p.371 互動圖表(Plotly:可縮放、懸停、切換圖例)

跟 px.funnel_area, 每一行的DataFrame 表示為漏門的一個階段。

p.372

px.bar - Bar Chart

df_pop = px.data.gapminder().query("continent == 'Europe' and year == 2007 and pop > 2.e6")
fig = px.bar(df_pop, ys='pop', xs='country', text_auto='.2s',
    title="Default: various text sizes, positions and angles")
fig.show()

默認情況下, Plotly 將縮放和旋轉文本標籤以最大化可見標籤的數量,這可以產生各種文本角度和大小和在同一圖中的位置。

The textfont, textposition 和 textangle 跟蹤屬性可用於控制 這些屬性。

Default: various text sizes, positions and angles

p.372 原掃描圖
p.372 原掃描圖

3D scatter plot

4 行代碼用於建立 3D
互動式圖形 .px

1 df_iris = px.data.iris()

2 fig = px.scatter_3d(df_iris, x='sepal_length', y='sepal_width', z='petal_width', color='species')

4 fig.show()

p.372 原掃描圖
p.372 原掃描圖

⚠️ 本頁有 1 段未能本地執行(#1: AttributeError: module 'plotly.express.data' has no attribute 'spamind),原因見 OCR_run_report.md

p.373

px.scatter_geo - Geographical Scatter Plot

df_geo = px.data.gapminder().query("year == 2007")
fig = px.scatter_geo(df_geo, locations="iso_alpha", color="continent", # which column to use to set the color of markers
hover_name="country", # column added to hover information
size="pop", # size of markers
projection="natural earth")

▶ 本地執行結果(Python 3.12 / matplotlib 3.11)

p.373 執行結果
p.373 執行結果

自定義地理

散點圖

px.treemap

import numpy as np
fig = px.treemap(df_geo, path=[px.Constant("world"), 'continent', 'country'], values='pop', color='lifeExp', hover_data=[iso_alpha], color=continuous_scale='RdBu', color=continuous_midpoint=np.merge(df_geo['lifeExp'], weights=df_geo['pop'])) fig.update_layout(margin = dict[t=50, 1=25, r=25, b=25])
fig.show()

If a color argument is passed, 節點的顏色計算為color values of its children, 按其值加權。

p.374

px.choropleth - Choropleth Map

fig = px.choropleth(df_exp, locations="iso_alpha", color="lifeExp", # lifeExp is a column of gapminder hover name="country", # column to add to hover information color "continuous scale=px.colors.sequential.Plasma)
fig.show()

In a choropleth map, 每行data_frame 由colored region mark on a map.

p.374 原掃描圖
p.374 原掃描圖

3 df_exp = px.data.gapminder().query('year=2007')
2 df_exp.sample(5)
countrycontinentyearlifeExppopgdpPercapiso_alphaiso_num
1391SloveniaEurope200777.926200924525768.257590SVN705
179BrazilAmericas200772.3901900106479065.800825BRA76
899LiberiaAfrica200745.6783193042414.507341LBR430

px.parallel_coordinates

在一個parallel coordinates

plot with

px.parallel_coordinates,

每一行的 DataFrame 由 polyline

標記遍曆一組平行軸,每個平

行軸對應一個維度。

def iris.samples():

sepal_lengthsepal_widthpetal_lengthpetal_widthspeciesspecies_ed
235.13.31.70.5sealosa1
265.23.41.40.2sealosa1
1386.03.04.81.8virginica3
325.24.11.50.1sealosa1
665.83.04.51.5vesicolor2

Can you figure out the idea of machine learning in Object Recognition?

⚠️ 本頁有 1 段未能本地執行(#2: ValueError: cannot assign without a target object),原因見 OCR_run_report.md

p.375

Graph Objects

The plotly.graph_objects module (typically imported as go) contains an automatically-generated hierarchy of Python classes which represent non-leaf nodes in this figure schema.

The term "graph objects" refers to instances of these classes.

Functions in Plotly Express, which is the recommended entry-point into the plotly library, are all built on top of graph objects, and all return instances of plotly.graph_objects.Figure.

You might see code one public resources like "import plotly.graph_objects as go"

This should be either earlier version plotly code or tend to customize some of the attributes, parameter, or setting.

Matplotlib vs Plotly

Featuresmatplotlibiitl plotly | Graphing Libraries
SyntaxComplex and lengthyShorter code and simple structure in px
Visual DesignStandard output and full range of plotsPublication style output with interactive functions
PopularityPopular in data scienceUser number is growing fast
Advance FunctionVarious plots with standard functionAdditional advance function available
Coding RequirementComparatively simple to useSkilful coding on advance function such as live data on Dash
p.376

Reference

Official Website:

https://plotly.com/python/

Plotly Express:

https://plotly.com/python/plotly-express/

GitHub Open Source Code:

https://github.com/plotly/plotly.py

plotly | Graphing Libraries

p.377

12.Plotly套件 Part 2

plotly | Graphing Libraries

Recap

在上一章中,我們學到了

• Discrete colour and continuous colour

plotly | Graphing Libraries

p.378

Chapter Summary

• Time Series Data and Plotly iii plotly | Graphing Libraries

• Series.isna, dropna, fillna, df.rank

• Multiple plot with graph_objects

Time Series Data

在第 8 章中Pandas part 2, 我們瞭解到, time series data 是通過重複測量獲得的觀測值隨著時間的流逝的集合. 在圖形上繪製點, 並將其中一個軸 (通常x-axis) 將永遠是時間。

時間序列數據是許多不同領域中結構化數據的重要形式,例如金融、經濟學、生態學、神經科學、和物理。

p.379

時間序列繪圖 - Plotly

時間序列可以使用以下任一方式表示plotly.express 功能

(px.line, px.scatter, px.bar etc) or plotly.graph_objects Charts 物件

(go.Scatter, go.Bar etc).

API data from WorldBank

許多組織使用以下方式打開他們的資料庫 API, WorldBank.org 是其中之一.也支援 Python 庫。

pip install wbgapi

Collecting wbgapi

Downloading wbgapi-1.0.12-py3-none-any.whl (36 Requirement already satisfied: PyYAML in /Users/1 api) (6.0)

Collecting tabulate

Downloading tabulate-0.9.0-py3-none-any.whl (3! Requirement already satisfied: requests in /User: bgapi) (2.28.1)

wbgapi 1.0.12

pip install wbgapi

https://blogs.worldbank.org/opendata/introducing-wbgapi-new-python-package-accessing-world-bank-data

p.380

API data from WorldBank

首先import wbapi as wb. 然後我們搜索'hong kong'

import wbgapi as wb

wb.search('hong kong')

Country-Series

IDNameField
CHN-SG.POP.MIGR.FE.ZSChina-Female migrants (% of international migrant stock)Country-Series ...For statistic Series
CHN-SM.POP.TOTLChina-International migrant stock, totalCountry-Series ...using model Special ,
CHN-SP.ADO.TFRTChina-Adolescent fertility rate (births per 1,000 women ages 15-19)Country-Series The data

幾十年來有很多數據,組

織良好且免費。而且它在

Pandas DataFrame 中提

供,甚至比許多付費服務

都要好。

THE WORLD BANK

ISRO - IDA

wb.source.info()
idnamecodeconcepts lastupdated
1Doing BusinessDBS3 2021-08-18
2World Development IndicatorsWDI3 2023-03-30
3Worldwide Governance IndicatorsWGI3 2022-09-23
5Subnational Malnutrition DatabaseSNM3 2016-03-21
6International Debt StatisticsIDS4 2022-12-06

wb.economy.info()

GUYGuyanaLCNUMC
HICHigh income
HKGHong Kong SAR, ChinaEASHIC
HNDHondurasLCNLMC

wb.series.info()

idvalue
AG.AGR.TRAC.NOAgricultural machinery, tractors
AG.CON.FERT.PT.ZSFertilizer consumption (% of fertilizer production)
AG.CON.FERT.ZSFertilizer consumption (kilograms per hectare of arable land)
AG.LND.AGRI.K2Agricultural land (sq. km)
p.381

Capture Hong Kong GDP data and plot via plotly

拉動香港的GDP數據。由於列是以年為單位的,我們使用T(轉置)將它們切換為行。

<h3 id="h-381-HongKong-GDP-per-capita-current-US">HongKong GDP per capita (current US$)</h3>
df = wb.data.DataFrame(['NY.GDP.PCAP.CD'], ['HKG']).T
df
import plotly.express as px
fig = px.bar(df, x=df.index, y="HKG", title="HongKong GDP per capita (current US$)")
    ).update_layout(xaxis_title="GDP per capita US$", yaxis_title="Year")
fig.show()

Hong Kong GDP per Capita

p.381 原掃描圖
p.381 原掃描圖

⚠️ 本頁有 1 段未能本地執行(#1: NameError: name 'wb' is not defined),原因見 OCR_run_report.md

p.382

WorldBank API Usage info

Google

world bank api python

All

Images

News

Videos

Books

More

Tools

About 13,500,000 results (0.33 seconds)

World Bank

https://blogs.worldbank.org/opendata/introducing-wb...

:

Introducing WBGAPI: A new python package for accessing ...

17 Feb 2021 — 1. WBGAPI makes databases easier to understand and use. The World Bank

API sometimes gives the illusion that all indicators reside in one big ...

https://blogs.worldbank.org/opendata/introd

ucing-wbgapi-new-python-package-

accessing-world-bank-data

THE WORLD BANK

IBRD·IDA

High Income Economy GDP

Pull High Income Countries.

1 # High Income Economy GDP

2 df_hic = wb.data.DataFrame('NY.GDP.PCAP.CD', economy=wb.income.members('HIC'), numericTimeKeys=True, labels=True)

3 df_hic

Country196019611962196319641965196619671968...2012
economy
CHESwitzerland1787.3603481971.3163232131.3916522294.1828472501.2931902620.4755472784.7335482960.7225863121.889031...85836.207677
URYUruguay491.213493604.176627659.611697587.006885744.879993705.398553668.328011584.850133578.588983...15206.87262
NLDNetherlands1068.7845871159.3923571240.6778941328.0366491541.9473651708.0963561835.8014241991.3606862185.248659...50070.14160
DNKDenmarkNaNNaNNaNNaNNaNNaN2487.1361812700.7462902776.135390...58507.50805
FRAFrance1333.8815731430.4346241685.7353111758.8566591928.9994022060.2997152209.0001732363.6696692553.975843...40870.85236
p.383

Select top 30 largest GDP in 2021 and transpose the years columns to rows.

1 df_hic = df_hic.nlargest(30, 2021).T

fig = px.line(df_hic, x=df_hic.index, y=df_hic.columns, title="High Income Economy GDP Per Capita (US$)" ).update_layout(xaxis_title="Year", yaxis_title="GDP per capita US$") fig.show()

Hong Kong ranked Top 23 GDP in 2021

High Income Economy GDP Per Capita (US$)

p.383 原掃描圖
p.383 原掃描圖

p.384

Hong Kong GDP rank in 1960

df_1960 = wb.data.DataFrame('NY.GDP.PCAP.CD', skipAggs=True, time=1960, numericTimeKeys=True, labels=True)
df_1960

Country NY.GDP.PCAP.CD

economy

ZWEZimbabwe276.643363
ZMBZambia228.567399
YEMYemen, Rep.NaN
PSEWest Bank and GazaNaN
VIRVirgin Islands (U.S.)NaN

1 df_1960['NY.GDP.PCAP.CD'].isna().sum()

117

As there are NaN data in almost half the countries, we should not use dropna() to delete the data.

df_1960 = wb.data.DataFrame('NY.GDP.PCAP.CD', skipAggs=True, time=1960, numericTimeKeys=True, labels=True).fillna(0)
df_1960

Country NY.GDP.PCAP.CD

economy

ZWEZimbabwe276.643363
ZMBZambia228.567399
YEMYemen, Rep.0.000000
PSEWest Bank and Gaza0.000000
VIRVirgin Islands (U.S.)0.000000

We use fillna with zero to handle the NaN properly.

⚠️ 本頁有 2 段未能本地執行(#1: NameError: name 'wb' is not defined; #2: NameError: name 'wb' is not defined),原因見 OCR_run_report.md

p.385

Hong Kong GDP rank in 1960

df_1960['Rank'] = df_1960['NY.GDP.PCAP.CD'].rank(ascending=False)
df_1960.nlargest(5, 'NY.GDP.PCAP.CD')

Country NY.GDP.PCAP.CD Rank

economy
USAUnited States3007.1234451.0
NZLNew Zealand2312.9499922.0
CANCanada2259.2505113.0
LUXLuxembourg2242.0158174.0
SWESweden2114.0029735.0

我們添加一個 Rank 列和.rank() 基於GDP. ascending=False 表示排名頂部的最大數位。這種排名過程在數據分析中經常使用。

1 df_1960.loc[df_1960.index=="HKG"]

economy

HKGHong Kong SAR, China424.05655434.0

Filter the DF then we know Hong Kong rank top 34 in 1960.

Time Series plot with Range Slider

Pull finance data from yfinance library.

import yfinance as yf
nvda = yf.download("NVDA", start="2013-01-01", end="2023-01-01")
[**********100**********] 1 of 1 completed

1 nvda

DateOpenHighLowCloseAdj CloseVolume
2013-01-023.1400003.1825003.1275003.1800002.93678247883600
2013-01-033.1800003.2175003.1450003.1825002.93909129888800

⚠️ 本頁有 1 段未能本地執行(#1: NameError: name 'df_1960' is not defined),原因見 OCR_run_report.md

p.386

Time Series plot with Range Slider

fig = px.line(nvda, x=nvda.index, y=nvda['close'], title="NVidia Share Price (US$)") ).update_layout(yaxis_title="Share Price (close) US$") fig.update_xaxes(rangeslider_visible=True, rangeselector=dict( buttons=list([ dict(count=1, label="12m", step="month", stepmode="backward"), dict(count=1, label="2y", step="year", stepmode="backward"), dict(count=1, label="YTD", step="year", stepmode="todate"), dict(step="all") ]))) fig.show()

NVidia Share Price (US$)

p.386 原掃描圖
p.386 原掃描圖

p.387

Multiple plots with graph_objects

We can import multiple stock data into a single DF, but pay attention to the columns.

df_chip = yf.download(['NVDA", "TSM"], start="2013-01-01", end="2023-01-01")
df_chip

[100100**********] 2 of 2

Adj CloseCloseHigh
NVDATSMNVDATSMNVDATSM
Date
2013-01-022.93678213.4002763.18000018.1000003.18250018.1200
2013-01-032.93909013.3928713.18250018.0900003.21750018.299
2013-01-043.03606013.2966283.28750017.9599993.29750018.1200
2013-01-072.94832613.1041363.19250017.7000013.29500017.860
2013-01-082.88368012.9856833.12250017.5400013.21000017.7195

1 df_chip.info()

<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 2518 entries, 2013-01-02 to 2022-12-30
Data columns (total 12 columns):
<h3 id="h-387-Column-Non-Null-Count-Dtype">Column Non-Null Count Dtype</h3>
(Adj Close, NVDA) 2518 non-null float64
(Adj Close, TSM) 2518 non-null float64
(Close, NVDA) 2518 non-null float64
(Close, TSM) 2518 non-null float64
(High, NVDA) 2518 non-null float64
(High, TSM) 2518 non-null float64
(Low, NVDA) 2518 non-null float64
(Low, TSM) 2518 non-null float64
(Open, NVDA) 2518 non-null float64
(Open, TSM) 2518 non-null float64
(Volume, NVDA) 2518 non-null int64
(Volume, TSM) 2518 non-null int64
dtypes: float64(10), int64(2)
memory usage: 255.7 KB

Access multiple series with a common column name

Access specific series like these.

1 df_chip['Close'][['NVDA','TSM']]

NVDATSM
Date
2013-01-023.18000018.100000
2013-01-033.18250018.090000
2013-01-043.28750017.959999
2013-01-073.19250017.700001
2013-01-083.12250017.540001

1 df_chip['Close']['NVDA']

Date
2013-01-023.180000
2013-01-033.182500
2013-01-043.287500
2013-01-073.192500
2013-01-083.122500
p.388

Multiple plots with graph_objects

為了更易於自定義設置,請使用 graph_objects library.

使用 for 循環繪製每隻股票。

import plotly.graph_objects as go
fig = go.Figure()
for i in df_chip['Close']:
    fig.add_scatter(x=df_chip.index, y=df_chip['Close'][i], name=i)
fig.update_layout(title="NVIDIA vs Taiwan Semiconductor Share Price", yaxis_title="Share Price (close) US$")
fig.show()

NVIDIA vs Taiwan Semiconductor Share Price

p.388 原掃描圖
p.388 原掃描圖

⚠️ 本頁有 1 段未能本地執行(#1: NameError: name 'df_chip' is not defined),原因見 OCR_run_report.md

p.389

Close and Adj. Close

您可能會發現有兩種類型的 Close。調整後的收盤價為 weighted and adjusted 任何股票分割、股息支付、普通股數量增加或減少後的價格等。收盤價是實際的市場收盤價。為分析價值問題,比如收益和帳面價值如何影響股價,我們通常使用 Adj. Close.

1 df_chip.filter(regex='Close').sample(3)

為 technical analysis, especially taken Open, Hi, Low 考慮到因素,我們傾向於使用 Close。由於從未調整過 Open, Hi, Low.

Adj CloseClose
NVDATSMNVDATSM
Date
2017-04-0724.76008227.38038425.0825 32.869999
2019-02-0836.76484333.69316537.0425 37.790001
2017-02-2127.37601926.93056927.7675 32.330002

Candlestick Chart

Plotly 支援易於編碼的蠟燭圖.

df_a = yf.download("AAPL", start="2022-09-01", end="2023-01-01")
df_a

[100100]*1 of 1 completed

OpenHighLowCloseAdj CloseVolume
Date
2022-09-01156.639999158.419998154.669998157.960007157.45799374229900
2022-09-02159.750000160.360001154.970001155.809998155.31481976957800
2022-09-06156.470001157.089996153.690002154.529999154.03887973714800
2022-09-07154.820007156.669998153.610001155.960007155.46435587449600
2022-09-08154.639999156.360001152.679993154.460007153.96911684923800
p.390

Candlestick Chart

import plotly.graph_objects as go fig = go.Figure(data=[go.Candlestick(x=df_a.index, open=df_a['Open'], high=df_a['High'], low=df_a['Low'], close=df_a['Close']]).update_layout( title="Apple INC. Share Price (Close) US$", yaxis_title="Close Price US$") fig.show()

Apple INC. Share Price (Close) US$

p.390 原掃描圖
p.390 原掃描圖

p.391

Change candle color and disable rangeslider

如果我們想更改預設繪圖設置,我們可以定義如下。

import plotly.graph_objects as go
fig = go.Figure(data=[go.Candlestick(x=df_a.index,
                                 open=df_a['Open'],
                                 high=df_a['High'],
                                 low=df_a['Low'],
                                 close=df_a['Close'],
                                 increasing_line_color='blue', decreasing_line_color='red']).update_layout(
                                 title="Apple INC. Share Price (Close) US$",
                                 yaxis_title="Close Price US$",
                                 xaxis_rangeslider_visible=False)
fig.show()

p.391 原掃描圖
p.391 原掃描圖

p.392

OHLC chart

OHLC (open high low close) chart 類似於candlestick chart.

fig = go.Figure(data=go.Ohlc(x=df_a.index,
                                 open=df_a['Open'],
                                 high=df_a['High'],
                                 low=df_a['Low'],
                                 close=df_a['Close']).update_layout(
                                 title="Apple INC. Share Price (Close) US$",
                                 yaxis_title="Close Price US$",)
fig.show()

OHLC chart

Apple INC. Share Price (Close) US$

p.392 原掃描圖
p.392 原掃描圖

p.393

Moving Average and Exponential Moving Average

Moving Average (MA) 有時被稱為簡單移動平均線 (SMA),可能是最常用的指標。以及指數移動平均線 (EMA),這對近期股價很敏感。

df_g = yf.download("GOOG", start="2022-01-01", end="2023-01-01")
df_g
[*****100*****] 1 of 1 completed
DateOpenHighLowCloseAdj CloseVolume
2022-01-03144.475494145.550003143.502502145.074493145.07449325214000
2022-01-04145.550507146.610001143.816147144.416504144.41650422928000

Create MA20 and EMA20 series

創造 20 days MA and EMA 列。請注意,有20 NaN 在MA20,對於整體的數據分析,我們應該去掉所有的NaN 行。如果你MA20 on 2022-01-03,你應該從周圍拉取數據1個月前。

df_g['MA20'] = df_g['Close'].rolling(20).mean()
df_g['EMA20'] = df_g['Close'].ewm(span=20, adjust=False).mean()
df_g
DateOpenHighLowCloseAdj CloseVolumeMA20EMA20
2022-01-03144.475494145.550003143.502502145.074493145.07449325214000NaN145.074493
2022-01-04145.550507146.610001143.816147144.416504144.41650422928000NaN145.011828
2022-01-05144.181000144.298004137.523499137.653503137.65350349642000NaN144.311035
2022-01-06137.497498139.686005136.763504137.550995137.55099529050000NaN143.667222
2022-01-07137.904999138.254745135.789001137.004501137.00450119408000NaN143.032677
………………………
2022-12-2387.62000390.09999887.62000389.80999889.8099981781500094.42399992.968646
2022-12-2789.30999889.50000087.53500487.93000087.9300001547090094.00799992.488775
2022-12-2887.50000088.51999786.37000386.45999986.4599991787960093.55899991.914606
2022-12-2987.02999989.36499886.98999888.94999788.9499971828070092.93399991.632262
2022-12-3087.36499888.83000287.02999988.73000388.7300031919030092.30649991.355857
p.394

Candlestick close with MA20 & EMA20 line

1 df_g = df_g.dropna()

import plotly.graph_objects as go fig = go.Figure() fig.add_candlestick(x=df_g.index, open=df_g['Open'], high=df_g['High'], low=df_g['Low'], close=df_g['Close'], increasing_line_color='blue', decreasing_line_color='red', name='Close') fig.add_scatter(x=df_g.index, y=df_g['MA20'], name='MA20') fig.add_scatter(x=df_g.index, y=df_g['EMA20'], name='EMA20') fig.update_layout(title="Alphabet Inc. (GOOG) Share Price (Close) US",yaxistitle="ClosePriceUS", xaxis_rangeslider_visible=True, width=1000, height=800) fig.show()

Candlestick close with MA20 & EMA20 line

p.394 原掃描圖
p.394 原掃描圖

p.395

Critics on MA and EMA

移動平均線數據也用於財務會計和行銷分析。這是一種比較特定時期歷史數據的簡單方法。

指數移動平均線對近期數據敏感,因此平均週期不應過長,否則毫無意義。

雖然這兩種方法經常被所謂的專欄作家用於預測,但除非你能證明趨勢在所有情況下的正確性達到95%,否則它不是統計方法。

我們可能會在後面的章節中發現這一點。

Chapter Wrap Up

Plotly Graph Object 是自定義繪圖的庫。在繪圖之前,請確保數據位於Pandas DF(免麻煩)和沒有NaN.

逐步建立您的地塊,並參考官方檔。

API data format (json) and API pypi library 使數據更易於訪問。現在不需要經常在網上潦草。

p.396

Reference

Official Website:

https://plotly.com/python/

Plotly Graph Objects:

https://plotly.com/python/graph-objects/

WorldBank API:

GitHub Open Source Code:

https://github.com/plotlv/plotlv.py

ii plotly | Graphing Libraries

← 第 11 章 Seaborn 套件課程總覽第 13 章 數據分析專案:Storytelling →