#!/usr/bin/env python # coding: utf-8 # # Visualize Financial Market Data # --- # # Here, we’ll demonstrate the visualization of financial market data using the `capon` theme. # In[1]: # # Install libraries - uncomment if running on a new environment (e.g., Colab) # !pip install --upgrade themes # In[2]: import themes themes.register() # ## The Data # We'll use an out-of-the-box sample data. # In[3]: from themes import datasets help(datasets.load_markets) # In[4]: markets = ( datasets.load_markets() .pipe(lambda df: df[df["timestamp"] > "2020"]) .assign( relative_price=lambda df: df.groupby("symbol")["close"].transform( lambda g: g / g.iloc[0] - 1 ) ) ) markets # ## Visualization with Matplotlib # In[5]: import matplotlib.pyplot as plt get_ipython().run_line_magic('config', "InlineBackend.figure_format = 'retina'") # In[6]: with plt.style.context("capon"): plt.figure(figsize=(9, 3), dpi=96) markets.pivot_table( index="timestamp", columns="symbol", values="relative_price" ).plot(ax=plt.gca()) plt.xlabel(None) plt.ylabel("Relative Price") # ## Visualization with Altair # In[7]: import altair as alt # In[8]: chart = ( alt.Chart(markets) .mark_line(interpolate="monotone") .encode( x=alt.X("timestamp", title=None, axis=alt.Axis(format="%b %y")), y=alt.Y("relative_price", title="Relative Price", axis=alt.Axis(format="+%")), color="symbol", tooltip=["timestamp", "symbol", alt.Tooltip("relative_price", format="+.2%")], ) .properties( title={ "text": f"Market Indexes Change", "subtitle": f"Relative to {markets['timestamp'].dt.date.min()}", }, width=600, height=200, ) ) display(chart) # In[9]: with alt.themes.enable("capon"): display(chart)