12.Plotly套件
plotly | Graphing Libraries
Chapter Summary
-
介紹
-
安装
-
開始使用bubble chart
-
Interactive graphing
• Discrete color and continuous color
-
Facet plots
-
Plotly Express
-
Matplotlib vs Plotly
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 之上,非常適合構建和部署具有定製使用者介面的數據應用程式。它特別適合任何與數據打交匯的人。
安装
-
Current version 5.13.1
-
Install using PIP
pip install plotly
- Import plotly.express
import plotly.express as px
plotly | Graphing Libraries
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.
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.
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()
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
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()
Customized symbol
Customized the symbol with .update_trace()
Linear Regression Line
fig = px.scatter(tips, x="total_bill", y="tip", trendline="ols")
fig.show()
Hover on the line, you can see the line function and
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
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()
facet_row 用於顯示行基數上的差異。
facet_row 這裏顯示了 lunch and dinner.
Facet plot - facet_col_wrap
facet_col_wrap is the column per row argument. 這可以應用於其他類型的繪圖。
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 是上半部分的中位數。
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()
| country | continent | year | lifeExp | pop | gdpPercap | iso_slpha | iso_num |
| 65 | Australia | Oceania | 1977 | 73.49 | 14074100 | 18334.19751 | AUS 36 |
| 64 | Australia | Oceania | 1972 | 71.93 | 13177000 | 16788.62948 | AUS 36 |
| 60 | Australia | Oceania | 1952 | 69.12 | 8691212 | 10039.59564 | AUS 36 |
⚠️ 本頁有 1 段未能本地執行(#1: NameError: name 'df_stock' is not defined),原因見 OCR_run_report.md
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.
Large range variables
在某些情況下,某些變數中的值可能比其他變數大得多。
很難在規模上視覺化。
GoldSpot: $16xx.xx
Zijin: $3.xx
Zhaojin: $13.xx
⚠️ 本頁有 1 段未能本地執行(#1: - passing
format='mixed', and the format will be inferred for ea),原因見 OCR_run_report.md
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 调整中的值 规格. 同様的想法也適用於:x-axis (然後使用 =True).
px.pie - Pie Chart
fig = px.pie(tips, values='tip', names='day')
fig.show()
Values: 數值數據
Names: 類別數據
px.sunburst - Sunburst of a rectangular DF
fig = px.sunburst(tips, path=['day', 'time', 'sex'], values='total_bill')
fig.show()
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()
跟 px.funnel_area, 每一行的DataFrame 表示為漏門的一個階段。
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
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()
⚠️ 本頁有 1 段未能本地執行(#1: AttributeError: module 'plotly.express.data' has no attribute 'spamind),原因見 OCR_run_report.md
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)
自定義地理
散點圖
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, 按其值加權。
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.
3 df_exp = px.data.gapminder().query('year=2007')
2 df_exp.sample(5)
| country | continent | year | lifeExp | pop | gdpPercap | iso_alpha | iso_num | |
| 1391 | Slovenia | Europe | 2007 | 77.926 | 2009245 | 25768.257590 | SVN | 705 |
| 179 | Brazil | Americas | 2007 | 72.390 | 190010647 | 9065.800825 | BRA | 76 |
| 899 | Liberia | Africa | 2007 | 45.678 | 3193042 | 414.507341 | LBR | 430 |
px.parallel_coordinates
在一個parallel coordinates
plot with
px.parallel_coordinates,
每一行的 DataFrame 由 polyline
標記遍曆一組平行軸,每個平
行軸對應一個維度。
def iris.samples():
| sepal_length | sepal_width | petal_length | petal_width | species | species_ed | |
| 23 | 5.1 | 3.3 | 1.7 | 0.5 | sealosa | 1 |
| 26 | 5.2 | 3.4 | 1.4 | 0.2 | sealosa | 1 |
| 138 | 6.0 | 3.0 | 4.8 | 1.8 | virginica | 3 |
| 32 | 5.2 | 4.1 | 1.5 | 0.1 | sealosa | 1 |
| 66 | 5.8 | 3.0 | 4.5 | 1.5 | vesicolor | 2 |
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
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
| Features | matplotlib | iitl plotly | Graphing Libraries |
| Syntax | Complex and lengthy | Shorter code and simple structure in px |
| Visual Design | Standard output and full range of plots | Publication style output with interactive functions |
| Popularity | Popular in data science | User number is growing fast |
| Advance Function | Various plots with standard function | Additional advance function available |
| Coding Requirement | Comparatively simple to use | Skilful coding on advance function such as live data on Dash |
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
12.Plotly套件 Part 2
plotly | Graphing Libraries
Recap
在上一章中,我們學到了
-
Bubble chart
-
Interactive graphing
• Discrete colour and continuous colour
-
Facet plots
-
Plotly Express
-
Matplotlib vs Plotly
plotly | Graphing Libraries
Chapter Summary
• Time Series Data and Plotly iii plotly | Graphing Libraries
• Series.isna, dropna, fillna, df.rank
- Range slider
• Multiple plot with graph_objects
-
Candlestick chart
-
OHLC chart
Time Series Data
在第 8 章中Pandas part 2, 我們瞭解到, time series data 是通過重複測量獲得的觀測值隨著時間的流逝的集合. 在圖形上繪製點, 並將其中一個軸 (通常x-axis) 將永遠是時間。
時間序列數據是許多不同領域中結構化數據的重要形式,例如金融、經濟學、生態學、神經科學、和物理。
時間序列繪圖 - 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
API data from WorldBank
首先import wbapi as wb. 然後我們搜索'hong kong'
import wbgapi as wb
wb.search('hong kong')
Country-Series
| ID | Name | Field |
| CHN-SG.POP.MIGR.FE.ZS | China-Female migrants (% of international migrant stock) | Country-Series ...For statistic Series |
| CHN-SM.POP.TOTL | China-International migrant stock, total | Country-Series ...using model Special , |
| CHN-SP.ADO.TFRT | China-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() | ||||
| id | name | code | concepts lastupdated | |
| 1 | Doing Business | DBS | 3 2021-08-18 | |
| 2 | World Development Indicators | WDI | 3 2023-03-30 | |
| 3 | Worldwide Governance Indicators | WGI | 3 2022-09-23 | |
| 5 | Subnational Malnutrition Database | SNM | 3 2016-03-21 | |
| 6 | International Debt Statistics | IDS | 4 2022-12-06 | |
wb.economy.info()
| GUY | Guyana | LCN | UMC |
| HIC | High income | ||
| HKG | Hong Kong SAR, China | EAS | HIC |
| HND | Honduras | LCN | LMC |
wb.series.info()
| id | value |
| AG.AGR.TRAC.NO | Agricultural machinery, tractors |
| AG.CON.FERT.PT.ZS | Fertilizer consumption (% of fertilizer production) |
| AG.CON.FERT.ZS | Fertilizer consumption (kilograms per hectare of arable land) |
| AG.LND.AGRI.K2 | Agricultural land (sq. km) |
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
⚠️ 本頁有 1 段未能本地執行(#1: NameError: name 'wb' is not defined),原因見 OCR_run_report.md
WorldBank API Usage info
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
| Country | 1960 | 1961 | 1962 | 1963 | 1964 | 1965 | 1966 | 1967 | 1968 | ... | 2012 | |
| economy | ||||||||||||
| CHE | Switzerland | 1787.360348 | 1971.316323 | 2131.391652 | 2294.182847 | 2501.293190 | 2620.475547 | 2784.733548 | 2960.722586 | 3121.889031 | ... | 85836.207677 |
| URY | Uruguay | 491.213493 | 604.176627 | 659.611697 | 587.006885 | 744.879993 | 705.398553 | 668.328011 | 584.850133 | 578.588983 | ... | 15206.87262 |
| NLD | Netherlands | 1068.784587 | 1159.392357 | 1240.677894 | 1328.036649 | 1541.947365 | 1708.096356 | 1835.801424 | 1991.360686 | 2185.248659 | ... | 50070.14160 |
| DNK | Denmark | NaN | NaN | NaN | NaN | NaN | NaN | 2487.136181 | 2700.746290 | 2776.135390 | ... | 58507.50805 |
| FRA | France | 1333.881573 | 1430.434624 | 1685.735311 | 1758.856659 | 1928.999402 | 2060.299715 | 2209.000173 | 2363.669669 | 2553.975843 | ... | 40870.85236 |
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$)
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
| ZWE | Zimbabwe | 276.643363 |
| ZMB | Zambia | 228.567399 |
| YEM | Yemen, Rep. | NaN |
| PSE | West Bank and Gaza | NaN |
| VIR | Virgin 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
| ZWE | Zimbabwe | 276.643363 |
| ZMB | Zambia | 228.567399 |
| YEM | Yemen, Rep. | 0.000000 |
| PSE | West Bank and Gaza | 0.000000 |
| VIR | Virgin 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
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 | |||
| USA | United States | 3007.123445 | 1.0 |
| NZL | New Zealand | 2312.949992 | 2.0 |
| CAN | Canada | 2259.250511 | 3.0 |
| LUX | Luxembourg | 2242.015817 | 4.0 |
| SWE | Sweden | 2114.002973 | 5.0 |
我們添加一個 Rank 列和.rank() 基於GDP. ascending=False 表示排名頂部的最大數位。這種排名過程在數據分析中經常使用。
1 df_1960.loc[df_1960.index=="HKG"]
economy
| HKG | Hong Kong SAR, China | 424.056554 | 34.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
| Date | Open | High | Low | Close | Adj Close | Volume |
| 2013-01-02 | 3.140000 | 3.182500 | 3.127500 | 3.180000 | 2.936782 | 47883600 |
| 2013-01-03 | 3.180000 | 3.217500 | 3.145000 | 3.182500 | 2.939091 | 29888800 |
⚠️ 本頁有 1 段未能本地執行(#1: NameError: name 'df_1960' is not defined),原因見 OCR_run_report.md
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$)
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 Close | Close | High | ||||
| NVDA | TSM | NVDA | TSM | NVDA | TSM | |
| Date | ||||||
| 2013-01-02 | 2.936782 | 13.400276 | 3.180000 | 18.100000 | 3.182500 | 18.1200 |
| 2013-01-03 | 2.939090 | 13.392871 | 3.182500 | 18.090000 | 3.217500 | 18.299 |
| 2013-01-04 | 3.036060 | 13.296628 | 3.287500 | 17.959999 | 3.297500 | 18.1200 |
| 2013-01-07 | 2.948326 | 13.104136 | 3.192500 | 17.700001 | 3.295000 | 17.860 |
| 2013-01-08 | 2.883680 | 12.985683 | 3.122500 | 17.540001 | 3.210000 | 17.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']]
| NVDA | TSM | |
| Date | ||
| 2013-01-02 | 3.180000 | 18.100000 |
| 2013-01-03 | 3.182500 | 18.090000 |
| 2013-01-04 | 3.287500 | 17.959999 |
| 2013-01-07 | 3.192500 | 17.700001 |
| 2013-01-08 | 3.122500 | 17.540001 |
1 df_chip['Close']['NVDA']
| Date | |
| 2013-01-02 | 3.180000 |
| 2013-01-03 | 3.182500 |
| 2013-01-04 | 3.287500 |
| 2013-01-07 | 3.192500 |
| 2013-01-08 | 3.122500 |
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
⚠️ 本頁有 1 段未能本地執行(#1: NameError: name 'df_chip' is not defined),原因見 OCR_run_report.md
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 Close | Close | ||
| NVDA | TSM | NVDA | TSM |
| Date | |||
| 2017-04-07 | 24.760082 | 27.380384 | 25.0825 32.869999 |
| 2019-02-08 | 36.764843 | 33.693165 | 37.0425 37.790001 |
| 2017-02-21 | 27.376019 | 26.930569 | 27.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
| Open | High | Low | Close | Adj Close | Volume | |
| Date | ||||||
| 2022-09-01 | 156.639999 | 158.419998 | 154.669998 | 157.960007 | 157.457993 | 74229900 |
| 2022-09-02 | 159.750000 | 160.360001 | 154.970001 | 155.809998 | 155.314819 | 76957800 |
| 2022-09-06 | 156.470001 | 157.089996 | 153.690002 | 154.529999 | 154.038879 | 73714800 |
| 2022-09-07 | 154.820007 | 156.669998 | 153.610001 | 155.960007 | 155.464355 | 87449600 |
| 2022-09-08 | 154.639999 | 156.360001 | 152.679993 | 154.460007 | 153.969116 | 84923800 |
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$
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()
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$
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
| Date | Open | High | Low | Close | Adj Close | Volume |
| 2022-01-03 | 144.475494 | 145.550003 | 143.502502 | 145.074493 | 145.074493 | 25214000 |
| 2022-01-04 | 145.550507 | 146.610001 | 143.816147 | 144.416504 | 144.416504 | 22928000 |
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
| Date | Open | High | Low | Close | Adj Close | Volume | MA20 | EMA20 |
| 2022-01-03 | 144.475494 | 145.550003 | 143.502502 | 145.074493 | 145.074493 | 25214000 | NaN | 145.074493 |
| 2022-01-04 | 145.550507 | 146.610001 | 143.816147 | 144.416504 | 144.416504 | 22928000 | NaN | 145.011828 |
| 2022-01-05 | 144.181000 | 144.298004 | 137.523499 | 137.653503 | 137.653503 | 49642000 | NaN | 144.311035 |
| 2022-01-06 | 137.497498 | 139.686005 | 136.763504 | 137.550995 | 137.550995 | 29050000 | NaN | 143.667222 |
| 2022-01-07 | 137.904999 | 138.254745 | 135.789001 | 137.004501 | 137.004501 | 19408000 | NaN | 143.032677 |
| … | … | … | … | … | … | … | … | … |
| 2022-12-23 | 87.620003 | 90.099998 | 87.620003 | 89.809998 | 89.809998 | 17815000 | 94.423999 | 92.968646 |
| 2022-12-27 | 89.309998 | 89.500000 | 87.535004 | 87.930000 | 87.930000 | 15470900 | 94.007999 | 92.488775 |
| 2022-12-28 | 87.500000 | 88.519997 | 86.370003 | 86.459999 | 86.459999 | 17879600 | 93.558999 | 91.914606 |
| 2022-12-29 | 87.029999 | 89.364998 | 86.989998 | 88.949997 | 88.949997 | 18280700 | 92.933999 | 91.632262 |
| 2022-12-30 | 87.364998 | 88.830002 | 87.029999 | 88.730003 | 88.730003 | 19190300 | 92.306499 | 91.355857 |
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", xaxis_rangeslider_visible=True, width=1000, height=800) fig.show()
Candlestick close with MA20 & EMA20 line
Critics on MA and EMA
移動平均線數據也用於財務會計和行銷分析。這是一種比較特定時期歷史數據的簡單方法。
指數移動平均線對近期數據敏感,因此平均週期不應過長,否則毫無意義。
雖然這兩種方法經常被所謂的專欄作家用於預測,但除非你能證明趨勢在所有情況下的正確性達到95%,否則它不是統計方法。
我們可能會在後面的章節中發現這一點。
Chapter Wrap Up
Plotly Graph Object 是自定義繪圖的庫。在繪圖之前,請確保數據位於Pandas DF(免麻煩)和沒有NaN.
逐步建立您的地塊,並參考官方檔。
API data format (json) and API pypi library 使數據更易於訪問。現在不需要經常在網上潦草。
Reference
Official Website:
https://plotly.com/python/
Plotly Graph Objects:
https://plotly.com/python/graph-objects/
WorldBank API:
-
https://blogs.worldbank.org/opendata/introducing-wbgapi-new-python-package-accessing-world-bank-data
-
https://nbviewer.org/github/tqherzog/wbgapi/blob/master/examples/wbgapi-cookbook.ipynb
-
https://pypi.org/project/wbgapi/
GitHub Open Source Code:
https://github.com/plotlv/plotlv.py
ii plotly | Graphing Libraries