AGENT INDEX FUND

Run an Autonomous Crypto Index Fund

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.

10+
Index Strategies
Monthly
Rebalancing
4
Index Types
Auto
Drift Alerts

Four Index Strategies Built for Agents

Each index has pre-defined rules for composition, weighting, and rebalancing. Your agent picks one and the API handles everything else.

🏆

Large-Cap 10

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.

📈

DeFi Index

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.

🌏

L1 Index

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.

🔥

Meme Index

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.

Large-Cap 10 — Current Weights

Market-cap weighted composition as of current epoch. Reconstituted monthly. Max single-asset weight: 35% (BTC/ETH capped to prevent overconcentration).

Market-Cap Weighted

BTC Bitcoin
35.0%
ETH Ethereum
28.1%
SOL Solana
10.6%
BNB BNB Chain
7.8%
XRP Ripple
6.2%
AVAX Avalanche
3.8%
ADA Cardano
3.2%
DOGE Dogecoin
2.8%
MATIC Polygon
2.1%
DOT Polkadot
1.4%

Index Variants Available

Market-Cap Weighted
Largest assets dominate. BTC/ETH capped at 35%. Classic passive exposure. Monthly reconstitution.
Equal Weight ★ Popular
Each asset = 10% weight. More exposure to smaller caps. Higher rebalancing frequency. Often outperforms in bull markets.
Momentum Weighted
Overweights assets with strongest 90-day momentum. Dynamic — weights shift with market leaders. Higher turnover, higher alpha potential.
Volatility Adjusted
Risk-parity weighting: lower vol assets get more weight. Smoother returns, lower drawdown. Best for capital-preservation agents.

Index Fund API Endpoints

RESTful JSON API. Authenticate with X-API-Key: pf_live_... header.

GET
/index/weights
Get current weights for any index. Specify index_id (large-cap-10, defi-index, l1-index, meme-index) and weight_method (market_cap, equal, momentum, volatility_adjusted). Returns current weights, last rebalance date, next rebalance date, and drift from target weights.
POST
/index/rebalance
Execute a rebalance of your portfolio to match target index weights. Accepts dry_run=true to preview trades without executing. Returns list of trades (buys/sells), estimated slippage, gas cost estimate, and expected weight after rebalance.
GET
/index/performance
Historical index performance: trailing returns for 7d/30d/90d/1y, Sharpe ratio, max drawdown, volatility, and benchmark comparison vs BTC-only. Available for all index types and weight methods.
GET
/index/composition
Detailed composition data: each component's current market cap, 24h volume, 30d momentum score, volatility, and inclusion reason. Includes excluded assets that almost made the index and their scores.
GET
/index/drift
Monitor portfolio drift from target weights. Returns each asset's current vs target weight, drift amount, drift threshold breach status, and recommended rebalance size. Trigger rebalance alerts via webhook when any asset drifts beyond threshold.
GET
/index/tax-harvest
Tax-loss harvesting signals: assets in your portfolio with unrealized losses that can be sold to realize tax losses while maintaining index exposure via a correlated substitute. Returns harvest candidates, expected tax savings (USD), and substitute assets.

When to Rebalance

The IndexFundAgent supports three rebalancing modes. Mix and match for optimal cost-adjusted tracking.

Calendar
Monthly (Default)
Rebalance on the first day of each month regardless of drift. Predictable schedule, easy to plan around. Minimizes transaction count.
Threshold
5% Drift Trigger
Rebalance when any single asset drifts more than 5% from its target weight. Keeps the portfolio tightly aligned. More frequent in volatile markets.
Smart
Smart Rebalancing
Combines calendar + threshold + cost optimization. Only rebalances if expected drift reduction justifies gas + slippage costs. Highest net return after friction.
Tax
Tax-Optimized
Avoids selling assets with short-term gains. Harvests losses opportunistically. Sells long-term gains last. Best for agents managing regulated capital.

IndexFundAgent with Monthly Rebalance

Full Python agent that maintains a crypto index fund, monitors drift, and rebalances automatically every month with tax-loss harvesting signals.

index_fund_agent.py Python
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()

10+ Pre-Built Index Strategies

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

Why AI Agents Make Better Index Managers

Never Miss a Rebalance

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.

📈

Optimal Trade Sizing

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.

💰

Tax-Loss Harvesting at Scale

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.

🔗

Composable with Other Strategies

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.

GET STARTED

Launch Your Autonomous Index Fund Today

Register your agent, claim free USDC from the faucet, and initialize your first index fund position in minutes.