upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,469 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import requests
|
2 |
+
import pandas as pd
|
3 |
+
import gradio as gr
|
4 |
+
import plotly.graph_objects as go
|
5 |
+
import plotly.express as px
|
6 |
+
from datetime import datetime, timedelta
|
7 |
+
import json
|
8 |
+
from web3 import Web3
|
9 |
+
from app_trans_new import create_transcation_visualizations
|
10 |
+
from app_value_locked import fetch_daily_value_locked
|
11 |
+
OPTIMISM_RPC_URL = 'https://opt-mainnet.g.alchemy.com/v2/U5gnXPYxeyH43MJ9tP8ONBQHEDRav7H0'
|
12 |
+
|
13 |
+
# Initialize a Web3 instance
|
14 |
+
web3 = Web3(Web3.HTTPProvider(OPTIMISM_RPC_URL))
|
15 |
+
|
16 |
+
# Check if connection is successful
|
17 |
+
if not web3.is_connected():
|
18 |
+
raise Exception("Failed to connect to the Optimism network.")
|
19 |
+
|
20 |
+
# Contract address
|
21 |
+
contract_address = '0x3d77596beb0f130a4415df3D2D8232B3d3D31e44'
|
22 |
+
|
23 |
+
# Load the ABI from the provided JSON file
|
24 |
+
with open('./contracts/service_registry_abi.json', 'r') as abi_file:
|
25 |
+
contract_abi = json.load(abi_file)
|
26 |
+
|
27 |
+
# Now you can create the contract
|
28 |
+
service_registry = web3.eth.contract(address=contract_address, abi=contract_abi)
|
29 |
+
|
30 |
+
def get_transfers(integrator: str, wallet: str) -> str:
|
31 |
+
url = f"https://li.quest/v1/analytics/transfers?integrator={integrator}&wallet={wallet}"
|
32 |
+
headers = {"accept": "application/json"}
|
33 |
+
response = requests.get(url, headers=headers)
|
34 |
+
return response.json()
|
35 |
+
|
36 |
+
def load_activity_checker_contract(w3, staking_token_address):
|
37 |
+
"""
|
38 |
+
Loads the Staking Token and Activity Checker contracts.
|
39 |
+
|
40 |
+
:param w3: Web3 instance
|
41 |
+
:param staking_token_address: Address of the staking token contract
|
42 |
+
:return: Tuple of (Staking Token contract instance, Activity Checker contract instance)
|
43 |
+
"""
|
44 |
+
try:
|
45 |
+
# Load the ABI file for the Staking Token contract
|
46 |
+
with open('./contracts/StakingToken.json', "r", encoding="utf-8") as file:
|
47 |
+
staking_token_data = json.load(file)
|
48 |
+
|
49 |
+
staking_token_abi = staking_token_data.get("abi", [])
|
50 |
+
|
51 |
+
# Create the Staking Token contract instance
|
52 |
+
staking_token_contract = w3.eth.contract(address=staking_token_address, abi=staking_token_abi)
|
53 |
+
|
54 |
+
# Get the activity checker contract address from staking_token_contract
|
55 |
+
activity_checker_address = staking_token_contract.functions.activityChecker().call()
|
56 |
+
|
57 |
+
# Load the ABI file for the Activity Checker contract
|
58 |
+
with open('./contracts/StakingActivityChecker.json', "r", encoding="utf-8") as file:
|
59 |
+
activity_checker_data = json.load(file)
|
60 |
+
|
61 |
+
activity_checker_abi = activity_checker_data.get("abi", [])
|
62 |
+
|
63 |
+
# Create the Activity Checker contract instance
|
64 |
+
activity_checker_contract = w3.eth.contract(address=activity_checker_address, abi=activity_checker_abi)
|
65 |
+
|
66 |
+
return staking_token_contract, activity_checker_contract
|
67 |
+
|
68 |
+
except Exception as e:
|
69 |
+
print(f"An error occurred while loading the contracts: {e}")
|
70 |
+
raise
|
71 |
+
|
72 |
+
|
73 |
+
def fetch_and_aggregate_transactions():
|
74 |
+
total_services = service_registry.functions.totalSupply().call()
|
75 |
+
aggregated_transactions = []
|
76 |
+
daily_agent_counts = {}
|
77 |
+
daily_agents_with_transactions = {}
|
78 |
+
|
79 |
+
_staking_token_contract, activity_checker_contract = load_activity_checker_contract(web3, '0x88996bbdE7f982D93214881756840cE2c77C4992')
|
80 |
+
|
81 |
+
for service_id in range(1, total_services + 1):
|
82 |
+
service = service_registry.functions.getService(service_id).call()
|
83 |
+
|
84 |
+
# Extract the list of agent IDs from the service data
|
85 |
+
agent_ids = service[-1] # Assuming the last element is the list of agent IDs
|
86 |
+
|
87 |
+
# Check if 25 is in the list of agent IDs
|
88 |
+
if 25 in agent_ids:
|
89 |
+
agent_address = service_registry.functions.getAgentInstances(service_id).call()[1][0]
|
90 |
+
response_transfers = get_transfers("valory", agent_address)
|
91 |
+
transfers = response_transfers.get("transfers", [])
|
92 |
+
if isinstance(transfers, list):
|
93 |
+
aggregated_transactions.extend(transfers)
|
94 |
+
|
95 |
+
# Track the daily number of agents
|
96 |
+
creation_event = service_registry.events.CreateService.create_filter(
|
97 |
+
from_block=0, argument_filters={'serviceId': service_id, 'configHash': service[2]}
|
98 |
+
).get_all_entries()
|
99 |
+
|
100 |
+
if creation_event:
|
101 |
+
block_number = creation_event[0]['blockNumber']
|
102 |
+
block = web3.eth.get_block(block_number)
|
103 |
+
creation_timestamp = datetime.fromtimestamp(block['timestamp'])
|
104 |
+
date_str = creation_timestamp.strftime('%Y-%m-%d')
|
105 |
+
print("date_str",date_str)
|
106 |
+
if date_str not in daily_agent_counts:
|
107 |
+
daily_agent_counts[date_str] = set()
|
108 |
+
if date_str not in daily_agents_with_transactions:
|
109 |
+
daily_agents_with_transactions[date_str] = set()
|
110 |
+
|
111 |
+
service_safe = service[1]
|
112 |
+
print("agent_address",agent_address,"service_safe",service_safe)
|
113 |
+
multisig_nonces = activity_checker_contract.functions.getMultisigNonces(service_safe).call()[0]
|
114 |
+
if multisig_nonces > 0:
|
115 |
+
daily_agents_with_transactions[date_str].add(agent_address)
|
116 |
+
daily_agent_counts[date_str].add(agent_address)
|
117 |
+
|
118 |
+
# Convert set to count
|
119 |
+
daily_agent_counts = {date: len(agents) for date, agents in daily_agent_counts.items()}
|
120 |
+
daily_agents_with_transactions = {date: len(agents) for date, agents in daily_agents_with_transactions.items()}
|
121 |
+
return aggregated_transactions, daily_agent_counts, daily_agents_with_transactions
|
122 |
+
|
123 |
+
# Function to parse the transaction data and prepare it for visualization
|
124 |
+
def process_transactions_and_agents(data):
|
125 |
+
transactions, daily_agent_counts, daily_agents_with_transactions = data
|
126 |
+
|
127 |
+
# Convert the data into a pandas DataFrame for easy manipulation
|
128 |
+
rows = []
|
129 |
+
for tx in transactions:
|
130 |
+
# Normalize amounts
|
131 |
+
sending_amount = float(tx["sending"]["amount"]) / (10 ** tx["sending"]["token"]["decimals"])
|
132 |
+
receiving_amount = float(tx["receiving"]["amount"]) / (10 ** tx["receiving"]["token"]["decimals"])
|
133 |
+
|
134 |
+
# Convert timestamps to datetime objects
|
135 |
+
sending_timestamp = datetime.utcfromtimestamp(tx["sending"]["timestamp"])
|
136 |
+
receiving_timestamp = datetime.utcfromtimestamp(tx["receiving"]["timestamp"])
|
137 |
+
|
138 |
+
# Prepare row data
|
139 |
+
rows.append({
|
140 |
+
"transactionId": tx["transactionId"],
|
141 |
+
"from_address": tx["fromAddress"],
|
142 |
+
"to_address": tx["toAddress"],
|
143 |
+
"sending_chain": tx["sending"]["chainId"],
|
144 |
+
"receiving_chain": tx["receiving"]["chainId"],
|
145 |
+
"sending_token_symbol": tx["sending"]["token"]["symbol"],
|
146 |
+
"receiving_token_symbol": tx["receiving"]["token"]["symbol"],
|
147 |
+
"sending_amount": sending_amount,
|
148 |
+
"receiving_amount": receiving_amount,
|
149 |
+
"sending_amount_usd": float(tx["sending"]["amountUSD"]),
|
150 |
+
"receiving_amount_usd": float(tx["receiving"]["amountUSD"]),
|
151 |
+
"sending_gas_used": int(tx["sending"]["gasUsed"]),
|
152 |
+
"receiving_gas_used": int(tx["receiving"]["gasUsed"]),
|
153 |
+
"sending_timestamp": sending_timestamp,
|
154 |
+
"receiving_timestamp": receiving_timestamp,
|
155 |
+
"date": sending_timestamp.date(), # Group by day
|
156 |
+
"week": sending_timestamp.strftime('%Y-%m-%d') # Group by week
|
157 |
+
})
|
158 |
+
|
159 |
+
df_transactions = pd.DataFrame(rows)
|
160 |
+
df_agents = pd.DataFrame(list(daily_agent_counts.items()), columns=['date', 'agent_count'])
|
161 |
+
df_agents_with_transactions = pd.DataFrame(list(daily_agents_with_transactions.items()), columns=['date', 'agent_count_with_transactions'])
|
162 |
+
|
163 |
+
# Convert the date column to datetime
|
164 |
+
df_agents['date'] = pd.to_datetime(df_agents['date'])
|
165 |
+
df_agents_with_transactions['date'] = pd.to_datetime(df_agents_with_transactions['date'])
|
166 |
+
|
167 |
+
# Convert to week periods
|
168 |
+
df_agents['week'] = df_agents['date'].dt.to_period('W').apply(lambda r: r.start_time)
|
169 |
+
df_agents_with_transactions['week'] = df_agents_with_transactions['date'].dt.to_period('W').apply(lambda r: r.start_time)
|
170 |
+
|
171 |
+
# Group by week
|
172 |
+
df_agents_weekly = df_agents[['week', 'agent_count']].groupby('week').sum().reset_index()
|
173 |
+
df_agents_with_transactions_weekly = df_agents_with_transactions[['week', 'agent_count_with_transactions']].groupby('week').sum().reset_index()
|
174 |
+
|
175 |
+
return df_transactions, df_agents_weekly, df_agents_with_transactions_weekly, df_agents_with_transactions
|
176 |
+
|
177 |
+
# Function to create visualizations based on the metrics
|
178 |
+
def create_visualizations():
|
179 |
+
transactions_data = fetch_and_aggregate_transactions()
|
180 |
+
df_transactions, df_agents_weekly, df_agents_with_transactions_weekly, df_agents_with_transactions = process_transactions_and_agents(transactions_data)
|
181 |
+
# Map chain IDs to chain names
|
182 |
+
|
183 |
+
# Fetch daily value locked data
|
184 |
+
df_tvl = fetch_daily_value_locked()
|
185 |
+
|
186 |
+
# Calculate total value locked per chain per day
|
187 |
+
df_tvl["total_value_locked_usd"] = df_tvl["amount0_usd"] + df_tvl["amount1_usd"]
|
188 |
+
df_tvl_daily = df_tvl.groupby(["date", "chain_name"])["total_value_locked_usd"].sum().reset_index()
|
189 |
+
df_tvl_daily['date'] = pd.to_datetime(df_tvl_daily['date'])
|
190 |
+
|
191 |
+
# Filter out dates with zero total value locked
|
192 |
+
df_tvl_daily = df_tvl_daily[df_tvl_daily["total_value_locked_usd"] > 0]
|
193 |
+
# Plot total value locked
|
194 |
+
fig_tvl = px.bar(
|
195 |
+
df_tvl_daily,
|
196 |
+
x="date",
|
197 |
+
y="total_value_locked_usd",
|
198 |
+
color="chain_name",
|
199 |
+
title="Total Volume Invested in Pools in Different Chains Daily",
|
200 |
+
labels={"date": "Date", "total_value_locked_usd": "Total Volume Invested (USD)"},
|
201 |
+
barmode='stack',
|
202 |
+
color_discrete_map={
|
203 |
+
"optimism": "blue",
|
204 |
+
"base": "purple",
|
205 |
+
"ethereum": "darkgreen"
|
206 |
+
}
|
207 |
+
)
|
208 |
+
fig_tvl.update_layout(
|
209 |
+
xaxis_title=None,
|
210 |
+
yaxis=dict(tickmode='linear', tick0=0, dtick=1),
|
211 |
+
xaxis=dict(
|
212 |
+
tickmode='array',
|
213 |
+
tickvals=df_tvl_daily['date'],
|
214 |
+
ticktext=df_tvl_daily['date'].dt.strftime('%b %d'),
|
215 |
+
tickangle=90,
|
216 |
+
),
|
217 |
+
bargap=0.6, # Increase gap between bar groups (0-1)
|
218 |
+
bargroupgap=0.1, # Decrease gap between bars in a group (0-1)
|
219 |
+
height=700,
|
220 |
+
width=1200, # Specify width to prevent bars from being too wide
|
221 |
+
margin=dict(l=50, r=50, t=50, b=50), # Add margins
|
222 |
+
showlegend=True,
|
223 |
+
legend=dict(
|
224 |
+
yanchor="top",
|
225 |
+
y=0.99,
|
226 |
+
xanchor="right",
|
227 |
+
x=0.99
|
228 |
+
)
|
229 |
+
)
|
230 |
+
fig_tvl.update_xaxes(tickformat="%b %d")
|
231 |
+
|
232 |
+
|
233 |
+
chain_name_map = {
|
234 |
+
10: "Optimism",
|
235 |
+
8453: "Base",
|
236 |
+
1: "Ethereum"
|
237 |
+
}
|
238 |
+
df_transactions["sending_chain"] = df_transactions["sending_chain"].map(chain_name_map)
|
239 |
+
df_transactions["receiving_chain"] = df_transactions["receiving_chain"].map(chain_name_map)
|
240 |
+
|
241 |
+
# Ensure that chain IDs are strings for consistent grouping
|
242 |
+
df_transactions["sending_chain"] = df_transactions["sending_chain"].astype(str)
|
243 |
+
df_transactions["receiving_chain"] = df_transactions["receiving_chain"].astype(str)
|
244 |
+
df_transactions['date'] = pd.to_datetime(df_transactions['date'])
|
245 |
+
|
246 |
+
# Identify swap transactions
|
247 |
+
df_transactions["is_swap"] = df_transactions.apply(lambda x: x["sending_token_symbol"] != x["receiving_token_symbol"], axis=1)
|
248 |
+
|
249 |
+
# Total swaps per chain per day
|
250 |
+
swaps_per_chain = df_transactions[df_transactions["is_swap"]].groupby(["date", "sending_chain"]).size().reset_index(name="swap_count")
|
251 |
+
fig_swaps_chain = px.bar(
|
252 |
+
swaps_per_chain,
|
253 |
+
x="date",
|
254 |
+
y="swap_count",
|
255 |
+
color="sending_chain",
|
256 |
+
title="Chain Daily Activity: Swaps",
|
257 |
+
labels={"sending_chain": "Transaction Chain", "swap_count": "Daily Swap Nr"},
|
258 |
+
barmode="stack",
|
259 |
+
color_discrete_map={
|
260 |
+
"Optimism": "blue",
|
261 |
+
"Ethereum": "darkgreen",
|
262 |
+
"Base": "purple"
|
263 |
+
}
|
264 |
+
)
|
265 |
+
fig_swaps_chain.update_layout(
|
266 |
+
xaxis_title="Date",
|
267 |
+
yaxis_title="Daily Swap Count",
|
268 |
+
yaxis=dict(tickmode='linear', tick0=0, dtick=1),
|
269 |
+
xaxis=dict(
|
270 |
+
tickmode='array',
|
271 |
+
tickvals=[d for d in swaps_per_chain['date'] if d.weekday() == 0], # Show only Mondays
|
272 |
+
ticktext=[d.strftime('%m-%d') for d in swaps_per_chain['date'] if d.weekday() == 0],
|
273 |
+
tickangle=45,
|
274 |
+
),
|
275 |
+
bargap=0.6, # Increase gap between bar groups (0-1)
|
276 |
+
bargroupgap=0.1, # Decrease gap between bars in a group (0-1)
|
277 |
+
height=700,
|
278 |
+
width=1200, # Specify width to prevent bars from being too wide
|
279 |
+
margin=dict(l=50, r=50, t=50, b=50), # Add margins
|
280 |
+
showlegend=True,
|
281 |
+
legend=dict(
|
282 |
+
yanchor="top",
|
283 |
+
y=0.99,
|
284 |
+
xanchor="right",
|
285 |
+
x=0.99
|
286 |
+
)
|
287 |
+
)
|
288 |
+
fig_swaps_chain.update_xaxes(tickformat="%m-%d")
|
289 |
+
|
290 |
+
# Identify bridge transactions
|
291 |
+
# Identify bridge transactions
|
292 |
+
df_transactions["is_bridge"] = df_transactions.apply(lambda x: x["sending_chain"] != x["receiving_chain"], axis=1)
|
293 |
+
|
294 |
+
# Total bridges per chain per day
|
295 |
+
bridges_per_chain = df_transactions[df_transactions["is_bridge"]].groupby(["date", "sending_chain"]).size().reset_index(name="bridge_count")
|
296 |
+
fig_bridges_chain = px.bar(
|
297 |
+
bridges_per_chain,
|
298 |
+
x="date",
|
299 |
+
y="bridge_count",
|
300 |
+
color="sending_chain",
|
301 |
+
title="Chain Daily Activity: Bridges",
|
302 |
+
labels={"sending_chain": "Transaction Chain", "bridge_count": "Daily Bridge Nr"},
|
303 |
+
barmode="stack",
|
304 |
+
color_discrete_map={
|
305 |
+
"Optimism": "blue",
|
306 |
+
"Ethereum": "darkgreen",
|
307 |
+
"Base": "purple"
|
308 |
+
}
|
309 |
+
)
|
310 |
+
fig_bridges_chain.update_layout(
|
311 |
+
xaxis_title="Date",
|
312 |
+
yaxis_title="Daily Bridge Count",
|
313 |
+
yaxis=dict(tickmode='linear', tick0=0, dtick=1),
|
314 |
+
xaxis=dict(
|
315 |
+
tickmode='array',
|
316 |
+
tickvals=[d for d in bridges_per_chain['date'] if d.weekday() == 0], # Show only Mondays
|
317 |
+
ticktext=[d.strftime('%m-%d') for d in bridges_per_chain['date'] if d.weekday() == 0],
|
318 |
+
tickangle=45,
|
319 |
+
),
|
320 |
+
bargap=0.6, # Increase gap between bar groups (0-1)
|
321 |
+
bargroupgap=0.1, # Decrease gap between bars in a group (0-1)
|
322 |
+
height=700,
|
323 |
+
width=1200, # Specify width to prevent bars from being too wide
|
324 |
+
margin=dict(l=50, r=50, t=50, b=50), # Add margins
|
325 |
+
showlegend=True,
|
326 |
+
legend=dict(
|
327 |
+
yanchor="top",
|
328 |
+
y=0.99,
|
329 |
+
xanchor="right",
|
330 |
+
x=0.99
|
331 |
+
)
|
332 |
+
)
|
333 |
+
fig_bridges_chain.update_xaxes(tickformat="%m-%d")
|
334 |
+
|
335 |
+
# Nr of agents registered daily and weekly
|
336 |
+
# Convert 'date' column to datetime
|
337 |
+
df_agents_with_transactions['date'] = pd.to_datetime(df_agents_with_transactions['date'])
|
338 |
+
|
339 |
+
# Calculate daily number of agents registered
|
340 |
+
daily_agents_df = df_agents_with_transactions.groupby('date').size().reset_index(name='daily_agent_count')
|
341 |
+
|
342 |
+
# Check for October 2, 2024 and update the value
|
343 |
+
daily_agents_df.loc[daily_agents_df['date'] == '2024-10-02', 'daily_agent_count'] = 2
|
344 |
+
|
345 |
+
# Calculate cumulative number of agents registered within the week up to each day
|
346 |
+
df_agents_with_transactions['week_start'] = df_agents_with_transactions['date'].dt.to_period("W").apply(lambda r: r.start_time)
|
347 |
+
cumulative_agents_df = df_agents_with_transactions.groupby(['week_start', 'date']).size().groupby(level=0).cumsum().reset_index(name='weekly_agent_count')
|
348 |
+
|
349 |
+
# Check for October 2, 2024 and update the value
|
350 |
+
cumulative_agents_df.loc[cumulative_agents_df['date'] == '2024-10-02', 'weekly_agent_count'] = 2
|
351 |
+
|
352 |
+
# Combine the data to ensure both dataframes align for plotting
|
353 |
+
combined_df = pd.merge(daily_agents_df, cumulative_agents_df, on='date', how='left')
|
354 |
+
|
355 |
+
# Create the bar chart with side-by-side bars
|
356 |
+
fig_agents_registered = go.Figure(data=[
|
357 |
+
go.Bar(
|
358 |
+
name='Daily nr of Registered Agents',
|
359 |
+
x=combined_df['date'],
|
360 |
+
y=combined_df['daily_agent_count'],
|
361 |
+
marker_color='blue'
|
362 |
+
),
|
363 |
+
go.Bar(
|
364 |
+
name='Total Weekly Nr of Registered Agents',
|
365 |
+
x=combined_df['date'],
|
366 |
+
y=combined_df['weekly_agent_count'],
|
367 |
+
marker_color='purple'
|
368 |
+
)
|
369 |
+
])
|
370 |
+
|
371 |
+
# Update layout to group bars side by side for each day
|
372 |
+
fig_agents_registered.update_layout(
|
373 |
+
xaxis_title='Date',
|
374 |
+
yaxis_title='Number of Agents',
|
375 |
+
title="Nr of Agents Registered",
|
376 |
+
barmode='group',
|
377 |
+
yaxis=dict(tickmode='linear', tick0=0, dtick=1),
|
378 |
+
xaxis=dict(
|
379 |
+
tickmode='array',
|
380 |
+
tickvals=combined_df['date'],
|
381 |
+
ticktext=[d.strftime("%b %d") for d in combined_df['date']],
|
382 |
+
tickangle=-45
|
383 |
+
),
|
384 |
+
bargap=0.6, # Increase gap between bar groups (0-1)
|
385 |
+
height=700,
|
386 |
+
width=1200, # Specify width to prevent bars from being too wide
|
387 |
+
margin=dict(l=50, r=50, t=50, b=50), # Add margins
|
388 |
+
showlegend=True,
|
389 |
+
legend=dict(
|
390 |
+
yanchor="top",
|
391 |
+
y=0.99,
|
392 |
+
xanchor="right",
|
393 |
+
x=0.99
|
394 |
+
)
|
395 |
+
)
|
396 |
+
|
397 |
+
# Calculate weekly average daily active agents
|
398 |
+
df_agents_with_transactions['day_of_week'] = df_agents_with_transactions['date'].dt.dayofweek
|
399 |
+
df_agents_with_transactions_weekly_avg = df_agents_with_transactions.groupby(['week', 'day_of_week'])['agent_count_with_transactions'].mean().reset_index()
|
400 |
+
df_agents_with_transactions_weekly_avg = df_agents_with_transactions_weekly_avg.groupby('week')['agent_count_with_transactions'].mean().reset_index()
|
401 |
+
# Number of agents with transactions per week
|
402 |
+
fig_agents_with_transactions_daily = px.bar(
|
403 |
+
df_agents_with_transactions_weekly,
|
404 |
+
x="week",
|
405 |
+
y="agent_count_with_transactions",
|
406 |
+
title="Daily Active Agents: Weekly Average Nr of agents with at least 1 transaction daily",
|
407 |
+
labels={"week": "Week of", "agent_count_with_transactions": "Number of Agents with Transactions"},
|
408 |
+
color_discrete_sequence=["darkgreen"]
|
409 |
+
)
|
410 |
+
fig_agents_with_transactions_daily.update_layout(
|
411 |
+
title=dict(
|
412 |
+
x=0.5,y=0.95,xanchor='center',yanchor='top'), # Adjust vertical position and Center the title
|
413 |
+
yaxis=dict(tickmode='linear', tick0=0, dtick=1),
|
414 |
+
xaxis=dict(
|
415 |
+
tickmode='array',
|
416 |
+
tickvals=df_agents_with_transactions_weekly_avg['week'],
|
417 |
+
ticktext=df_agents_with_transactions_weekly_avg['week'].dt.strftime('%b %d'),
|
418 |
+
tickangle=0
|
419 |
+
),
|
420 |
+
bargap=0.6, # Increase gap between bar groups (0-1)
|
421 |
+
bargroupgap=0.1, # Decrease gap between bars in a group (0-1)
|
422 |
+
height=700,
|
423 |
+
width=1200, # Specify width to prevent bars from being too wide
|
424 |
+
margin=dict(l=50, r=50, t=50, b=50), # Add margins
|
425 |
+
showlegend=True,
|
426 |
+
legend=dict(
|
427 |
+
yanchor="top",
|
428 |
+
y=0.99,
|
429 |
+
xanchor="right",
|
430 |
+
x=0.99
|
431 |
+
)
|
432 |
+
)
|
433 |
+
|
434 |
+
return fig_swaps_chain, fig_bridges_chain, fig_agents_registered, fig_agents_with_transactions_daily,fig_tvl
|
435 |
+
|
436 |
+
# Gradio interface
|
437 |
+
def dashboard():
|
438 |
+
with gr.Blocks() as demo:
|
439 |
+
gr.Markdown("# Valory Transactions Dashboard")
|
440 |
+
with gr.Tab("Chain Daily activity"):
|
441 |
+
fig_tx_chain = create_transcation_visualizations()
|
442 |
+
gr.Plot(fig_tx_chain)
|
443 |
+
|
444 |
+
fig_swaps_chain, fig_bridges_chain, fig_agents_registered, fig_agents_with_transactions_daily,fig_tvl = create_visualizations()
|
445 |
+
#Fetch and display visualizations
|
446 |
+
with gr.Tab("Swaps Daily"):
|
447 |
+
gr.Plot(fig_swaps_chain)
|
448 |
+
|
449 |
+
with gr.Tab("Bridges Daily"):
|
450 |
+
#fig_swaps_chain, fig_bridges_chain, fig_agents_daily, fig_agents_with_transactions_daily,fig_tvl = create_visualizations()
|
451 |
+
gr.Plot(fig_bridges_chain)
|
452 |
+
|
453 |
+
with gr.Tab("Nr of Agents Registered"):
|
454 |
+
#fig_swaps_chain, fig_bridges_chain, fig_agents_daily, fig_agents_with_transactions_daily,fig_tvl = create_visualizations()
|
455 |
+
gr.Plot(fig_agents_registered)
|
456 |
+
|
457 |
+
with gr.Tab("DAA"):
|
458 |
+
#fig_swaps_chain, fig_bridges_chain, fig_agents_daily, fig_agents_with_transactions_daily,fig_tvl = create_visualizations()
|
459 |
+
gr.Plot(fig_agents_with_transactions_daily)
|
460 |
+
|
461 |
+
with gr.Tab("Total Value Locked"):
|
462 |
+
#fig_swaps_chain, fig_bridges_chain, fig_agents_daily, fig_agents_with_transactions_daily, fig_tvl,fig_tvl = create_visualizations()
|
463 |
+
gr.Plot(fig_tvl)
|
464 |
+
|
465 |
+
return demo
|
466 |
+
|
467 |
+
# Launch the dashboard
|
468 |
+
if __name__ == "__main__":
|
469 |
+
dashboard().launch()
|