使用altair绘制漂亮的股票价格趋势图, 直接上代码。
安装
!pip3 install altair
案例数据
这里使用vega_datasets中提供的数据做测试,返回的结果是dataframe类型的数据。
from vega_datasets import data
def get_data():
source = data.stocks()
source = source[source.date.gt("2004-01-01")]
return source
get_data()
symbol | date | price | |
---|---|---|---|
49 | MSFT | 2004-02-01 | 21.77 |
50 | MSFT | 2004-03-01 | 20.46 |
51 | MSFT | 2004-04-01 | 21.45 |
52 | MSFT | 2004-05-01 | 21.53 |
53 | MSFT | 2004-06-01 | 23.44 |
... | ... | ... | ... |
555 | AAPL | 2009-11-01 | 199.91 |
556 | AAPL | 2009-12-01 | 210.73 |
557 | AAPL | 2010-01-01 | 192.06 |
558 | AAPL | 2010-02-01 | 204.62 |
559 | AAPL | 2010-03-01 | 223.02 |
364 rows × 3 columns
完整代码
import altair as alt
import pandas as pd
from vega_datasets import data
from vega_datasets import data
def get_data():
source = data.stocks()
source = source[source.date.gt("2004-01-01")]
return source
def get_chart(df):
hover = alt.selection_single(
fields=["date"],
nearest=True,
on="mouseover",
empty="none",
)
lines = (
alt.Chart(df, title="股票价格趋势")
.mark_line()
.encode(
x="date",
y="price",
color="symbol",
# strokeDash="symbol",
)
)
# Draw points on the line, and highlight based on selection
points = lines.transform_filter(hover).mark_circle(size=65)
# Draw a rule at the location of the selection
tooltips = (
alt.Chart(df)
.mark_rule()
.encode(
x="yearmonthdate(date)",
y="price",
opacity=alt.condition(hover, alt.value(0.3), alt.value(0)),
tooltip=[
alt.Tooltip("date", title="日期"),
alt.Tooltip("price", title="价格 (USD)"),
],
)
.add_selection(hover)
)
return (lines + points + tooltips).interactive()
# Original time series chart. Omitted `get_chart` for clarity
chart = get_chart(get_data())
# Input annotations
ANNOTATIONS = [
("Mar 01, 2008", "Pretty good day for GOOG"),
("Dec 01, 2007", "Something's going wrong for GOOG & AAPL"),
("Nov 01, 2008", "Market starts again thanks to..."),
("Dec 01, 2009", "Small crash for GOOG after..."),
]
# Create a chart with annotations
annotations_df = pd.DataFrame(ANNOTATIONS, columns=["date", "event"])
annotations_df.date = pd.to_datetime(annotations_df.date)
annotations_df["y"] = 0
annotation_layer = (
alt.Chart(annotations_df)
.mark_text(size=15, text=ticker, dx=ticker_dx, dy=ticker_dy, align="center")
.encode(
x="date:T",
y=alt.Y("y:Q"),
tooltip=["event"],
)
.interactive()
)
(chart + annotation_layer).interactive()
Run
代码下载
出处
https://share.streamlit.io/streamlit/example-app-time-series-annotation/main