agent_system / execution.py
janggi3's picture
Upload folder using huggingface_hub
d96a847 verified
Raw History Blame Contribute Delete
6.83 kB
#
# file: agent_system/execution.py
from typing import List, Dict
import numpy as np
from core import Portfolio, Force
class ExecutionAgent:
def __init__(self, portfolio: Portfolio):
self.portfolio = portfolio
def execute_rebalance(self, forces: List[Force], weights: np.ndarray, prices: Dict[str, float]):
print(f"\n--- 🤖 EXECUTION: Rebalancing ---")
# 1. Calculate Target USD exposure per asset
target_exposure = {}
equity = self.portfolio.total_value
for i, force in enumerate(forces):
w = weights[i]
if w < 0.01: continue
usd_allocation = equity * w
for asset, asset_w in force.allocation.weights.items():
target_exposure[asset] = target_exposure.get(asset, 0) + (usd_allocation * asset_w)
# 2. Generate Orders
for sym, price in prices.items():
current_qty = self.portfolio.positions.get(sym, 0.0)
current_usd = current_qty * price
target_usd = target_exposure.get(sym, 0.0)
diff_usd = target_usd - current_usd
if abs(diff_usd) < 50.0: continue # Dust filter
action = "BUY" if diff_usd > 0 else "SELL"
qty = abs(diff_usd) / price
print(f"ORDER: {action} {qty:.4f} {sym} (Value: ${abs(diff_usd):.2f})")
# Update Internal State (Simulation)
self.portfolio.cash -= diff_usd
self.portfolio.positions[sym] = self.portfolio.positions.get(sym, 0) + (qty if action == "BUY" else -qty)
# file: agent_system/execution.py
"""class MPCExecutor:
def __init__(self, fee_rate=0.002, min_gain=0.001):
self.fee_rate = fee_rate
self.min_gain = min_gain
def rebalance(self, portfolio, forces, target_w, prices):
current_total_val = portfolio.total_value
# 1. Map Force weights to Asset Target USD values
# We initialize ONLY for assets that are not the base cash (USDT)
target_usd_assets = {symbol: 0.0 for symbol in prices.keys() if symbol != "USDT"}
for i, force in enumerate(forces):
force_weight = target_w[i]
for asset_symbol, asset_alloc_weight in force.allocation.weights.items():
if asset_symbol in target_usd_assets:
# Target Value = Total Portfolio * Force Weight * Asset's weight in that Force
target_usd_assets[asset_symbol] += (current_total_val * force_weight * asset_alloc_weight)
# 2. Execute Asset Trades
for asset, t_usd in target_usd_assets.items():
price = prices[asset]
# Use .get() with a default of 0.0 to prevent KeyError
current_qty = portfolio.positions.get(asset, 0.0)
current_usd_val = current_qty * price
diff_usd = t_usd - current_usd_val
# MPC Friction Filter: Only trade if move is significant
if abs(diff_usd) > (current_total_val * self.min_gain):
execution_fee = abs(diff_usd) * self.fee_rate
# Update Cash (USDT)
portfolio.cash -= (diff_usd + execution_fee)
# Update Asset Position
portfolio.positions[asset] = current_qty + (diff_usd / price)
action = "BUY" if diff_usd > 0 else "SELL"
print(f" [MPC] {action} {asset}: ${abs(diff_usd):.2f} | Fee: ${execution_fee:.2f}")
# 3. Final Portfolio Sync
portfolio.update(prices)"""
"""class MPCExecutor:
def __init__(self, fee_rate=0.002, min_gain=0.001):
self.fee_rate = fee_rate
self.min_gain = min_gain
def rebalance(self, portfolio, forces, target_w, prices):
current_total = portfolio.total_value
target_usd_assets = {sym: 0.0 for sym in prices.keys() if sym != "USDT"}
for i, force in enumerate(forces):
f_weight = target_w[i]
for asset, a_weight in force.allocation.weights.items():
if asset in target_usd_assets:
target_usd_assets[asset] += (current_total * f_weight * a_weight)
for asset, t_usd in target_usd_assets.items():
price = prices[asset]
current_qty = portfolio.positions.get(asset, 0.0)
current_usd = current_qty * price
diff = t_usd - current_usd
if abs(diff) > (current_total * self.min_gain):
fee = abs(diff) * self.fee_rate
portfolio.cash -= (diff + fee)
portfolio.positions[asset] = current_qty + (diff / price)
portfolio.update(prices)"""
# file: agent_system/executor.py
class MPCExecutor:
def __init__(self, fee_rate=0.002, min_gain_threshold=0.01):
"""
:param fee_rate: Trading fee (e.g., 0.002 = 0.2%)
:param min_gain_threshold: The 'Safety Buffer'.
Only trade if the position change > 1% of total portfolio.
"""
self.fee_rate = fee_rate
self.min_gain = min_gain_threshold
def rebalance(self, portfolio, forces, target_w, prices):
current_total = portfolio.total_value
target_usd_assets = {sym: 0.0 for sym in prices.keys() if sym != "USDT"}
# 1. Map Force Weights -> Asset Weights (Target State)
for i, force in enumerate(forces):
f_weight = target_w[i]
for asset, a_weight in force.allocation.weights.items():
if asset in target_usd_assets:
target_usd_assets[asset] += (current_total * f_weight * a_weight)
# 2. Threshold Execution (The Safety Buffer)
for asset, t_usd in target_usd_assets.items():
price = prices[asset]
current_qty = portfolio.positions.get(asset, 0.0)
current_usd = current_qty * price
# Calculate the absolute difference in USD
diff_usd = t_usd - current_usd
# --- THE SAFETY CHECK ---
# If the trade size is less than 1% of our total money, IGNORE IT.
# This stops 'micro-trading' and saves massive fees.
if abs(diff_usd) < (current_total * self.min_gain):
continue # Skip this trade
# 3. Apply Fees and Execute
fee = abs(diff_usd) * self.fee_rate
portfolio.cash -= (diff_usd + fee)
portfolio.positions[asset] = current_qty + (diff_usd / price)
print(f"⚖️ Rebalanced {asset}: Moved ${diff_usd:,.2f} (Fee: ${fee:,.2f})")
portfolio.update(prices)