File size: 10,629 Bytes
97ae727
 
 
fd50cbd
1f4b746
97ae727
fd50cbd
 
 
 
97ae727
 
 
 
 
fd50cbd
 
97ae727
fd50cbd
 
97ae727
fd50cbd
97ae727
 
 
 
 
 
 
fd50cbd
97ae727
 
 
 
fd50cbd
 
 
 
 
 
 
 
 
 
 
 
 
 
97ae727
 
 
 
 
 
 
 
 
fd50cbd
97ae727
 
 
 
 
 
 
 
 
 
fd50cbd
 
 
97ae727
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd50cbd
 
97ae727
 
 
 
 
 
 
 
fd50cbd
 
97ae727
 
 
 
 
fd50cbd
4ab50ad
97ae727
fd50cbd
 
97ae727
 
 
fd50cbd
97ae727
 
fd50cbd
 
97ae727
 
fd50cbd
97ae727
 
 
fd50cbd
 
 
97ae727
 
 
 
fd50cbd
 
 
 
 
fed4ab4
 
 
 
 
 
fd50cbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97ae727
1f4b746
fd50cbd
 
 
 
1f4b746
 
fd50cbd
 
1f4b746
 
97ae727
fd50cbd
 
 
 
 
 
 
 
 
 
 
 
 
 
fed4ab4
fd50cbd
 
 
97ae727
fd50cbd
1f4b746
fd50cbd
1f4b746
fd50cbd
1f4b746
 
 
 
fd50cbd
 
1f4b746
 
97ae727
fd50cbd
 
 
 
 
 
 
 
 
 
fed4ab4
fd50cbd
 
 
97ae727
1f4b746
fd50cbd
1f4b746
 
fd50cbd
1f4b746
 
 
 
 
 
 
97ae727
 
1f4b746
fd50cbd
1f4b746
 
fd50cbd
1f4b746
 
 
 
fd50cbd
 
 
 
 
 
 
97ae727
 
 
1f4b746
fd50cbd
 
 
 
 
1f4b746
 
fd50cbd
 
 
97ae727
 
fd50cbd
 
 
 
 
 
1f4b746
97ae727
 
1f4b746
fd50cbd
1f4b746
 
 
 
 
fd50cbd
1f4b746
fd50cbd
 
1f4b746
 
97ae727
fd50cbd
 
 
 
 
 
 
 
 
 
 
 
 
 
97ae727
fd50cbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
import pandas as pd
import yfinance as yf

import streamlit as st
import altair as alt

from types import SimpleNamespace

alt.renderers.set_embed_options(theme="dark")


def clean_etf_data(df):
    """
    Clean ETF data
    """
    # Copy original
    df_original = df.copy()
    # Set date as index
    df_original["Date"] = pd.to_datetime(df_original["Date"])

    # Format outflow to negative value
    df = df.drop(columns="Date")
    df.replace(to_replace=r"\(([0-9.]+)\)", value=r"-\1", regex=True, inplace=True)

    # Replace '-' with 0
    df.replace("-", 0, inplace=True)

    # Convert from strings to numberic
    df = df.apply(pd.to_numeric)
    df["Date"] = df_original["Date"]

    return df, df_original


def extract_date_index(df):
    """
    Extract index from dataframe as Date
    """
    # Convert Series to DataFrame
    if isinstance(df, pd.Series):
        df = df.to_frame()
    df = df.reset_index(names="Date")
    # Set date as index
    df.Date = pd.to_datetime(df.Date)

    return df


##------------------------- ETF flow --------------------------------------------

# Get Bitcoin spot ETF history
btc_etf_flow = pd.read_html(
    "https://farside.co.uk/?p=1321", attrs={"class": "etf"}, skiprows=[1]
)[0]
# Remove summary lines
btc_etf_flow = btc_etf_flow.iloc[:-4]
# Extract symbols of ETF funds
btc_etf_funds = btc_etf_flow.drop(["Date", "Total"], axis=1).columns.to_list()

# Get Ethereum spot ETF history
eth_etf_flow = pd.read_html(
    "https://farside.co.uk/ethereum-etf-flow-all-data/",
    attrs={"class": "etf"},
    skiprows=[2, 3],
)[0]
# Drop column index level 2
eth_etf_flow.columns = eth_etf_flow.columns.droplevel(2)
# Extract symbols of ETF funds
eth_etf_funds = (
    eth_etf_flow.drop("Total", axis=1).columns[1:].get_level_values(1).to_list()
)
# Merge multi-index columns
eth_etf_flow.columns = eth_etf_flow.columns.map(" | ".join)
# Name first column "Date"
eth_etf_flow.rename(
    columns={
        "Unnamed: 0_level_0 | Unnamed: 0_level_1": "Date",
        "Total | Unnamed: 10_level_1": "Total",
    },
    inplace=True,
)
# Remove summary lines
eth_etf_flow = eth_etf_flow.iloc[:-1]

