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
351
352
353
354
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
import json
def analyze_hlp_vault(days: int = 30, include_24h: bool = True):
"""
Analyze the HLP Vault data from Hyperliquid for the specified number of days.
Args:
days: Number of days to analyze
include_24h: Whether to include detailed 24-hour analysis
Returns:
Dictionary with the analysis results
"""
try:
from hyperliquid.info import Info
from hyperliquid.utils import constants
sdk_available = True
except ImportError:
print("Using mock data as Hyperliquid SDK is not available")
sdk_available = False
# Mock classes for demonstration
class MockInfo:
def __init__(self, base_url=None, chain=None):
self.base_url = base_url or "https://api.hyperliquid.xyz"
self.chain = chain or "arbitrum"
def get_vault_state(self):
# Mock current vault state
return {
"vaults": [
{
"name": "HLP",
"totalShares": "120000000",
"totalAssetValue": "125000000", # $125M TVL
"assetPrice": "1.0",
"apy": "0.25", # 25% APY
"utilization": "0.8" # 80% utilization
}
]
}
def get_vault_history(self, vault_name, start_time=None, end_time=None):
# Generate mock historical data
if not start_time:
start_time = int((datetime.now() - timedelta(days=30)).timestamp() * 1000)
if not end_time:
end_time = int(datetime.now().timestamp() * 1000)
# Create daily timestamps
timestamps = []
current = start_time
while current <= end_time:
timestamps.append(current)
current += 24 * 3600 * 1000 # Add one day
# Generate mock data
history = []
# Base values
base_tvl = 100000000 # $100M starting TVL
base_apy = 0.22 # 22% starting APY
for i, timestamp in enumerate(timestamps):
# Add some randomness and a slight uptrend for TVL
day_factor = i / len(timestamps)
tvl_trend = 1 + (day_factor * 0.25) # Up to 25% increase over period
tvl_random = np.random.normal(1, 0.02) # 2% daily variation
# APY fluctuations
apy_random = np.random.normal(0, 0.02) # 2% daily variation
apy_trend = 0.03 * np.sin(i / 5) # Cyclical component
tvl = base_tvl * tvl_trend * tvl_random
apy = base_apy + apy_random + apy_trend
apy = max(0.15, min(0.35, apy)) # Keep APY between 15% and 35%
# Calculate shares based on TVL and a slightly increasing share price
share_price = 1.0 + (day_factor * 0.05) # Up to 5% increase in share price
shares = tvl / share_price
# Utilization rate with some fluctuation
utilization = 0.75 + (0.1 * np.sin(i / 3)) + np.random.normal(0, 0.03)
utilization = max(0.6, min(0.9, utilization)) # Keep between 60% and 90%
history.append({
"timestamp": timestamp,
"totalAssetValue": tvl,
"totalShares": shares,
"sharePrice": share_price,
"apy": apy,
"utilization": utilization,
"dailyVolume": tvl * 0.05 * np.random.normal(1, 0.3) # ~5% of TVL with variation
})
return history
def get_vault_hourly_data(self, vault_name, hours=24):
# Generate mock hourly data for the last 24 hours
end_time = datetime.now()
start_time = end_time - timedelta(hours=hours)
# Create hourly timestamps
timestamps = []
current = start_time
while current <= end_time:
timestamps.append(int(current.timestamp() * 1000))
current += timedelta(hours=1)
# Generate mock hourly data
hourly_data = []
# Base values (from the last day of historical data)
base_tvl = 125000000 # $125M current TVL
base_apy = 0.25 # 25% current APY
for i, timestamp in enumerate(timestamps):
# Add some intraday pattern and randomness
hour_of_day = datetime.fromtimestamp(timestamp/1000).hour
# TVL fluctuations
time_factor = 1.0
if 0 <= hour_of_day < 8: # Asian hours
time_factor = 0.995
elif 12 <= hour_of_day < 20: # US hours
time_factor = 1.005
tvl_random = np.random.normal(1, 0.003) # 0.3% hourly variation
tvl = base_tvl * time_factor * tvl_random
# APY fluctuations - smaller on hourly timeframe
apy_random = np.random.normal(0, 0.005) # 0.5% hourly variation
apy = base_apy + apy_random
# Share price and shares
share_price = 1.04 + np.random.normal(0, 0.001) # Small variations in share price
shares = tvl / share_price
# Utilization rate
utilization = 0.8 + np.random.normal(0, 0.01)
utilization = max(0.75, min(0.85, utilization))
hourly_data.append({
"timestamp": timestamp,
"totalAssetValue": tvl,
"totalShares": shares,
"sharePrice": share_price,
"apy": apy,
"utilization": utilization,
"hourlyVolume": tvl * 0.002 * np.random.normal(1, 0.5) # ~0.2% of TVL per hour with variation
})
return hourly_data
# Create mock classes
Info = MockInfo
constants = {"MAINNET_API_URL": "https://api.hyperliquid.xyz", "CHAIN": "arbitrum"}
# Initialize the Info client
if sdk_available:
info_client = Info(base_url=constants.MAINNET_API_URL, chain=constants.CHAIN)
else:
info_client = Info()
# Get current vault state
vault_state = info_client.get_vault_state()
current_vault = vault_state["vaults"][0] if "vaults" in vault_state and vault_state["vaults"] else {}
current_tvl = float(current_vault.get("totalAssetValue", 0)) if current_vault else 0
current_apy = float(current_vault.get("apy", 0)) if current_vault else 0
current_utilization = float(current_vault.get("utilization", 0)) if current_vault else 0
# Get historical vault data
end_time = int(datetime.now().timestamp() * 1000)
start_time = int((datetime.now() - timedelta(days=days)).timestamp() * 1000)
vault_history = info_client.get_vault_history("HLP", start_time=start_time, end_time=end_time)
# Process the historical data
results = {}
if vault_history:
# Create a DataFrame with the historical data
df = pd.DataFrame(vault_history)
# Convert timestamp to datetime
df['date'] = pd.to_datetime(df['timestamp'], unit='ms')
# Calculate key metrics
avg_tvl = df['totalAssetValue'].mean()
avg_apy = df['apy'].mean()
avg_utilization = df['utilization'].mean() if 'utilization' in df.columns else None
# Create a summary of results
results = {
'start_date': df['date'].min().strftime('%Y-%m-%d'),
'end_date': df['date'].max().strftime('%Y-%m-%d'),
'days_analyzed': (df['date'].max() - df['date'].min()).days + 1,
'avg_tvl': avg_tvl,
'min_tvl': df['totalAssetValue'].min(),
'max_tvl': df['totalAssetValue'].max(),
'current_tvl': current_tvl,
'avg_apy': avg_apy * 100, # Convert to percentage
'min_apy': df['apy'].min() * 100,
'max_apy': df['apy'].max() * 100,
'current_apy': current_apy * 100,
'avg_utilization': avg_utilization * 100 if avg_utilization is not None else None,
'current_utilization': current_utilization * 100
}
# Create plots
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(12, 15))
# Plot TVL
ax1.plot(df['date'], df['totalAssetValue'] / 1e6, 'b-', linewidth=2)
ax1.set_title('HLP Vault Total Value Locked (TVL)')
ax1.set_ylabel('TVL (Million USD)')
ax1.grid(True)
# Plot APY
ax2.plot(df['date'], df['apy'] * 100, 'g-', linewidth=2)
ax2.set_title('HLP Vault APY')
ax2.set_ylabel('APY (%)')
ax2.grid(True)
# Plot Utilization
if 'utilization' in df.columns:
ax3.plot(df['date'], df['utilization'] * 100, 'r-', linewidth=2)
ax3.set_title('HLP Vault Utilization Rate')
ax3.set_ylabel('Utilization (%)')
ax3.set_xlabel('Date')
ax3.grid(True)
plt.tight_layout()
plt.show()
# Print the results
print("\n=== HYPERLIQUID HLP VAULT ANALYSIS ===")
print(f"Period: {results['start_date']} to {results['end_date']} ({results['days_analyzed']} days)")
print("\nTotal Value Locked (TVL):")
print(f"Average TVL: ${results['avg_tvl']:,.2f} (${results['avg_tvl']/1e6:.2f}M)")
print(f"Range: ${results['min_tvl']/1e6:.2f}M - ${results['max_tvl']/1e6:.2f}M")
print(f"Current TVL: ${results['current_tvl']:,.2f} (${results['current_tvl']/1e6:.2f}M)")
print("\nAnnual Percentage Yield (APY):")
print(f"Average APY: {results['avg_apy']:.2f}%")
print(f"Range: {results['min_apy']:.2f}% - {results['max_apy']:.2f}%")
print(f"Current APY: {results['current_apy']:.2f}%")
if results['avg_utilization'] is not None:
print("\nUtilization Rate:")
print(f"Average Utilization: {results['avg_utilization']:.2f}%")
print(f"Current Utilization: {results['current_utilization']:.2f}%")
# Get 24-hour data if requested
if include_24h:
# Note: This is a hypothetical method - the actual SDK method might have a different name or parameters
hourly_data = info_client.get_vault_hourly_data("HLP", hours=24)
if hourly_data:
# Create a DataFrame with the hourly data
hourly_df = pd.DataFrame(hourly_data)
# Convert timestamp to datetime
hourly_df['datetime'] = pd.to_datetime(hourly_df['timestamp'], unit='ms')
# Calculate key metrics for the last 24 hours
avg_24h_tvl = hourly_df['totalAssetValue'].mean()
avg_24h_apy = hourly_df['apy'].mean()
avg_24h_utilization = hourly_df['utilization'].mean() if 'utilization' in hourly_df.columns else None
# Add to results
results.update({
'24h_start_time': hourly_df['datetime'].min().strftime('%Y-%m-%d %H:%M'),
'24h_end_time': hourly_df['datetime'].max().strftime('%Y-%m-%d %H:%M'),
'24h_hours_analyzed': len(hourly_df),
'24h_avg_tvl': avg_24h_tvl,
'24h_min_tvl': hourly_df['totalAssetValue'].min(),
'24h_max_tvl': hourly_df['totalAssetValue'].max(),
'24h_avg_apy': avg_24h_apy * 100, # Convert to percentage
'24h_min_apy': hourly_df['apy'].min() * 100,
'24h_max_apy': hourly_df['apy'].max() * 100,
'24h_avg_utilization': avg_24h_utilization * 100 if avg_24h_utilization is not None else None
})
# Create plots for 24-hour data
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 10))
# Plot 24h TVL
ax1.plot(hourly_df['datetime'], hourly_df['totalAssetValue'] / 1e6, 'b-', linewidth=2)
ax1.axhline(y=avg_24h_tvl / 1e6, color='r', linestyle='--', label=f'24h Avg: ${avg_24h_tvl/1e6:.2f}M')
ax1.set_title('HLP Vault TVL (Last 24 Hours)')
ax1.set_ylabel('TVL (Million USD)')
ax1.grid(True)
ax1.legend()
# Plot 24h APY
ax2.plot(hourly_df['datetime'], hourly_df['apy'] * 100, 'g-', linewidth=2)
ax2.axhline(y=avg_24h_apy * 100, color='r', linestyle='--', label=f'24h Avg: {avg_24h_apy*100:.2f}%')
ax2.set_title('HLP Vault APY (Last 24 Hours)')
ax2.set_ylabel('APY (%)')
ax2.set_xlabel('Time')
ax2.grid(True)
ax2.legend()
plt.tight_layout()
plt.show()
# Print 24-hour results
print("\n=== LAST 24 HOURS ANALYSIS ===")
print(f"Period: {results['24h_start_time']} to {results['24h_end_time']}")
print("\nTotal Value Locked (TVL) - Last 24 Hours:")
print(f"Average TVL: ${results['24h_avg_tvl']:,.2f} (${results['24h_avg_tvl']/1e6:.2f}M)")
print(f"Range: ${results['24h_min_tvl']/1e6:.2f}M - ${results['24h_max_tvl']/1e6:.2f}M")
print("\nAnnual Percentage Yield (APY) - Last 24 Hours:")
print(f"Average APY: {results['24h_avg_apy']:.2f}%")
print(f"Range: {results['24h_min_apy']:.2f}% - {results['24h_max_apy']:.2f}%")
if results['24h_avg_utilization'] is not None:
print("\nUtilization Rate - Last 24 Hours:")
print(f"Average Utilization: {results['24h_avg_utilization']:.2f}%")
return results
# Run the analysis for the HLP Vault
results = analyze_hlp_vault(days=30, include_24h=True)
if results:
# Additional context about what this means
print("\n=== ANALYSIS CONTEXT ===")
print("The HLP Vault is Hyperliquid's liquidity pool where users can deposit assets")
print("to earn yield by providing liquidity to the exchange.")
print("\nKey metrics explained:")
print("- TVL (Total Value Locked): The total value of assets deposited in the vault")
print("- APY: The annualized yield earned by liquidity providers")
print("- Utilization: The percentage of deposited assets being used for trading")
# Compare 24h to 30-day averages if available
if '24h_avg_tvl' in results and 'avg_tvl' in results:
tvl_diff_pct = ((results['24h_avg_tvl'] / results['avg_tvl']) - 1) * 100
print(f"\nThe 24-hour average TVL (${results['24h_avg_tvl']/1e6:.2f}M) is {abs(tvl_diff_pct):.2f}% " +
f"{'HIGHER' if tvl_diff_pct > 0 else 'LOWER'} than the 30-day average (${results['avg_tvl']/1e6:.2f}M).")
if '24h_avg_apy' in results and 'avg_apy' in results:
apy_diff_pct = ((results['24h_avg_apy'] / results['avg_apy']) - 1) * 100
print(f"The 24-hour average APY ({results['24h_avg_apy']:.2f}%) is {abs(apy_diff_pct):.2f}% " +
f"{'HIGHER' if apy_diff_pct > 0 else 'LOWER'} than the 30-day average ({results['avg_apy']:.2f}%).")No Output
Run the code to generate an output.