-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathetfs.py
More file actions
executable file
·64 lines (52 loc) · 1.75 KB
/
Copy pathetfs.py
File metadata and controls
executable file
·64 lines (52 loc) · 1.75 KB
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
#!/usr/bin/env python3
"""Calculate ETF values."""
from datetime import datetime
from typing import Optional
import pandas as pd
import common
import ledger_amounts
TICKER_PRICES_TABLE = "ticker_prices"
def get_etfs_df(account: Optional[str] = None) -> pd.DataFrame:
data = []
tas = {}
for ticker, amount in ledger_amounts.get_etfs_amounts(account).items():
tas[ticker] = amount
ps = common.get_tickers(get_tickers())
for ticker, amount in tas.items():
price = ps[ticker]
data.append(
{
"ticker": ticker,
"shares": amount,
"current_price": price,
"value": amount * price,
}
)
df = pd.DataFrame(data).set_index("ticker").sort_index()
return df
def get_tickers() -> set[str]:
return set(ledger_amounts.get_etfs_amounts().keys())
# This is used in separate graph generation processes so redis caching makes sense.
@common.walrus_db.db.lock("get_prices_wide_df", ttl=common.LOCK_TTL_SECONDS * 1000)
@common.walrus_db.cache.cached()
def get_prices_wide_df() -> pd.DataFrame:
prices_df = (
common.read_sql_table(TICKER_PRICES_TABLE)
.reset_index()
.pivot(index="date", columns="ticker", values="price")
.resample("h")
.last()
.interpolate()
)
cols = get_tickers()
prices_df = prices_df[sorted(prices_df.columns.intersection(list(cols)))]
return prices_df
def get_prices_percent_diff_df(
prices_df: pd.DataFrame,
r: Optional[tuple[str | datetime, str | datetime]] = None,
) -> pd.DataFrame:
if r is not None:
start, end = r
prices_df = prices_df[start:end]
diff_df = (1 + prices_df.pct_change()).cumprod() * 100 - 100
return diff_df