Trireme commited on
Commit
14e1f7d
·
1 Parent(s): c075af7

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. README.md +2 -8
  2. app.py +256 -0
  3. requirements.txt +8 -0
README.md CHANGED
@@ -1,12 +1,6 @@
1
  ---
2
- title: Billy Dashboard
3
- emoji: 🏢
4
- colorFrom: indigo
5
- colorTo: indigo
6
  sdk: gradio
7
  sdk_version: 5.29.1
8
- app_file: app.py
9
- pinned: false
10
  ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: billy_dashboard
3
+ app_file: app.py
 
 
4
  sdk: gradio
5
  sdk_version: 5.29.1
 
 
6
  ---
 
 
app.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import asyncio
3
+ import aiohttp
4
+ import nest_asyncio
5
+ import pandas as pd
6
+ import requests
7
+ import json
8
+ import urllib.parse
9
+ import gradio as gr
10
+
11
+ wallets = [
12
+ "J7QAjhEGTAx71RoS1Nnuz4aKqK866xEnRXky4zhPa2WG",
13
+ "9huTEYifjBMJVhPWG3dX84S1Pr6pgXBH9i7274dpPeMr",
14
+ "CoA4vLyykjYobxEsDWHEx2Rna9WribGQMxSxVkH5NwN6",
15
+ "BpaD3QF9Z2YtUqPRxpTn7dgC2sBzpzxro5zrEdwhwNd9",
16
+ "FWmhs5vdUSMHUE5sHPQmd1hBEQVWD8wyCPe9op3KwTNg",
17
+ "HW1qacccywvtEmUK6mDWfaJfxcM1R64T8BmhfjmxA6Nx",
18
+ "3QpWHc77Vze5uiqm6WDfxYawKUj1bVbKEegS3YYBLGvL",
19
+ "5FyNV778E1SZ4ZBwUXCgbx43zrJFdMy4UgUysSw3yocU",
20
+ "4L3wPZc8smLYQbnpMSxHCiRB5cojbtuc33NkTNsrtdug",
21
+ "MruHB1owAkBQwtSkzTqTDpqZEDPmz4iUWz3oHCYHKWV"
22
+ ]
23
+
24
+ SCRAPE_DO_TOKEN = "c3cb4da35304433483052fb6ba0c7011fef2ff42d62"
25
+
26
+ common_headers = {
27
+ "accept": "application/json",
28
+ "accept-encoding": "identity",
29
+ "accept-language": "en-GB,en-US;q=0.9,en;q=0.8",
30
+ "authorization": "Bearer CGtF4EdvDbBpwUXmZSKW3HsYkajy7e",
31
+ "content-type": "application/json",
32
+ "origin": "https://portfolio.jup.ag",
33
+ "referer": "https://portfolio.jup.ag/",
34
+ "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
35
+ "x-turnstile-token": "0.replS6iD2yH0tx4VW09xgMrsCEIhseDU5PLWuo893A_Ekt3xg5uRfVTGixcTrEgV-lHCrY1MdVrBbARS4d3pvNdSjTGlyE9joXTSFSwgPi3b-vSVZ68uxq-VwgMWVBscYHQQSD8jSt_cDyl8C57Zqfc5GAeF8KLvCW6TzMDUGUkuAL824tStFs2o-16lgma5L_36AH0DxhriHsm_4bI9E8vAezX9QNyW9t7d6Io5nCyFTAcNbhXA5hvblmwprOop7Nb_j_dDjmJDUNl_SUmmbG5SshHwoXrIeJDGuSP5q47TL6xpgUlyjqg8cRboczfQVL09bn82rsb_6mOz84vm0aAH3I2lOPGeTPcaIBIyjfg4Eb2I-_YAbfVl3yPzwDCBKW8p4CCCTIVJU1pV638M_EFMOnnGk3RcXb9TVIpIkGnvatCOMzCPQHXGDpT1qbiA7YQnuZjr62oSEXwyQrsmKnXYqwC0K7iRpxjanYKfJR7B6NGRj4w5f-VJUnQd9u_zxHp2yNkz7MvQlIbUYMPaenL66HvAD0EoPzDWd8xWxivo-SME42YqXGRxw4Pe0cn48BvnfO7ZwebV1fCOGy9Mb2bQc_JxEArkmPCNu9YCJ-Cs_mSFlZ6Q5PM-VtBV2NFlV8itMea4GDEU823bGLoAgQJ_ct0Vxh5Jcn3CE94wIItk1ahZDgXCoY38Hq57U3iA3OFaCl9MvA3L8WXkWgmqezJLGl0cjj5TuxaAIlFnpSir4jdZHsD-ET7HlUeiz07Jy9rkG-Jtj1Gl5mA8lfoUloEn5eiW7P_JaediaYHZ5VmaVqVMvzLFjiZ27y9WLuRViRtlM15d-1w0isvBFI2LBXezx3UT-owLhXjeBE28y4M.AlrCxH1Qs0BV-6wumeZlZw.d75bf4fc0601ec6ac26dd1e7ab7753521759ecefbe078db1222669ae67a8fde4" # keep this updated
36
+ }
37
+
38
+ async def fetch_portfolio(session, wallet_address, results):
39
+ base_url = f"https://portfolio-api-jup.sonar.watch/v1/portfolio/fetch?address={wallet_address}&addressSystem=solana"
40
+ encoded_url = urllib.parse.quote(base_url)
41
+ proxy_url = f"http://api.scrape.do/?token={SCRAPE_DO_TOKEN}&url={encoded_url}&forwardHeaders=True&super=True"
42
+
43
+ try:
44
+ async with session.get(proxy_url, headers=common_headers) as resp:
45
+ text = await resp.json()
46
+ if resp.status == 200:
47
+ print(f"✅ Wallet {wallet_address[:6]}...: success")
48
+ results.append({"wallet": wallet_address,"data": text})
49
+ else:
50
+ print(f"❌ Wallet {wallet_address[:6]}...: HTTP {resp.status}")
51
+ results.append({"wallet": wallet_address, "data": None})
52
+ except Exception as e:
53
+ print(f"⚠️ Error fetching {wallet_address}: {e}")
54
+ results.append({"wallet": wallet_address, "status": "error", "error": str(e)})
55
+
56
+ async def get_data(wallet_addresses):
57
+ results = []
58
+ async with aiohttp.ClientSession() as session:
59
+ tasks = [fetch_portfolio(session, address, results) for address in wallet_addresses]
60
+ await asyncio.gather(*tasks)
61
+ return results
62
+ #Have a button function which does all this
63
+
64
+ async def process_data():
65
+ portfolios = await get_data(wallets)
66
+ df = pd.DataFrame(portfolios)
67
+ token_rows = []
68
+
69
+ for index, row in df.iterrows():
70
+ data = row['data']
71
+
72
+ # Token info mapping
73
+ token_info = data.get('tokenInfo', {}).get('solana', {})
74
+
75
+ # Navigate to assets list
76
+ elements = data.get('elements', [])
77
+ for element in elements:
78
+ if element.get('type') == 'multiple':
79
+ assets = element.get('data', {}).get('assets', [])
80
+ for asset in assets:
81
+ asset_data = asset.get('data', {})
82
+ address = asset_data.get('address')
83
+ amount = asset_data.get('amount')
84
+ value = asset.get('value')
85
+
86
+ # Get symbol using address
87
+ symbol = token_info.get(address, {}).get('symbol', 'UNKNOWN')
88
+
89
+ token_rows.append({
90
+ 'original_row': index,
91
+ 'address': address,
92
+ 'symbol': symbol,
93
+ 'amount': amount,
94
+ 'value': value
95
+ })
96
+
97
+ # Final DataFrame
98
+ tokens_df = pd.DataFrame(token_rows)
99
+ tokens_df['original_row'] = tokens_df['original_row'].apply(lambda x: df.loc[x, 'wallet'])
100
+ tokens_df = tokens_df.dropna()
101
+
102
+ # Pivot for values
103
+ value_pivot = tokens_df.pivot(index='original_row', columns='symbol', values='value')
104
+ value_pivot.columns = [f'{col}_value' for col in value_pivot.columns]
105
+
106
+ # Pivot for amounts
107
+ amount_pivot = tokens_df.pivot(index='original_row', columns='symbol', values='amount')
108
+ amount_pivot.columns = [f'{col}_amount' for col in amount_pivot.columns]
109
+
110
+ # Combine both
111
+ final_df = pd.concat([value_pivot, amount_pivot], axis=1).reset_index()
112
+
113
+ # Optional: Fill NaNs with 0
114
+ final_df = final_df.fillna(0)
115
+
116
+ rows = []
117
+ for idx, row in df.iterrows():
118
+ data = row['data']
119
+ original_row = row['wallet'] # or whatever uniquely identifies the row
120
+
121
+ for element in data.get("elements", []):
122
+ if element.get("platformId") == "jupiter-exchange":
123
+ input_token = element.get("data", {}).get("assets", {}).get("input", {})
124
+ if input_token:
125
+ token_data = input_token.get("data", {})
126
+ address = token_data.get("address")
127
+ value = input_token.get("value")
128
+ amount = token_data.get("amount")
129
+ symbol = token_info.get(address, {}).get("symbol", address)
130
+
131
+ rows.append({
132
+ "original_row": original_row,
133
+ "address": address,
134
+ "symbol": symbol,
135
+ "amount": amount,
136
+ "value": value
137
+ })
138
+
139
+ # Convert to DataFrame
140
+ jup_tokens_df = pd.DataFrame(rows)
141
+
142
+ jup_tokens_df['symbol'] = jup_tokens_df['symbol'].apply(lambda x: "SOL" if x == "So11111111111111111111111111111111111111112" else x)
143
+
144
+ # Pivot
145
+ # Group by original_row and symbol, sum value and amount
146
+ tokens_grouped = jup_tokens_df.groupby(['original_row', 'symbol']).agg({
147
+ 'value': 'sum',
148
+ 'amount': 'sum'
149
+ }).reset_index()
150
+
151
+ # Pivot
152
+ value_pivot = tokens_grouped.pivot(index='original_row', columns='symbol', values='value')
153
+ value_pivot.columns = [f'{col}_value' for col in value_pivot.columns]
154
+
155
+ amount_pivot = tokens_grouped.pivot(index='original_row', columns='symbol', values='amount')
156
+ amount_pivot.columns = [f'{col}_amount' for col in amount_pivot.columns]
157
+
158
+ jup_df = pd.concat([value_pivot, amount_pivot], axis=1).reset_index().fillna(0)
159
+
160
+ final_df1 = final_df.set_index('original_row')
161
+ final_df2 = jup_df.set_index('original_row')
162
+
163
+ # Combine the two DataFrames, adding values where they overlap
164
+ combined_df = final_df1.add(final_df2, fill_value=0)
165
+
166
+ # Reset index if you want original_row back as a column
167
+ combined_df = combined_df.reset_index()
168
+
169
+ # Optional: fill NaNs (if any) with 0 just in case
170
+ combined_df = combined_df.fillna(0)
171
+
172
+ # Sum all numeric columns except the original_row which is non-numeric
173
+ totals = combined_df.select_dtypes(include='number').sum()
174
+
175
+ # Add a row with these totals at the bottom of the dataframe
176
+ totals_row = pd.DataFrame(totals).T
177
+ totals_row['original_row'] = 'Total'
178
+
179
+ # Append the totals row to the original df
180
+ df_with_totals = pd.concat([combined_df, totals_row], ignore_index=True)
181
+
182
+ totals = final_df.select_dtypes(include='number').sum()
183
+
184
+ # Add a row with these totals at the bottom of the dataframe
185
+ totals_row = pd.DataFrame(totals).T
186
+ totals_row['original_row'] = 'Total'
187
+
188
+ # Append the totals row to the original df
189
+ final_df = pd.concat([final_df, totals_row], ignore_index=True)
190
+
191
+ totals = jup_df.select_dtypes(include='number').sum()
192
+
193
+ # Add a row with these totals at the bottom of the dataframe
194
+ totals_row = pd.DataFrame(totals).T
195
+ totals_row['original_row'] = 'Total'
196
+
197
+ # Append the totals row to the original df
198
+ jup_df = pd.concat([jup_df, totals_row], ignore_index=True)
199
+
200
+ final_df = final_df.rename(columns={'original_row': ' '})
201
+ jup_df = jup_df.rename(columns={'original_row': ' '})
202
+ df_with_totals = df_with_totals.rename(columns={'original_row': ' '})
203
+
204
+ sol_price = 170
205
+ billy_price = 0.001845
206
+
207
+ # Starting balances
208
+ starting_balances = {
209
+ " ": ["Total"],
210
+ "SOL_amount": [344],
211
+ "SOL_value": [344 * sol_price],
212
+ "BILLY_amount": [75_000_000],
213
+ "BILLY_value": [75_000_000 * billy_price]
214
+ }
215
+
216
+ # Create the DataFrame
217
+ starting_df = pd.DataFrame(starting_balances)
218
+
219
+ return(starting_df,final_df.tail(1),jup_df.tail(1),df_with_totals.tail(1))
220
+
221
+ async def display_data():
222
+ df0, df1, df2, df3 = await process_data()
223
+
224
+ def summarize(df):
225
+ value_cols = [col for col in df.columns if "value" in col.lower()]
226
+ total_value = df[value_cols].sum(axis=1).values[0] if value_cols else 0
227
+ return df, total_value
228
+
229
+ df0, total0 = summarize(df0)
230
+ df3, total3 = summarize(df3)
231
+
232
+ pnl = float(total3) - float(total0)
233
+
234
+ return summarize(df0) + summarize(df1) + summarize(df2) + summarize(df3) + (f"PNL : {pnl:,.2f}"," ")
235
+
236
+ with gr.Blocks() as demo:
237
+ gr.Markdown("## BILLY Balances and PnL")
238
+ btn = gr.Button("Fetch & Display Balances")
239
+
240
+ df0_out = gr.Dataframe(label="Starting Balances")
241
+ txt0_out = gr.Textbox(label="Starting Value Total")
242
+
243
+ df1_out = gr.Dataframe(label="Wallet Balances")
244
+ txt1_out = gr.Textbox(label="Wallet Value Total")
245
+
246
+ df2_out = gr.Dataframe(label="JUP Limit Balances")
247
+ txt2_out = gr.Textbox(label="JUP Limit Value Total")
248
+
249
+ df3_out = gr.Dataframe(label="Total Balances")
250
+ txt3_out = gr.Textbox(label="Current Value Total")
251
+
252
+ pnl_out = gr.Textbox(label="PNL (AUM Model)")
253
+
254
+ btn.click(display_data, outputs=[df0_out, txt0_out, df1_out, txt1_out, df2_out, txt2_out, df3_out,txt3_out,pnl_out])
255
+
256
+ demo.launch(debug=True)
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ asyncio
2
+ aiohttp
3
+ nest_asyncio
4
+ pandas
5
+ requests
6
+ json
7
+ urllib.parse
8
+ gradio