Spaces:
Sleeping
Sleeping
Commit ·
fef93db
1
Parent(s): 66eb00a
feat(core): add analytics engine with technical indicators and arbitrage detection
Browse filesFiles changed (2)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161# core/analytics.pyimport pandas as pdimport ta # <--- NEW LIBRARYimport sqlite3import jsonimport sysimport osfrom datetime import datetime, timezone, timedelta# Add project root to the Python pathsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))from config import DB_PATH, TOKENS# --- CONFIGURATION ---DATA_LOOKBACK_HOURS = 72ARBITRAGE_THRESHOLD = 0.01 # 1%# --- DATABASE HELPERS ---def get_db_connection():"""Establishes a connection to the SQLite database."""conn = sqlite3.connect(DB_PATH)conn.row_factory = sqlite3.Rowreturn conndef get_token_id(conn, symbol):"""Fetches the ID for a given token symbol."""return conn.execute("SELECT id FROM tokens WHERE symbol = ?", (symbol,)).fetchone()['id']def insert_indicators(conn, token_id, indicators):"""Inserts the latest calculated indicators into the database."""cursor = conn.cursor()# Storing None for vwap and realized_vol for nowcursor.execute("""INSERT INTO indicators (token_id, sma10, sma30, ema, rsi14, vwap24h, realized_vol, raw_data)VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", (token_id,indicators.get('SMA_10'),indicators.get('SMA_30'),indicators.get('EMA_14'),indicators.get('RSI_14'),None, # VWAP temporarily removedNone, # Realized Volatility temporarily removedjson.dumps(indicators)))conn.commit()def insert_arbitrage(conn, token_id, opp):"""Inserts a detected arbitrage opportunity into the database."""cursor = conn.cursor()cursor.execute("""INSERT INTO arbitrage (token_id, source_a, source_b, price_diff, percent_diff, raw_data)VALUES (?, ?, ?, ?, ?, ?)""", (token_id,opp['source_a'],opp['source_b'],opp['price_diff'],opp['percent_diff'],json.dumps(opp)))conn.commit()# --- ANALYTICS FUNCTIONS ---def calculate_technical_indicators(df: pd.DataFrame) -> dict:"""Calculates a set of technical indicators using the 'ta' library."""if df.empty or len(df) < 30:print("Warning: Not enough data points to calculate all indicators.")return {}# Use the 'ta' library to calculate indicators# It automatically finds the 'close' columndf['SMA_10'] = ta.trend.sma_indicator(df['close'], window=10)df['SMA_30'] = ta.trend.sma_indicator(df['close'], window=30)df['EMA_14'] = ta.trend.ema_indicator(df['close'], window=14)df['RSI_14'] = ta.momentum.rsi(df['close'], window=14)# Get the most recent indicator valueslatest_indicators = df.iloc[-1].to_dict()# Clean up NaN values for JSON serializationreturn {k: v for k, v in latest_indicators.items() if pd.notna(v)}def detect_arbitrage(df: pd.DataFrame) -> list:"""Detects arbitrage opportunities from the latest prices across different sources."""opportunities = []latest = df.sort_values('timestamp').drop_duplicates('source', keep='last')if len(latest) < 2:return []import itertoolsfor (idx_a, row_a), (idx_b, row_b) in itertools.combinations(latest.iterrows(), 2):price_a = row_a['price_usd']price_b = row_b['price_usd']price_diff = abs(price_a - price_b)percent_diff = price_diff / min(price_a, price_b)if percent_diff >= ARBITRAGE_THRESHOLD:if price_a < price_b:buy_source, sell_source = row_a['source'], row_b['source']buy_price, sell_price = price_a, price_belse:buy_source, sell_source = row_b['source'], row_a['source']buy_price, sell_price = price_b, price_aopportunities.append({"source_a": f"Buy at {buy_source}","source_b": f"Sell at {sell_source}","price_diff": sell_price - buy_price,"percent_diff": percent_diff * 100,"buy_price": buy_price,"sell_price": sell_price,})return opportunities# --- MAIN RUNNER ---def run_analytics():"""Main function to run all analytics for all configured tokens."""print("Starting analytics engine...")conn = get_db_connection()for token_config in TOKENS:symbol = token_config['symbol']print(f"--- Processing analytics for {symbol} ---")try:token_id = get_token_id(conn, symbol)lookback_time = (datetime.now(timezone.utc) - timedelta(hours=DATA_LOOKBACK_HOURS)).isoformat()query = "SELECT * FROM prices WHERE token_id = ? AND timestamp >= ? ORDER BY timestamp ASC"df = pd.read_sql_query(query, conn, params=(token_id, lookback_time))if df.empty:print(f"No recent price data found for {symbol}. Skipping.")continue# Prepare DataFrame: 'ta' needs a 'close' columndf.rename(columns={'price_usd': 'close'}, inplace=True)indicators = calculate_technical_indicators(df.copy())if indicators:insert_indicators(conn, token_id, indicators)print(f"Successfully calculated and stored indicators for {symbol}.")# Rename back to original for arbitrage detectiondf.rename(columns={'close': 'price_usd'}, inplace=True)arbitrage_opps = detect_arbitrage(df)if arbitrage_opps:for opp in arbitrage_opps:insert_arbitrage(conn, token_id, opp)print(f"Found and stored {len(arbitrage_opps)} arbitrage opportunity for {symbol}.")except Exception as e:print(f"An error occurred while processing {symbol}: {e}")conn.close()print("\nAnalytics engine run complete.")if __name__ == "__main__":run_analytics()
__pycache__/config.cpython-313.pyc
core/analytics.py+161