btc_etf_flow, btc_etf_flow_original = clean_etf_data(btc_etf_flow)
eth_etf_flow, eth_etf_flow_original = clean_etf_data(eth_etf_flow)

##------------------------- ETF volume -----------------------------------------

# Get BTC ETF daily volume
btc_etf_volumes = pd.DataFrame()
for fund in btc_etf_funds:
    btc_etf_volumes[fund] = yf.download(
        f"{fund}", interval="1d", period="max", start=btc_etf_flow.index[0]
    )["Volume"]

# Extract Date column from index
btc_etf_volumes = extract_date_index(btc_etf_volumes)

# Get ETH ETF daily volume
eth_etf_volumes = pd.DataFrame()
for fund in eth_etf_funds:
    eth_etf_volumes[fund] = yf.download(
        f"{fund}", interval="1d", period="max", start=eth_etf_flow.index[0]
    )["Volume"]

# Extract Date column from index
eth_etf_volumes = extract_date_index(eth_etf_volumes)

##------------------------- Asset price --------------------------------------------

# Get BTC price history
btc_price = yf.download(
    "BTC-USD", interval="1d", period="max", start=btc_etf_flow["Date"][0]
)
btc_price = btc_price.Close
# Extract Date column from index
btc_price = extract_date_index(btc_price)

# Get ETH price history
eth_price = yf.download(
    "ETH-USD", interval="1d", period="max", start=eth_etf_flow["Date"][0]
)
eth_price = eth_price.Close
# Extract Date column from index
eth_price = extract_date_index(eth_price)


def gen_data(asset):
    if asset == "BTC":
        etf_volumes = btc_etf_volumes
        price = btc_price

        etf_flow_individual = btc_etf_flow.drop(columns="Total")
        etf_flow_total = btc_etf_flow[["Date", "Total"]]
    else:
        etf_volumes = eth_etf_volumes
        price = eth_price

        etf_flow_individual = eth_etf_flow.drop(columns="Total")
        etf_flow_total = eth_etf_flow[["Date", "Total"]]

    cum_flow_individual = etf_flow_individual.drop(columns="Date").cumsum()
    cum_flow_individual["Date"] = etf_flow_individual.Date
    cum_flow_total = pd.DataFrame(
        {
            "Date": etf_flow_total.Date,
            "Total": etf_flow_total.Total.cumsum(),
        }
    )

    return SimpleNamespace(
        etf_volumes=etf_volumes,
        price=price,
        etf_flow_individual=etf_flow_individual,
        etf_flow_total=etf_flow_total,
        cum_flow_individual=cum_flow_individual,
        cum_flow_total=cum_flow_total,
    )


