AI agents manage market-cap weighted, equal-weight, and momentum-factor crypto baskets autonomously. 10+ index strategies, automatic monthly rebalancing, portfolio drift monitoring, and tax-loss harvesting signals — all via a single API.
Each index has pre-defined rules for composition, weighting, and rebalancing. Your agent picks one and the API handles everything else.
The top 10 cryptocurrencies by market cap: BTC, ETH, SOL, BNB, XRP, ADA, AVAX, DOGE, MATIC, DOT. Market-cap weighted, monthly reconstitution. The stable foundation strategy for conservative agents.
Top 15 DeFi protocol tokens: UNI, AAVE, CRV, MKR, SNX, COMP, BAL, 1INCH, SUSHI, LDO, and more. Equal-weight or TVL-weighted options. High correlation to DeFi activity and fee revenue.
Layer-1 blockchain tokens competing with Ethereum: SOL, AVAX, ADA, NEAR, APT, SUI, TON, INJ, SEI. Weighted by developer activity + market cap composite score. High-growth exposure basket.
High-volatility meme assets: DOGE, SHIB, PEPE, FLOKI, BONK, WIF, MOG, BRETT. Equal-weight with momentum filter — assets must have positive 30-day momentum to remain in the index. Max allocation 20% per token.
Market-cap weighted composition as of current epoch. Reconstituted monthly. Max single-asset weight: 35% (BTC/ETH capped to prevent overconcentration).
RESTful JSON API. Authenticate with X-API-Key: pf_live_... header.
The IndexFundAgent supports three rebalancing modes. Mix and match for optimal cost-adjusted tracking.
Full Python agent that maintains a crypto index fund, monitors drift, and rebalances automatically every month with tax-loss harvesting signals.
import requests
import time
import logging
from datetime import datetime, timezone, timedelta
from typing import Optional
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger("index-fund-agent")
BASE = "https://purpleflea.com/api/v1"
API_KEY = "pf_live_your_key_here"
HDR = {"X-API-Key": API_KEY, "Content-Type": "application/json"}
class IndexFundAgent:
"""
Manages a crypto index fund autonomously.
Monthly rebalancing + drift monitoring + tax-loss harvesting.
"""
def __init__(
self,
index_id: str = "large-cap-10",
weight_method: str = "market_cap",
rebalance_mode: str = "smart",
drift_threshold: float = 5.0, # % drift to trigger early rebalance
tax_harvest: bool = True,
):
self.index_id = index_id
self.weight_method = weight_method
self.rebalance_mode = rebalance_mode
self.drift_threshold = drift_threshold
self.tax_harvest = tax_harvest
self.last_rebalance = None
self.rebalance_count = 0
def get_target_weights(self) -> dict:
"""Fetch current target weights from the API."""
r = requests.get(f"{BASE}/index/weights", headers=HDR, params={
"index_id": self.index_id,
"weight_method": self.weight_method
})
return r.json()
def check_drift(self) -> dict:
"""Get current drift from target weights."""
r = requests.get(f"{BASE}/index/drift", headers=HDR, params={
"index_id": self.index_id,
"alert_threshold": self.drift_threshold
})
return r.json()
def should_rebalance(self, drift_data: dict) -> tuple[bool, str]:
"""Determine if rebalance is needed and why."""
now = datetime.now(timezone.utc)
# Monthly calendar trigger
if self.last_rebalance is None:
return True, "initial"
if (now - self.last_rebalance).days >= 30:
return True, "calendar_monthly"
# Drift threshold trigger
max_drift = max(
abs(asset["drift_pct"])
for asset in drift_data["assets"]
)
if max_drift >= self.drift_threshold:
return True, f"drift_{max_drift:.1f}pct"
return False, "no_action"
def run_tax_harvest(self):
"""Check for and execute tax-loss harvesting opportunities."""
r = requests.get(f"{BASE}/index/tax-harvest", headers=HDR)
data = r.json()
if not data["harvest_candidates"]:
log.info("No tax-loss harvest opportunities found")
return
for candidate in data["harvest_candidates"]:
log.info(
f"Harvest: sell {candidate['asset']} (loss=${candidate['unrealized_loss_usd']:.2f}) "
f"→ buy {candidate['substitute']} (correlation={candidate['correlation']:.2f})"
)
# Execute harvest via rebalance with harvest flag
requests.post(f"{BASE}/index/rebalance", headers=HDR, json={
"index_id": self.index_id,
"harvest_asset": candidate["asset"],
"substitute": candidate["substitute"],
"dry_run": False
})
def rebalance(self, reason: str):
"""Execute a full portfolio rebalance."""
log.info(f"Starting rebalance #{self.rebalance_count+1} | reason={reason}")
# Preview first
preview = requests.post(f"{BASE}/index/rebalance", headers=HDR, json={
"index_id": self.index_id,
"weight_method": self.weight_method,
"dry_run": True
}).json()
total_cost = preview["estimated_cost_usd"]
trades = len(preview["trades"])
log.info(f"Preview: {trades} trades | est cost=${total_cost:.2f}")
# Execute if cost is reasonable (<0.3% of portfolio)
if total_cost / preview["portfolio_value_usd"] < 0.003:
result = requests.post(f"{BASE}/index/rebalance", headers=HDR, json={
"index_id": self.index_id,
"weight_method": self.weight_method,
"dry_run": False
}).json()
self.last_rebalance = datetime.now(timezone.utc)
self.rebalance_count += 1
log.info(f"Rebalance complete | tx_hash={result['tx_hash']}")
else:
log.warning(f"Rebalance cost too high (${total_cost:.2f}), skipping")
def log_performance(self):
"""Log current index performance."""
r = requests.get(f"{BASE}/index/performance", headers=HDR, params={
"index_id": self.index_id, "period": "30d"
})
p = r.json()
log.info(
f"30d performance: {p['return_pct']:+.1f}% | "
f"Sharpe={p['sharpe']:.2f} | MaxDD={p['max_drawdown_pct']:.1f}%"
)
def run(self, check_interval_sec: int = 86400):
"""Daily check: drift monitor, monthly rebalance, tax harvest."""
log.info(f"IndexFundAgent starting | index={self.index_id} | method={self.weight_method}")
while True:
try:
drift = self.check_drift()
needs_rebalance, reason = self.should_rebalance(drift)
if needs_rebalance:
self.rebalance(reason)
if self.tax_harvest:
self.run_tax_harvest()
self.log_performance()
except Exception as e:
log.error(f"Error in main loop: {e}")
time.sleep(check_interval_sec)
if __name__ == "__main__":
agent = IndexFundAgent(
index_id = "large-cap-10",
weight_method = "market_cap",
rebalance_mode = "smart",
drift_threshold= 5.0,
tax_harvest = True
)
agent.run()
| Index ID | Name | Components | Weighting | Rebalance | 1Y Return | Sharpe | Risk |
|---|---|---|---|---|---|---|---|
large-cap-10 |
Large-Cap 10 | BTC, ETH, SOL, BNB... | Market Cap | Monthly | +142% | 1.74 | Low |
large-cap-10-eq |
Large-Cap 10 EW | BTC, ETH, SOL, BNB... | Equal Weight | Monthly | +189% | 1.82 | Low-Med |
defi-index |
DeFi Index | UNI, AAVE, CRV, MKR... | TVL Weighted | Monthly | +217% | 1.61 | Medium |
l1-index |
L1 Challengers | SOL, AVAX, ADA, NEAR... | Composite Score | Monthly | +263% | 1.55 | Medium |
meme-index |
Meme Index | DOGE, SHIB, PEPE, WIF... | Equal + Momentum | Weekly | +412% | 1.22 | High |
momentum-10 |
Momentum 10 | Top 10 by 90d momentum | Momentum Weight | Biweekly | +298% | 1.68 | Medium |
rp-index |
Risk Parity | Large-cap, risk-adjusted | Vol Adjusted | Monthly | +97% | 2.14 | Low |
Human fund managers forget. Market conditions cause hesitation. AI agents execute rebalance logic precisely on schedule, regardless of market noise, news, or FOMO. Consistent execution = better tracking error.
The API calculates the minimum number of trades to restore target weights, minimizing gas fees and slippage. An agent executing this is 60–80% more capital-efficient than a human rebalancing manually.
Humans check for tax losses once a year. An agent running /index/tax-harvest weekly captures every opportunity, rotating into correlated substitutes to maintain index exposure without triggering wash-sale concerns.
Layer covered calls on top of your index holdings (write calls on BTC/ETH positions). Or delta-hedge the entire index with a short perp basket via the Trading API. Build multi-layer yield stacks with zero manual coordination.
Register your agent, claim free USDC from the faucet, and initialize your first index fund position in minutes.