Skip to content

Commit

Permalink
FEAT: Styling altair plotter
Browse files Browse the repository at this point in the history
  • Loading branch information
gialdetti committed Aug 28, 2024
1 parent 9456bff commit c76a99a
Show file tree
Hide file tree
Showing 5 changed files with 306 additions and 606 deletions.
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Changed
* Styling altair plotter.

## [0.0.92] - 2024-08-28
### Fixed
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ In the context of answering these questions, the tutorials demonstrate the relev

| Theme | MyBinder | Colab |
| ------------ | :----------: | :---: |
| [Market Performance Visualization](https://nbviewer.jupyter.org/github/gialdetti/capon/blob/master/examples/visualization/visualize-markets.ipynb) | [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/gialdetti/capon/master?filepath=examples/visualization/visualize-markets.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/gialdetti/capon/blob/master/examples/visualization/visualize-markets.ipynb) |
| [My Stock Portfolio Performance](https://nbviewer.jupyter.org/github/gialdetti/capon/blob/master/examples/monitoring/my_portfolio_performance.ipynb) | [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/gialdetti/capon/master?filepath=examples/monitoring/my_portfolio_performance.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/gialdetti/capon/blob/master/examples/monitoring/my_portfolio_performance.ipynb) |
| [Stock Market Crash and Rebound Amid Coronavirus](https://nbviewer.jupyter.org/github/gialdetti/capon/blob/master/examples/market_analysis/stock_indexes.ipynb) | [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/gialdetti/capon/master?filepath=examples/market_analysis/stock_indexes.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/gialdetti/capon/blob/master/examples/market_analysis/stock_indexes.ipynb) |
| [Analyzing the Sector-level Crash and Rebound](https://nbviewer.jupyter.org/github/gialdetti/capon/blob/master/examples/market_analysis/sector_crash_and_rebound.ipynb) | [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/gialdetti/capon/master?filepath=examples/market_analysis/sector_crash_and_rebound.ipynb) | [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/gialdetti/capon/blob/master/examples/market_analysis/sector_crash_and_rebound.ipynb) |
Expand Down
61 changes: 31 additions & 30 deletions capon/visualization/altairplotter.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,17 @@
from capon.preprocessing import normalize_traces


defaults = dict(line=dict(interpolate="monotone"))


def plot_history(
stocks, normalize=None, index="timestamp", value="close", by="symbol", point=False
stocks,
normalize=None,
index="timestamp",
value="close",
by="symbol",
point=False,
title="Market Performance",
):
value_params = {}

Expand All @@ -16,15 +25,17 @@ def plot_history(
tooltip=dict(format="+.2%"),
)

line_kwargs = {}
line_kwargs = defaults["line"].copy()
if point:
line_kwargs = dict(point={"filled": False, "fill": "white"})
line_kwargs.update(dict(point={"filled": False, "fill": "white"}))

highlight = alt.selection(type="single", on="mouseover", fields=[by], nearest=True)

base = alt.Chart(stocks).encode(
x=f"{index}:T",
y=alt.Y(f"{value}:Q", axis=alt.Axis(**value_params.get("axis", {}))),
x=alt.X(f"{index}:T", axis=alt.Axis(format="%Y-%m-%d"), title=None),
y=alt.Y(
f"{value}:Q", axis=alt.Axis(**value_params.get("axis", {})), title=None
),
color=f"{by}:N",
)

Expand Down Expand Up @@ -55,22 +66,18 @@ def plot_history(
return chart.properties(
width=800,
height=240,
title=f"Historical Changes"
+ (f" from {normalize}" if normalize is not None else ""),
title={
"text": title,
"subtitle": f"Relative to {normalize}" if normalize is not None else "",
},
)


if __name__ == "__main__":
import pandas as pd
from tqdm.auto import tqdm
import capon

tickers = ["BAC", "ALLY", "DFS", "SCHW"]

history = pd.concat(
[capon.stock(ticker, range="2y", interval="1mo") for ticker in tqdm(tickers)],
ignore_index=True,
)
history = capon.stocks(tickers, range="2y", interval="1mo", n_jobs=-1)

chart = plot_history(history)
chart.display()
Expand All @@ -81,33 +88,27 @@ def plot_history(
chart.configure_line(point={"filled": False, "fill": "white"}).display()

normalize = history["timestamp"].unique()[12].strftime("%Y-%m-%d")

chart = plot_history(
history,
normalize=normalize,
point=True,
)
chart = plot_history(history, normalize=normalize, point=True)
chart.display()


if __name__ == "__main__":
from capon.datasets import load_stock_indexes

tickers = (
indices_tickers = (
load_stock_indexes()
.pipe(lambda df: df[df["country_code"] == "US"])
.symbol.tolist()
)

stocks = pd.concat(
[
capon.stock(ticker, range="10y", interval="1mo").iloc[:-1]
for ticker in tqdm(tickers)
],
ignore_index=True,
indices = capon.stocks(
indices_tickers, range="10y", interval="1mo", n_jobs=-1
).pipe(lambda df: df[df["timestamp"] >= "2013"])
stocks
indices

capon.plot(
stocks.merge(load_stock_indexes(), on="symbol"), by="name", normalize="start"
)
indices.merge(load_stock_indexes(), on="symbol"),
by="name",
normalize="start",
title="Market Indices Change",
).configure_legend(title=None).display()
Loading

0 comments on commit c76a99a

Please sign in to comment.