Spaces:
Sleeping
Sleeping
Commit ·
2acb948
1
Parent(s): d446982
feat(simulator): add feature simulation engine for fee change impact with DB integration
Browse filesFiles changed (3)
45 unmodified lines4647484945 unmodified lines# --- Use the API Key to build the official, reliable Uniswap URL ---UNISWAP_SUBGRAPH_ID = "5zvR82QoaXYFyDEKLZ9t6v9adgnptxYpKpSbxtgVENFV" # The ID you foundUNISWAP_V3_SUBGRAPH_URL = f"https://gateway.thegraph.com/api/{THE_GRAPH_API_KEY}/subgraphs/id/{UNISWAP_SUBGRAPH_ID}"45 unmodified lines46474849505152535455565745 unmodified lines# --- Use the API Key to build the official, reliable Uniswap URL ---UNISWAP_SUBGRAPH_ID = "5zvR82QoaXYFyDEKLZ9t6v9adgnptxYpKpSbxtgVENFV" # The ID you foundUNISWAP_V3_SUBGRAPH_URL = f"https://gateway.thegraph.com/api/{THE_GRAPH_API_KEY}/subgraphs/id/{UNISWAP_SUBGRAPH_ID}"# ------------------ Feature Simulation Config ------------------# A simple constant representing how sensitive trade volume is to fee changes.# 0.5 means a 10% fee increase might lead to a 5% volume decrease.SIMULATION_ELASTICITY_CONSTANT = 0.5# The baseline fee our exchange charges, for revenue calculations (e.g., 0.1%)SIMULATION_BASE_FEE_PERCENT = 0.1
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121# core/feature_simulator.pyimport pandas as pdimport jsonimport sqlite3import sysimport os# Add project root to the Python pathsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))from config import DB_PATH, SIMULATION_ELASTICITY_CONSTANT, SIMULATION_BASE_FEE_PERCENT# --- DATABASE HELPERS ---def get_db_connection():"""Establishes a connection to the SQLite database."""conn = sqlite3.connect(DB_PATH)conn.row_factory = sqlite3.Rowreturn conndef insert_simulation_result(conn: sqlite3.Connection, token_id: int, result: dict):"""Saves a simulation result to the database."""cursor = conn.cursor()cursor.execute("""INSERT INTO simulations (token_id, scenario, baseline, simulated, delta, recommendation, raw_data)VALUES (?, ?, ?, ?, ?, ?, ?)""", (token_id,result['scenario_name'],result['baseline_revenue'],result['simulated_revenue'],result['delta'],result['recommendation'],json.dumps(result)))conn.commit()# --- SIMULATION LOGIC ---def simulate_fee_change_impact(historical_volume_data: pd.Series,proposed_fee_change_percent: float) -> dict:"""Simulates the revenue impact of changing trading fees.Args:historical_volume_data: A pandas Series of 24h trading volumes.proposed_fee_change_percent: The proposed change in fees (e.g., 0.05 for a 0.05% increase).Returns:A dictionary containing the simulation results."""if historical_volume_data.empty:return {}# --- 1. Calculate Baseline Metrics ---avg_daily_volume = historical_volume_data.mean()baseline_fee = SIMULATION_BASE_FEE_PERCENT / 100 # Convert percentage to decimalbaseline_revenue = avg_daily_volume * baseline_fee# --- 2. Model the Impact on Volume (Elasticity) ---# This is a simplified model. A real-world model would be much more complex.# It assumes a linear relationship between fee changes and volume changes.percent_change_in_fee = proposed_fee_change_percent / SIMULATION_BASE_FEE_PERCENTpercent_change_in_volume = -SIMULATION_ELASTICITY_CONSTANT * percent_change_in_feesimulated_volume = avg_daily_volume * (1 + percent_change_in_volume)# --- 3. Calculate Simulated Revenue ---new_fee_percent = SIMULATION_BASE_FEE_PERCENT + proposed_fee_change_percentsimulated_fee = new_fee_percent / 100simulated_revenue = simulated_volume * simulated_fee# --- 4. Determine Delta and Recommendation ---delta = simulated_revenue - baseline_revenueif delta > 0:recommendation = f"Positive Impact: The proposed fee change is projected to increase revenue by ${delta:,.2f}."elif delta < 0:recommendation = f"Negative Impact: The proposed fee change is projected to decrease revenue by ${abs(delta):,.2f}."else:recommendation = "Neutral Impact: No significant revenue change projected."result = {"scenario_name": f"Fee Change from {SIMULATION_BASE_FEE_PERCENT}% to {new_fee_percent}%","baseline_revenue": baseline_revenue,"simulated_revenue": simulated_revenue,"delta": delta,"recommendation": recommendation,"inputs": {"avg_daily_volume": avg_daily_volume,"proposed_fee_change_percent": proposed_fee_change_percent}}return result# You could add other simulation functions here, e.g., simulate_latency_impact()if __name__ == '__main__':# Example of how to run the simulator directly for testingprint("--- Running Feature Simulator Test ---")conn = get_db_connection()# Fetching some sample volume data for BTC (token_id=1)df = pd.read_sql_query("SELECT volume_24h FROM prices WHERE token_id = 1", conn)if not df.empty:# Test a scenario: increasing the fee by 0.02%proposed_change = 0.02simulation_result = simulate_fee_change_impact(df['volume_24h'], proposed_change)if simulation_result:print(f"Scenario: {simulation_result['scenario_name']}")print(f" Baseline Daily Revenue: ${simulation_result['baseline_revenue']:,.2f}")print(f" Simulated Daily Revenue: ${simulation_result['simulated_revenue']:,.2f}")print(f" Projected Delta: ${simulation_result['delta']:,.2f}")print(f" Recommendation: {simulation_result['recommendation']}")# Example of saving the result# insert_simulation_result(conn, 1, simulation_result)# print("\nTest result saved to database.")else:print("Not enough data in the database to run a simulation test.")conn.close()
__pycache__/config.cpython-313.pyc
config.py+9-1
core/feature_simulator.py+121