def gen_charts(asset, chart_size={"width": 560, "height": 300}):
    # Gen data
    data = gen_data(asset)
    etf_volumes = data.etf_volumes
    price = data.price
    etf_flow_individual = data.etf_flow_individual
    etf_flow_total = data.etf_flow_total
    cum_flow_individual = data.cum_flow_individual
    cum_flow_total = data.cum_flow_total

    trading_vol_fig = (
        alt.Chart(etf_volumes)
        .transform_fold(
            etf_volumes.drop(columns="Date").columns.to_list(), as_=["Funds", "Volume"]
        )
        .mark_bar()
        .encode(
            x=alt.X("Date:T", axis=alt.Axis(tickCount="day")),
            y=alt.Y("Volume:Q"),
            color="Funds:N",
        )
    )
    trading_vol_avg_fig = (
        alt.Chart(etf_volumes)
        .transform_fold(
            etf_volumes.drop(columns="Date").columns.to_list(), as_=["Funds", "Volume"]
        )
        .mark_line()
        .encode(
            x=alt.X("Date:T", axis=alt.Axis(tickCount="day")),
            y=alt.Y("mean(Volume):Q", title="Average Volume"),
            color=alt.value("crimson"),
        )
    )
    # Combine trading volume and average trading volume
    trading_vol_fig += trading_vol_avg_fig
    trading_vol_fig = trading_vol_fig.properties(
        title=f"{asset} ETF trading volume",
        **chart_size,
    )

    # Net flow individual
    net_flow_individual_fig = (
        alt.Chart(etf_flow_individual)
        .transform_fold(
            etf_flow_individual.drop(columns="Date").columns.to_list(),
            as_=["Funds", "Net Flow"],
        )
        .mark_bar()
        .encode(
            x=alt.X("Date:T", axis=alt.Axis(tickCount="day")),
            y=alt.Y("Net Flow:Q"),
            color="Funds:N",
        )
    )
    net_flow_total_line_fig = (
        alt.Chart(etf_flow_total)
        .mark_line()
        .encode(
            x=alt.X("Date:T", axis=alt.Axis(tickCount="day")),
            y=alt.Y("Total:Q"),
            color=alt.value("crimson"),
        )
    )
    net_flow_individual_fig += net_flow_total_line_fig
    net_flow_individual_fig = net_flow_individual_fig.properties(
        title=f"{asset} ETF net flow of individual funds",
        **chart_size,
    )

    net_flow_total_fig = (
        alt.Chart(etf_flow_total)
        .mark_bar()
        .encode(
            x=alt.X("Date:T", axis=alt.Axis(tickCount="day")),
            y=alt.Y("Total:Q"),
            color=alt.condition(
                alt.datum.Total > 0,
                alt.value("seagreen"),  # The positive color
                alt.value("orangered"),  # The negative color
            ),
        )
    )
    # Line chart of price
    price_fig = (
        alt.Chart(price)
        .mark_line()
        .encode(
            x=alt.X("Date:T", axis=alt.Axis(tickCount="day")),
            y=alt.Y("Close:Q", title="Price"),
            color=alt.value("crimson"),
        )
    )

    net_flow_total_fig += price_fig
    net_flow_total_fig = net_flow_total_fig.resolve_scale(
        y="independent",
    ).properties(
        title=f"{asset} ETF net flow total vs asset price",
        **chart_size,
    )

    # Stacking area chart of flow from individual funds
    cum_flow_individual_net_fig = (
        alt.Chart(cum_flow_individual)
        .transform_fold(
            cum_flow_individual.drop(columns="Date").columns.to_list(),
            as_=["Funds", "Net Flow"],
        )
        .mark_area()
        .encode(
            x=alt.X("Date:T", axis=alt.Axis(tickCount="day")),
            y=alt.Y("Net Flow:Q"),
            color=alt.Color("Funds:N", scale=alt.Scale(scheme="tableau20")),
        )
    )
    cum_flow_individual_net_fig += price_fig
    cum_flow_individual_net_fig = cum_flow_individual_net_fig.resolve_scale(
        y="independent",
    ).properties(
        title=f"{asset} ETF cumulative flow of individual funds vs asset price",
        **chart_size,
    )

    # Area chart for cumulative flow
    cum_flow_total_fig = (
        alt.Chart(cum_flow_total)
        .transform_calculate(
            negative="datum.Total < 0",
        )
        .mark_area()
        .encode(
            x=alt.X("Date:T", axis=alt.Axis(tickCount="day")),
            y=alt.Y("Total:Q", impute={"value": 0}),
            color=alt.Color(
                "negative:N", title="Negative Flow", scale=alt.Scale(scheme="set2")
            ),
        )
    )
    cum_flow_total_fig += price_fig
    cum_flow_total_fig = cum_flow_total_fig.resolve_scale(
        y="independent",
    ).properties(
        title=f"{asset} ETF cumulative flow total vs asset price",
        **chart_size,
    )

    return SimpleNamespace(
        trading_vol_fig=trading_vol_fig,
        net_flow_individual_fig=net_flow_individual_fig,
        net_flow_total_fig=net_flow_total_fig,
        cum_flow_individual_net_fig=cum_flow_individual_net_fig,
        cum_flow_total_fig=cum_flow_total_fig,
    )


def compound_chart(chart_size={"width": 560, "height": 300}):
    btc_charts = gen_charts("BTC", chart_size)
    eth_charts = gen_charts("ETH", chart_size)

    # Vertical concat the charts in each asset into single colume of that asset
    all_charts_btc = (
        btc_charts.trading_vol_fig
        & btc_charts.net_flow_individual_fig
        & btc_charts.net_flow_total_fig
        & btc_charts.cum_flow_individual_net_fig
        & btc_charts.cum_flow_total_fig
    ).resolve_scale(color="independent")
    all_charts_eth = (
        eth_charts.trading_vol_fig
        & eth_charts.net_flow_individual_fig
        & eth_charts.net_flow_total_fig
        & eth_charts.cum_flow_individual_net_fig
        & eth_charts.cum_flow_total_fig
    ).resolve_scale(color="independent")
    # Horizontal concat the charts for btc and eth
    all_charts = (all_charts_btc | all_charts_eth).resolve_scale(color="independent")

    return all_charts


if __name__ == "__main__":
    # Set page config
    st.set_page_config(layout="wide", page_icon="πŸ“ˆ")

    chart = compound_chart(chart_size={"width": 560, "height": 300})
    # Display charts
    st.altair_chart(chart, use_container_width=True)