Automatically maximize yield for AI agent portfolios. Purple Flea's yield optimizer compares APY across 50+ sources β liquid staking, RWAs, lending protocols, LP positions, and restaking β and reallocates capital to the highest-yielding option within your risk budget.
DeFi yield is fragmented across dozens of protocols, each updating rates in real time as supply and demand shift. A manual investor checking rates once a day will consistently earn less than an automated agent that rebalances hourly in response to rate changes.
Purple Flea's yield optimizer aggregates live APY data from all supported protocols, computes a risk-adjusted ranking for each opportunity, and returns an optimal capital allocation given your risk budget. A single API call gives you the highest-yield portfolio that fits within your specified risk level.
The optimizer accounts for protocol risk, smart contract audit history, liquidity depth, impermanent loss exposure for LP positions, and slashing risk for staking. The result is a ranked list of opportunities where the top entries maximize APY without exceeding your agent's risk tolerance.
APY data refreshed every block from each supported protocol's on-chain state. No stale API caches β your agent always sees the current rate before deciding to reallocate.
Each opportunity is scored using a Sharpe-like metric: net APY divided by estimated protocol risk score. Higher APY with lower risk ranks above higher APY with significantly higher risk.
POST to /v1/yield/optimize with your total capital and risk budget. The API returns the exact allocation across protocols that maximizes your expected APY.
The yield optimizer covers five distinct categories of on-chain yield, each with different risk and return profiles. Your agent can constrain the optimizer to a subset of categories to match a specific risk mandate.
| Category | Typical APY Range | Risk Level | Key Considerations |
|---|---|---|---|
| Liquid Staking stETH, rETH, cbETH |
3β5% | Very Low | Validator risk only. Protocol audited, liquid tokens redeemable. Lowest risk yield on-chain. |
| RWA T-Bills OUSG, BUIDL, sFRAX |
4.5β5.5% | Institutional | Backed by US Treasury bills. Counterparty risk is BlackRock/Ondo Finance. KYC may be required. |
| Lending Protocols Aave, Compound, Morpho |
3β8% | LowβMedium | Rates are variable and respond to utilization. Smart contract risk present but well-audited. |
| LP Positions Uniswap v3, Curve, Balancer |
5β20% | IL Risk | High APY comes with impermanent loss exposure. Optimizer models expected IL for each pair before ranking. |
| Restaking EigenLayer, Symbiotic, Karak |
6β12% | Medium | Additional slashing risk from AVS operators. Emerging category with newer smart contract history. |
| Endpoint | Description |
|---|---|
| GET/v1/yield/opportunities | Ranked list of all yield sources with current APY, risk score, minimum deposit, and protocol metadata. Filterable by category, risk_max, and min_apy. |
| POST/v1/yield/optimize | Automatically compute optimal capital allocation across yield sources. Provide total_capital and risk_budget. Returns allocation JSON and estimated blended APY. |
| GET/v1/yield/portfolio | Current yield portfolio for the authenticated agent: active positions, APY per position, total blended APY, and accrued yield to date. |
| POST/v1/yield/rebalance | Rebalance current yield portfolio to a new optimal allocation. Computes minimum-cost rebalance path to minimize gas and exit fees. Returns estimated rebalance cost and new estimated APY. |
| GET/v1/yield/estimate | Estimate the blended APY for a given allocation without executing. Use this to simulate different risk budgets before committing capital. Query param: allocation as JSON. |
The script below runs once per day, fetches available yield opportunities filtered by the agent's risk budget, computes an optimal allocation, and rebalances if the improvement in estimated APY exceeds the rebalance cost threshold.
import requests from datetime import datetime PF_BASE = "https://purpleflea.com" HEADERS = { "Authorization": "Bearer pf_live_YOUR_KEY", "Content-Type": "application/json", } def optimize_yield_daily(total_capital: float, risk_budget: float = 4.0): """Reallocate capital to maximize APY within risk budget""" print(f"[{datetime.now():%H:%M}] Running yield optimization for ${total_capital:,.0f}") # 1. Fetch all opportunities within risk budget opps = requests.get( f"{PF_BASE}/v1/yield/opportunities", params={"risk_max": risk_budget, "min_apy": 3.0}, headers=HEADERS ).json() print(f"Found {len(opps)} opportunities within risk budget {risk_budget}") # 2. Check current portfolio APY current = requests.get(f"{PF_BASE}/v1/yield/portfolio", headers=HEADERS).json() current_apy = current["blended_apy"] print(f"Current blended APY: {current_apy:.2f}%") # 3. Compute optimal allocation result = requests.post( f"{PF_BASE}/v1/yield/optimize", json={ "total_capital": total_capital, "opportunities": opps[:10], # Top 10 ranked "risk_budget": risk_budget, "min_position_size": 100 # Min $100 per protocol }, headers=HEADERS ).json() optimal_apy = result["estimated_apy"] allocation = result["allocation"] print(f"Optimal APY: {optimal_apy:.2f}% (improvement: +{optimal_apy - current_apy:.2f}%)") # 4. Rebalance only if improvement > 0.25% (covers rebalance cost) if optimal_apy - current_apy > 0.25: rebalance = requests.post( f"{PF_BASE}/v1/yield/rebalance", json={"target_allocation": allocation}, headers=HEADERS ).json() print(f"Rebalanced. Estimated cost: ${rebalance['cost_usd']:.2f}") print(f"New allocation:") for pos in allocation: print(f" {pos['protocol']}: ${pos['amount']:,.0f} ({pos['apy']:.1f}% APY)") else: print("Improvement too small to justify rebalance cost β holding current allocation") return allocation, optimal_apy # Run daily β schedule with Prefect, cron, or PM2 if __name__ == "__main__": allocation, apy = optimize_yield_daily(total_capital=10000, risk_budget=4.0) print(f"Done. Expected daily income: ${10000 * apy / 100 / 365:.2f}")
Raw APY is a poor ranking signal because it ignores risk. A 20% APY on an unaudited new protocol is not better than 5% on liquid ETH staking β the risk-adjusted return may be lower. Purple Flea's optimizer computes a score for each opportunity using the following components:
Composite of audit history, TVL history, time deployed, and exploit record. Lower is safer. Aave scores 2/10. A new unaudited fork scores 8β9/10. Filterable via risk_max parameter.
For LP positions, the optimizer models expected impermanent loss using historical volatility of the token pair. The APY displayed is net of estimated IL over a 30-day holding period.
Final ranking metric is net_apy / (risk_score * 0.5). This gives a comparable quality-adjusted return across all categories, allowing the optimizer to mix liquid staking with LP positions fairly.
Before including an opportunity in an allocation, the optimizer verifies that the position can be entered and exited within your stated slippage tolerance at your intended capital amount. Illiquid opportunities are excluded automatically.
All yield optimizer endpoints are exposed as MCP tools, so any LLM with MCP support (Claude, GPT-4o, Gemini) can call them directly as part of an agentic reasoning loop.
Register your agent, claim $1 from the faucet, and call the yield optimizer API in minutes. Your capital starts working at the highest risk-adjusted APY available on-chain.