I'm exploring Altair since a couple of days to create interactive charts. I am trying to create a chart with two layers both showing cumulative stock returns over time. Brushing over one chart should provide a zoomed-in view in the other chart with the cumulative return updating in real-time starting at 0.
In pandas, you could calculate this as follows over the visible time period:
(1 + ret).cumprod() - 1
I can't figure out how and whether it is possible to do this with altair.
I've seen that there are two kind of transformations possible:
- Within an encoding channel
- Using top level transforms (eg, transform_aggregate and transform_calculate)
I have successfully used 1 in the past (for example for creating two charts with one acting as zoom selection for the other one), I am having trouble to make 2 work.
To take a concrete simple example, I am concatenating vertically two charts below. A selection on the bottom one should show a running sum over this selection in the first one.
Here is my current attempt at doing this that produces behavior I don't fully understand (brushing from left to right seems to do what I want, brushing right to left results in a downward sloping running sum, deselecting produces bizarre results altogether)...
import altair as alt
from vega_datasets import data
source = data.stocks().query('symbol=="GOOG"')
sel = alt.selection_interval(encodings=['x'])
c1 = alt.Chart(source).mark_line().encode(
x='date',
y='price_cum:Q'
).transform_filter(sel).transform_window(price_cum='sum(price)')
c2 = alt.Chart(source).mark_line().encode(
x='date',
y='price'
).properties(height=100).add_selection(sel)
c1&c2
Here is the corresponding vega-lite spec in the editor: