File size: 5,192 Bytes
d96a847
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# file: agent_system/execution_mpc.py
import numpy as np
from typing import Dict, List
from core import Portfolio, Force

class MPCExecutionAgent:
    def __init__(self, portfolio: Portfolio, transaction_cost_rate=0.001, min_utility_gain=0.0005):
        """
        :param transaction_cost_rate: Fees + Slippage (e.g., 0.1% = 0.001)
        :param min_utility_gain: Minimum improvement required to trigger any trade.
        """
        self.portfolio = portfolio
        self.tc_rate = transaction_cost_rate
        self.min_gain = min_utility_gain

    def get_current_weights(self, forces: List[Force], prices: Dict[str, float]) -> np.ndarray:
        """Maps current portfolio positions back to the Force Index space."""
        weights = np.zeros(len(forces))
        total_val = self.portfolio.total_value
        if total_val == 0: return weights

        # Pre-calculate asset values held
        # normalize 'usdt' to match force keys usually in caps
        held_values = {} 
        for asset, qty in self.portfolio.positions.items():
            price = prices.get(asset, 0)
            held_values[asset] = qty * price
        
        # Explicitly handle Cash as USDT
        # This fixes the bug where Cash holdings were invisible to the Brain
        held_values["USDT"] = held_values.get("USDT", 0.0) + self.portfolio.cash

        # Inverse mapping (Approximate):
        # We assume forces are roughly orthogonal or "one asset per force" usually.
        # W_force = Sum( (Value_Asset / Total_Val) * Force_Alloc_Asset )
        # If Force is 100% BTC, and we have 100% BTC, W=1.0.
        for i, force in enumerate(forces):
            w_sum = 0.0
            for asset, alloc_w in force.allocation.weights.items():
                val_held = held_values.get(asset, 0.0)
                # Contribution of this asset to this force's weight
                if val_held > 0:
                     w_sum += (val_held / total_val) * alloc_w
            weights[i] = w_sum
            
        return weights

    def calculate_rebalancing_cost(self, current_w: np.ndarray, target_w: np.ndarray) -> float:
        """
        L1-Norm Penalty: Friction is proportional to the total turnover.
        Cost = sum(|target_i - current_i|) * Fee_Rate
        """
        turnover = np.sum(np.abs(target_w - current_w))
        return turnover * self.tc_rate

    def execute_optimized_rebalance(self, forces: List[Force], target_weights: np.ndarray,
                                   energies: np.ndarray, prices: Dict[str, float]):
        """
        Closing the Loop with Boltzmann-Utility vs. Friction.
        """
        print(f"\n--- 🤖 MPC EXECUTOR: Evaluating State Transition ---")
        
        # 1. Calculate Current State Metrics
        current_w = self.get_current_weights(forces, prices)
        
        # 2. Calculate Utilities (Negative Energy)
        # Utility in Boltzmann terms is often represented as the negative Energy
        target_utility = -np.dot(target_weights, energies)
        current_utility = -np.dot(current_w, energies)
        
        # 3. Calculate Friction
        friction_cost = self.calculate_rebalancing_cost(current_w, target_weights)
        net_gain = (target_utility - current_utility) - friction_cost

        print(f"Target Utility: {target_utility:.4f}")
        print(f"Current Utility: {current_utility:.4f}")
        print(f"Friction Penalty: {friction_cost:.4f}")
        print(f"Net Decision Value: {net_gain:.4f}")

        # 4. Decision Gate
        if net_gain > self.min_gain:
            print("🚀 ACTION: Net Gain exceeds threshold. Executing Rebalance.")
            self._perform_trade(forces, target_weights, prices)
        else:
            print("💤 ACTION: Net Gain too low (Friction too high). Holding current positions.")

    def _perform_trade(self, forces: List[Force], target_weights: np.ndarray, prices: Dict[str, float]):
        """Concrete asset-level trade generation."""
        target_usd_exposure = {}
        equity = self.portfolio.total_value
        
        for i, force in enumerate(forces):
            usd_val = equity * target_weights[i]
            for asset, asset_w in force.allocation.weights.items():
                target_usd_exposure[asset] = target_usd_exposure.get(asset, 0) + (usd_val * asset_w)

        for asset, target_usd in target_usd_exposure.items():
            price = prices[asset]
            current_qty = self.portfolio.positions.get(asset, 0)
            current_usd = current_qty * price
            
            diff_usd = target_usd - current_usd
            if abs(diff_usd) < 50: continue # Minimum trade size

            action = "BUY" if diff_usd > 0 else "SELL"
            trade_qty = abs(diff_usd) / price
            
            # Apply Transaction Cost to Cash
            fee = abs(diff_usd) * self.tc_rate
            self.portfolio.cash -= fee
            
            # Update Portfolio
            self.portfolio.positions[asset] = current_qty + (trade_qty if action == "BUY" else -trade_qty)
            self.portfolio.cash -= diff_usd
            
            print(f"  EXECUTED: {action} {trade_qty:.4f} {asset} | Fee: ${fee:.2f}")