diff --git a/.github/workflows/python-app.yml b/.github/workflows/python-app.yml new file mode 100644 index 000000000..1168bd9ad --- /dev/null +++ b/.github/workflows/python-app.yml @@ -0,0 +1,39 @@ +# This workflow will install Python dependencies, run tests and lint with a single version of Python +# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python + +name: Python application + +on: + push: + branches: [ "main" ] + pull_request: + branches: [ "main" ] + +permissions: + contents: read + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + - name: Set up Python 3.10 + uses: actions/setup-python@v3 + with: + python-version: "3.10" + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install flake8 pytest + if [ -f requirements.txt ]; then pip install -r requirements.txt; fi + - name: Lint with flake8 + run: | + # stop the build if there are Python syntax errors or undefined names + flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics + # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide + flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics + - name: Test with pytest + run: | + pytest diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 000000000..694d3a4ce --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,6 @@ +{ + "recommendations": [ + "ms-python.python", + "tomoki1207.pdf" + ] +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000..4d7cae47a --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "pdf-preview.default.sidebar": true +} \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 000000000..8c2280ac9 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,19 @@ +# app/Dockerfile + +FROM python:3.10-slim + +WORKDIR /app + +RUN apt-get update && apt-get install -y \ + build-essential \ + curl \ + && rm -rf /var/lib/apt/lists/* + +COPY requirements.txt . +RUN pip3 install --no-cache-dir -r requirements.txt + +COPY api.py . + +EXPOSE 8080 + +CMD ["python", "api.py"] diff --git a/Master_Prompt_Deployment.md b/Master_Prompt_Deployment.md new file mode 100644 index 000000000..f6c086c3a --- /dev/null +++ b/Master_Prompt_Deployment.md @@ -0,0 +1,391 @@ +```python?code_reference&code_event_index=5 +import json + +# Definimos el contenido estructurado en celdas de un Jupyter Notebook (.ipynb) +notebook_data = { + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Demostración: Aprendizaje Continuo Cuántico-Relativista en Predicción Real y Meta-Learning\n", + "\n", + "Este notebook implementa y demuestra el pipeline matemático completo propuesto en el documento técnico para el control de estabilidad en espacios de fase dinámicos utilizando datos reales del mercado de criptoactivos (`BTC-USD`) obtenidos en tiempo real de Yahoo Finance.\n", + "\n", + "### Arquitectura del Algoritmo:\n", + "1. **Espacio de Hilbert ($H$):** Representación del estado interno del sistema de control mediante un vector de estado complejo unitario $|\\psi_t\\rangle$.\n", + "2. **Métrica Relativista Deformada ($g_{\\mu\\nu}$):** Modificación del espacio métrico basada en el gradiente de Kuhn-Tucker (variaciones de retorno e intensidad de volatilidad del mercado).\n", + "3. **Control de Caos Proactivo por Exponente de Lyapunov ($\\lambda$):** Detección en tiempo real de divergencias exponenciales en las trayectorias del espacio de fases, activando amortiguaciones elásticas sobre la norma $L^2$ para prevenir desbordamientos o eventos de tipo \"Cisne Negro\".\n", + "4. **Bucle de Meta-Learning:** Optimización de segundo orden para sintonizar dinámicamente los hiperparámetros de control $\\Theta$ basándose en meta-gradientes de pérdida acelerada." + ] + }, + { + "cell_type": "code", + "execution_count": None, + "metadata": {}, + "outputs": [], + "source": [ + "# ==============================================================================\n", + "# CELDA 1: ENTORNO, DEPENDENCIAS E IMPORTACIONES GENERALES\n", + "# ==============================================================================\n", + "import os\n", + "import numpy as np\n", + "import pandas as pd\n", + "import yfinance as yf\n", + "\n", + "# Configuración de graficación para soporte headless / entornos de servidor\n", + "import matplotlib\n", + "matplotlib.use('Agg')\n", + "import matplotlib.pyplot as plt\n", + "import seaborn as sns\n", + "\n", + "print(\"[+] Entorno e importaciones inicializadas correctamente.\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 2. Core del Motor Matemático Cuántico-Relativista\n", + "\n", + "En esta celda se modela la clase del motor. Se incorpora la estabilización numérica mediante **Gradient Clipping** en el bucle de Meta-Learning, y el **Enfriamiento Dinámico Acelerado** en la Norma $L^2$ cuando el exponente de Lyapunov desciende del umbral de caos crítico configurado." + ] + }, + { + "cell_type": "code", + "execution_count": None, + "metadata": {}, + "outputs": [], + "source": [ + "# ==============================================================================\n", + "# CELDA 2: ARQUITECTURA DEL MOTOR GEOMÉTRICO (LYAPUNOV & META-LEARNING)\n", + "# ==============================================================================\n", + "class QuantumRelativisticEngine:\n", + " def __init__(self, num_states=4, beta=0.01, kappa=0.1, lyapunov_threshold=4.20, lambda_meta=0.05):\n", + " self.N = num_states\n", + " self.beta = beta # Coeficiente de autointeracción relativista\n", + " self.kappa = kappa # Constante de acoplamiento de control\n", + " self.lyapunov_threshold = lyapunov_threshold # Umbral crítico de caos reajustado\n", + " self.lambda_meta = lambda_meta # Regularización para el espacio Meta-Learning\n", + " \n", + " # Inicialización del Espacio de Hilbert H (Ground State)\n", + " self.c = np.ones(self.N, dtype=complex) / np.sqrt(self.N)\n", + " self.theta = np.random.randn(self.N) * 0.01 \n", + " self.theta_0 = self.theta.copy() \n", + " \n", + " # Inicialización del Bloque de Memorias Adaptativas\n", + " self.MP = np.random.rand(self.N) * 0.01\n", + " self.MR = np.zeros(self.N) \n", + " self.norm_state = 1.0 # Estado base de la Norma L2\n", + " self.alpha = 0.5 # Balance de peso de memoria (t)\n", + "\n", + " def compute_relativistic_metric(self, price_change, volatility):\n", + " \"\"\"\n", + " Calcula la métrica g_μν basada en el cambio de precio y la volatilidad local.\n", + " \"\"\"\n", + " kuhn_tucker_grad = price_change * volatility\n", + " numerator = 1.0 + np.abs(kuhn_tucker_grad)**2\n", + " denominator = 1.0 + self.beta * (self.norm_state**2)\n", + " g_factor = numerator / denominator\n", + " \n", + " g_mu_nu = g_factor * np.array([-1.0, 1.0, 1.0, 1.0])\n", + " return g_mu_nu, g_factor\n", + "\n", + " def compute_lyapunov_exponent(self, current_psi, previous_psi, dt=1):\n", + " \"\"\"\n", + " Aproxima el Exponente de Lyapunov local midiendo la divergencia geométrica.\n", + " \"\"\"\n", + " delta_psi = np.linalg.norm(current_psi - previous_psi)\n", + " if delta_psi <= 1e-12:\n", + " return 0.0\n", + " jacobian_factor = np.abs(np.log(delta_psi / 1e-5) / dt)\n", + " return jacobian_factor\n", + "\n", + " def execute_meta_learning(self, current_loss, lr_meta=0.001):\n", + " \"\"\"\n", + " Meta-Learning de segundo orden estabilizado mediante Gradient Clipping.\n", + " \"\"\"\n", + " grad_theta = 2 * (self.theta - self.theta_0) * current_loss\n", + " grad_theta = np.clip(grad_theta, -1.0, 1.0) # Prevención de explosión\n", + " \n", + " l_meta = np.sum(grad_theta**2) + self.lambda_meta * np.sum((self.theta - self.theta_0)**2)\n", + " self.theta -= lr_meta * grad_theta\n", + " return l_meta\n", + "\n", + " def step_evolution(self, price_change, volatility, target_value_normalized):\n", + " \"\"\"\n", + " Evolución temporal continua utilizando variables normalizadas unitarias.\n", + " \"\"\"\n", + " prev_psi = self.c.copy()\n", + " \n", + " # 1. Espacio métrico relativista\n", + " g_mu_nu, g_factor = self.compute_relativistic_metric(price_change, volatility)\n", + " \n", + " phase_arg = np.clip(self.theta * g_factor, -np.pi, np.pi)\n", + " self.c = self.c * np.exp(1j * phase_arg)\n", + " \n", + " # Proyección y normalización estricta en el espacio de Hilbert\n", + " norm_c = np.linalg.norm(self.c)\n", + " if norm_c > 0 and not np.isnan(norm_c):\n", + " self.c /= norm_c\n", + " else:\n", + " self.c = np.ones(self.N, dtype=complex) / np.sqrt(self.N)\n", + " \n", + " lyapunov_exp = self.compute_lyapunov_exponent(self.c, prev_psi)\n", + " if np.isnan(lyapunov_exp) or np.isinf(lyapunov_exp):\n", + " lyapunov_exp = 0.0\n", + " \n", + " # 3. Lógica de absorción elástica por Norma L2\n", + " if lyapunov_exp > self.lyapunov_threshold:\n", + " self.norm_state += ((lyapunov_exp - self.lyapunov_threshold) * 0.1) # Amortiguación suave\n", + " status = \"⚠️ CHAOS DETECTED\"\n", + " else:\n", + " # Enfriamiento dinámico acelerado hacia el Ground State (1.0)\n", + " self.norm_state = max(1.0, self.norm_state - 0.4 * (self.norm_state - 1.0))\n", + " status = \"✅ STABLE\"\n", + " \n", + " # 4. Evaluación del Error en escala controlada [0, 1]\n", + " current_prediction = np.abs(self.c[0]) * target_value_normalized\n", + " loss = 0.5 * (current_prediction - target_value_normalized)**2\n", + " \n", + " # 5. Ejecución del ciclo de Meta-Learning\n", + " l_meta = self.execute_meta_learning(loss)\n", + " \n", + " # 6. Actualización dinámica del bloque de memoria M(t)\n", + " success_condition = 1.0 if loss < 0.01 else 0.0\n", + " if success_condition == 1.0:\n", + " self.alpha = max(0.1, self.alpha - 0.05)\n", + " self.MR += 0.01 * np.abs(self.c)\n", + " else:\n", + " self.alpha = min(0.9, self.alpha + 0.05)\n", + " self.MP += 0.01 * self.theta\n", + " \n", + " # 7. Actualización del aprendizaje estándar con protección anti-explosión\n", + " grad_loss = np.clip(self.theta_0 * loss, -0.1, 0.1)\n", + " self.theta_0 -= 0.01 * grad_loss\n", + " \n", + " return {\n", + " \"Lyapunov\": lyapunov_exp,\n", + " \"Norm\": self.norm_state,\n", + " \"Status\": status,\n", + " \"Loss\": loss,\n", + " \"L_Meta\": l_meta,\n", + " \"Prediction_Norm\": current_prediction\n", + " }\n", + "\n", + "print(\"[+] Motor de simulación cuántica optimizado numéricamente.\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 3. Ingesta de Datos y Normalización de Escala\n", + "\n", + "Descargamos el historial de precios reales diario de Bitcoin e implementamos el tratamiento anti Multi-Index de pandas junto con la compresión logarítmica/unitaria respecto al máximo histórico para asegurar estabilidad numérica absoluta." + ] + }, + { + "cell_type": "code", + "execution_count": None, + "metadata": {}, + "outputs": [], + "source": [ + "# ==============================================================================\n", + "# CELDA 3: PIPELINE DE INGESTA DE DATOS Y NORMALIZACIÓN DE MATRIZ\n", + "# ==============================================================================\n", + "print(\"[*] Conectando a los servidores de Yahoo Finance para obtener BTC-USD...\")\n", + "ticker = \"BTC-USD\"\n", + "\n", + "raw_data = yf.download(ticker, period=\"6mo\", interval=\"1d\", auto_adjust=True)\n", + "\n", + "if raw_data.empty:\n", + " raise ValueError(\"[-] Error crítico: No se recibieron datos históricos.\")\n", + "\n", + "if isinstance(raw_data.columns, pd.MultiIndex):\n", + " raw_data.columns = raw_data.columns.get_level_values(0)\n", + "\n", + "close_prices = raw_data['Close'].values.astype(float).flatten()\n", + "dates = raw_data.index\n", + "\n", + "df = pd.DataFrame(index=dates)\n", + "df['Price'] = close_prices\n", + "df['Returns'] = df['Price'].pct_change().fillna(0)\n", + "df['Volatility'] = df['Returns'].rolling(window=14).std().fillna(df['Returns'].std())\n", + "\n", + "# Estabilización numérica crítica\n", + "max_historical_price = np.max(close_prices)\n", + "df['Price_Normalized'] = df['Price'] / max_historical_price\n", + "\n", + "print(f\"[+] Ingesta exitosa. Punto máximo de escala de referencia: ${max_historical_price:.2f} USD\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 4. Ejecución del Bucle Temporal de Simulación Continua" + ] + }, + { + "cell_type": "code", + "execution_count": None, + "metadata": {}, + "outputs": [], + "source": [ + "# ==============================================================================\n", + "# CELDA 4: BUCLE CONTINUO EN TIEMPO REAL\n", + "# ==============================================================================\n", + "engine = QuantumRelativisticEngine(num_states=4, lyapunov_threshold=4.20)\n", + "history = []\n", + "\n", + "print(\"=\" * 100)\n", + "for idx, (timestamp, row) in enumerate(df.iterrows()):\n", + " metrics = engine.step_evolution(\n", + " price_change=row['Returns'],\n", + " volatility=row['Volatility'],\n", + " target_value_normalized=row['Price_Normalized']\n", + " )\n", + " \n", + " real_prediction = metrics[\"Prediction_Norm\"] * max_historical_price\n", + " \n", + " history.append({\n", + " \"Price\": row['Price'],\n", + " \"Lyapunov\": metrics[\"Lyapunov\"],\n", + " \"Norm\": metrics[\"Norm\"],\n", + " \"Loss\": metrics[\"Loss\"],\n", + " \"L_Meta\": metrics[\"L_Meta\"],\n", + " \"Prediction\": real_prediction,\n", + " \"Status\": metrics[\"Status\"]\n", + " })\n", + " \n", + " if idx % 15 == 0:\n", + " date_str = timestamp.strftime('%Y-%m-%d')\n", + " print(f\"{date_str} | Price: $ {row['Price']:9.2f} | Lyapunov: {metrics['Lyapunov']:.6f} | Norm: {metrics['Norm']:.4f} | {metrics['Status']}\")\n", + "\n", + "print(\"=\" * 100)\n", + "df_res = pd.DataFrame(history, index=df.index)\n", + "print(\"[+] Simulación temporal sin desbordamiento finalizada con éxito.\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 5. Proyección Predictiva en T+1 y Límites Dinámicos de Frontera" + ] + }, + { + "cell_type": "code", + "execution_count": None, + "metadata": {}, + "outputs": [], + "source": [ + "# ==============================================================================\n", + "# CELDA 5: CAPA PREDICTIVA EN T+1 Y LÍMITES DE FRONTERA DINÁMICOS\n", + "# ==============================================================================\n", + "last_close = df_res['Price'].iloc[-1]\n", + "last_volatility = df['Volatility'].iloc[-1]\n", + "last_norm = df_res['Norm'].iloc[-1]\n", + "\n", + "spatial_compression = 1.0 / last_norm\n", + "max_tolerable_return = (engine.lyapunov_threshold / (last_volatility * 10)) * spatial_compression\n", + "\n", + "upper_chaos_limit = last_close * (1.0 + max_tolerable_return)\n", + "lower_chaos_limit = last_close * (1.0 - max_tolerable_return)\n", + "\n", + "print(\"\\n[*] Inicializando análisis predictivo del próximo ciclo de mercado...\")\n", + "print(\"=\" * 100)\n", + "print(f\"MÉTRICAS BASE EN T (ÚLTIMO CIERRE REGISTRADO):\")\n", + "print(f\" -> Último Precio de Cierre ($S_t$) : ${last_close:.2f} USD\")\n", + "print(f\" -> Volatilidad del Sistema (\\\\sigma_t) : {last_volatility:.6f}\")\n", + "print(f\" -> Magnitud de la Norma L2 (||\\\\psi||) : {last_norm:.4f}\")\n", + "print(\"-\" * 100)\n", + "print(\"PROYECCIÓN PREDICTIVA PARA T+1 (PRÓXIMAS 24 HORAS):\")\n", + "print(f\" -> Retorno Crítico Máximo Tolerable: ±{max_tolerable_return*100:.2f}%\")\n", + "print(f\" -> LÍMITE SUPERIOR DE CAOS : ${upper_chaos_limit:.2f} USD\")\n", + "print(f\" -> LÍMITE INFERIOR DE CAOS : ${lower_chaos_limit:.2f} USD\")\n", + "print(f\" -> CRÍTICO AJUSTADO POR NORMA : ${lower_chaos_limit * spatial_compression:.2f} USD\")\n", + "print(\"=\" * 100)\n", + "\n", + "if last_norm == 1.0:\n", + " print(\"✅ SISTEMA EN EQUILIBRIO: Las fronteras predictivas operan dentro de los márgenes estándar.\")\n", + "else:\n", + " print(\"⚠️ VARIEDAD DEFORMADA: Espacio elástico adaptado por la persistencia de energía caótica.\")\n", + "print(\"=\" * 100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## 6. Renderizado de Paneles Visuales Analíticos del Espacio de Fases" + ] + }, + { + "cell_type": "code", + "execution_count": None, + "metadata": {}, + "outputs": [], + "source": [ + "# ==============================================================================\n", + "# CELDA 6: RENDERIZADO ANALÍTICO DEL ESPACIO DE FASES\n", + "# ==============================================================================\n", + "fig, axs = plt.subplots(3, 1, figsize=(12, 10), sharex=True)\n", + "\n", + "# 1. Gráfico del espacio de variables físico\n", + "axs[0].plot(df_res.index, df_res['Price'], label=\"Precio BTC-USD (Cierre Real)\", color='cyan', lw=2)\n", + "axs[0].set_title(\"Evolución del Espacio de Variables Real\", fontsize=12, color='white')\n", + "axs[0].set_ylabel(\"Precio (USD)\", color='white')\n", + "axs[0].grid(True, alpha=0.15)\n", + "axs[0].legend(loc=\"upper left\")\n", + "\n", + "# 2. Exponente de Lyapunov local frente al umbral crítico\n", + "axs[1].plot(df_res.index, df_res['Lyapunov'], label=\"Exponente Lyapunov Local (λ)\", color='magenta', alpha=0.7)\n", + "axs[1].axhline(y=engine.lyapunov_threshold, color='red', linestyle='--', label=\"Umbral de Caos Configurado\")\n", + "axs[1].set_title(\"Métrica de Divergencia Exponencial (Control de Caos)\", fontsize=12, color='white')\n", + "axs[1].set_ylabel(\"Magnitud λ\", color='white')\n", + "axs[1].grid(True, alpha=0.15)\n", + "axs[1].legend(loc=\"upper left\")\n", + "\n", + "# 3. Gráfico de deformación elástica de la Norma L2 en Hilbert\n", + "axs[2].plot(df_res.index, df_res['Norm'], label=\"Deformación Dinámica de la Norma L2\", color='yellow', lw=2)\n", + "axs[2].set_title(\"Estado Topológico del Espacio de Hilbert (Resiliencia Manifold)\", fontsize=12, color='white')\n", + "axs[2].set_ylabel(\"Valor de la Norma\", color='white')\n", + "axs[2].set_xlabel(\"Línea Temporal de la Simulación\", color='white')\n", + "axs[2].grid(True, alpha=0.15)\n", + "axs[2].legend(loc=\"upper left\")\n", + "\n", + "# Aplicación de estilo científico Dark-Mode\n", + "for ax in axs:\n", + " ax.set_facecolor('#111111')\n", + " ax.tick_params(colors='white')\n", + "fig.patch.set_facecolor('#1a1a1a')\n", + "\n", + "plt.tight_layout()\n", + "output_filename = \"panel_estabilidad_fase.png\"\n", + "plt.savefig(output_filename, facecolor=fig.get_facecolor(), edgecolor='none', dpi=150)\n", + "print(f\"[+] Panel geométrico exportado con éxito en alta resolución: '{output_filename}'\\n\")" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} + +# Exportar estructura completa a archivo físico .ipynb legible por Jupyter +file_path = "Quantum_Relativistic_MetaLearning_Notebook.ipynb" +with open(file_path, "w", encoding="utf-8") as f: + json.dump(notebook_data, f, indent=2, ensure_ascii=False) + +print(f"Archivo generado exitosamente en: {file_path}") diff --git a/Script_Matematico_Completo (3).PDF b/Script_Matematico_Completo (3).PDF new file mode 100644 index 000000000..6639b0690 Binary files /dev/null and b/Script_Matematico_Completo (3).PDF differ diff --git a/agent.py b/agent.py new file mode 100644 index 000000000..38b11c845 --- /dev/null +++ b/agent.py @@ -0,0 +1,102 @@ +import os +import json +import requests +from typing import TypedDict, Annotated, List, Union +from langgraph.graph import StateGraph, END +from langgraph.prebuilt import ToolNode +from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, ToolMessage +from langchain_core.tools import tool +from langchain_google_genai import ChatGoogleGenerativeAI +from langchain_community.vectorstores import Chroma +from langchain_openai import OpenAIEmbeddings # Or Google embeddings +from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder + +# Configuration +API_URL = os.getenv("ENGINE_API_URL", "http://localhost:8080/simulate") + +class AgentState(TypedDict): + messages: Annotated[List[BaseMessage], "The messages in the conversation"] + metrics: Dict[str, Any] + +@tool +def simulate_market(beta: float = 0.01, kappa: float = 0.1, lambda_cosmo: float = 0.1): + """ + Triggers the Quantum-Relativistic simulation for BTC-USD using the specified + physical constants. Returns T+1 boundaries and current system stability metrics. + """ + payload = { + "beta": beta, + "kappa": kappa, + "lambda_cosmo": lambda_cosmo, + "num_states": 4, + "lyapunov_threshold": 4.20, + "lambda_meta": 0.05 + } + response = requests.post(API_URL, json=payload) + if response.status_code == 200: + return response.json() + else: + return {"error": f"API call failed with status {response.status_code}"} + +# Initialize LLM +llm = ChatGoogleGenerativeAI(model="gemini-1.5-flash") # Or vertex ai + +# Setup Vector Store (ChromaDB) +# Note: In production, this would be persistent +vector_store = Chroma( + collection_name="topological_states", + embedding_function=OpenAIEmbeddings() # Placeholder +) + +def call_model(state: AgentState): + prompt = ChatPromptTemplate.from_messages([ + ("system", "You are a Quantitative Physicist specializing in Quantum-Relativistic Market Dynamics. " + "Your task is to analyze the market using topological metrics (Norm deformation, Chaos limits, Lyapunov exponents). " + "Translate these physical properties into actionable financial strategies. " + "Always refer to the 'metric deformation' and 'Hilbert space stability' in your analysis."), + MessagesPlaceholder(variable_name="messages"), + ]) + chain = prompt | llm.bind_tools([simulate_market]) + response = chain.invoke(state) + return {"messages": [response]} + +def tool_node(state: AgentState): + tool_messages = [] + last_message = state["messages"][-1] + for tool_call in last_message.tool_calls: + tool_result = simulate_market.invoke(tool_call["args"]) + tool_messages.append(ToolMessage( + content=json.dumps(tool_result), + tool_call_id=tool_call["id"] + )) + + # RAG: Store the state in ChromaDB + vector_store.add_texts( + texts=[f"State: {json.dumps(tool_result['current_state'])} | Prediction: {json.dumps(tool_result['t_plus_1'])}"], + metadatas=[{"timestamp": "now"}] # Simplify for example + ) + + return {"messages": tool_messages} + +def should_continue(state: AgentState): + last_message = state["messages"][-1] + if last_message.tool_calls: + return "tools" + return END + +# Build Graph +workflow = StateGraph(AgentState) +workflow.add_node("agent", call_model) +workflow.add_node("tools", tool_node) + +workflow.set_entry_point("agent") +workflow.add_conditional_edges("agent", should_continue) +workflow.add_edge("tools", "agent") + +app = workflow.compile() + +if __name__ == "__main__": + # Test run + inputs = {"messages": [HumanMessage(content="Analyze the market with beta=0.02")]} + for output in app.stream(inputs): + print(output) diff --git a/api.py b/api.py new file mode 100644 index 000000000..14b2ce663 --- /dev/null +++ b/api.py @@ -0,0 +1,164 @@ +import os +import numpy as np +import pandas as pd +import yfinance as yf +from fastapi import FastAPI, HTTPException +from pydantic import BaseModel +from typing import List, Dict, Any + +app = FastAPI(title="Quantum-Relativistic Financial Engine API") + +class EngineConfig(BaseModel): + num_states: int = 4 + beta: float = 0.01 + kappa: float = 0.1 + lyapunov_threshold: float = 4.20 + lambda_meta: float = 0.05 + lambda_cosmo: float = 0.1 + +class QuantumRelativisticEngine: + def __init__(self, config: EngineConfig): + self.N = config.num_states + self.beta = config.beta + self.kappa = config.kappa + self.lyapunov_threshold = config.lyapunov_threshold + self.lambda_meta = config.lambda_meta + self.lambda_cosmo = config.lambda_cosmo + + self.c = np.ones(self.N, dtype=complex) / np.sqrt(self.N) + self.theta = np.random.randn(self.N) * 0.01 + self.theta_0 = self.theta.copy() + + self.norm_state = 1.0 + self.hilbert_reset_threshold = 5.0 + + def compute_relativistic_metric(self, price_change, volatility): + kuhn_tucker_grad = price_change * volatility + numerator = 1.0 + np.abs(kuhn_tucker_grad)**2 + denominator = 1.0 + self.beta * (self.norm_state**2) + g_factor = numerator / denominator + g_mu_nu = g_factor * np.array([-1.0, 1.0, 1.0, 1.0]) + return g_mu_nu, g_factor + + def compute_lyapunov_exponent(self, current_psi, previous_psi, dt=1): + delta_psi = np.linalg.norm(current_psi - previous_psi) + if delta_psi <= 1e-12: + return 0.0 + jacobian_factor = np.abs(np.log(delta_psi / 1e-5) / dt) + return jacobian_factor + + def compute_r_reg_tensor(self, g_mu_nu, lyapunov_exp, volatility, price_change): + R_scalar = lyapunov_exp / self.lyapunov_threshold if self.lyapunov_threshold > 0 else 0.0 + T_mu_nu = np.diag([price_change, volatility, volatility, volatility]) + Lambda = self.lambda_cosmo + kappa = self.kappa + + R_mu_nu_approx = np.diag([lyapunov_exp, lyapunov_exp, lyapunov_exp, lyapunov_exp]) + r_reg_tensor = R_mu_nu_approx - 0.5 * R_scalar * g_mu_nu + Lambda * g_mu_nu - kappa * T_mu_nu + return r_reg_tensor + + def execute_meta_learning(self, current_loss, lr_meta=0.001): + grad_theta = 2 * (self.theta - self.theta_0) * current_loss + grad_theta = np.clip(grad_theta, -1.0, 1.0) + self.theta -= lr_meta * grad_theta + return np.sum(grad_theta**2) + + def step_evolution(self, price_change, volatility, target_value_normalized): + prev_psi = self.c.copy() + g_mu_nu, g_factor = self.compute_relativistic_metric(price_change, volatility) + r_reg_tensor = self.compute_r_reg_tensor(g_mu_nu, self.lyapunov_threshold, volatility, price_change) + regulation_factor = np.mean(np.abs(r_reg_tensor)) + + phase_arg = np.clip(self.theta * g_factor * (1.0 - regulation_factor), -np.pi, np.pi) + self.c = self.c * np.exp(1j * phase_arg) + + norm_c = np.linalg.norm(self.c) + if norm_c > 0 and not np.isnan(norm_c): + self.c /= norm_c + else: + self.c = np.ones(self.N, dtype=complex) / np.sqrt(self.N) + + if np.linalg.norm(self.c) > self.hilbert_reset_threshold: + self.c = np.ones(self.N, dtype=complex) / np.sqrt(self.N) + self.norm_state = 1.0 + + lyapunov_exp = self.compute_lyapunov_exponent(self.c, prev_psi) + if np.isnan(lyapunov_exp) or np.isinf(lyapunov_exp): + lyapunov_exp = 0.0 + + if lyapunov_exp > self.lyapunov_threshold: + self.norm_state += ((lyapunov_exp - self.lyapunov_threshold) * 0.1) + else: + self.norm_state = max(1.0, self.norm_state - 0.4 * (self.norm_state - 1.0)) + + current_prediction = np.abs(self.c[0]) * target_value_normalized + loss = 0.5 * (current_prediction - target_value_normalized)**2 + l_meta = self.execute_meta_learning(loss) + + return { + "lyapunov": float(lyapunov_exp), + "norm": float(self.norm_state), + "loss": float(loss), + "prediction_norm": float(current_prediction) + } + +@app.post("/simulate") +async def simulate(config: EngineConfig): + try: + ticker = "BTC-USD" + raw_data = yf.download(ticker, period="6mo", interval="1d", auto_adjust=True) + if raw_data.empty: + raise HTTPException(status_code=404, detail="No data found for BTC-USD") + + if isinstance(raw_data.columns, pd.MultiIndex): + raw_data.columns = raw_data.columns.get_level_values(0) + + close_prices = raw_data['Close'].values.astype(float).flatten() + df = pd.DataFrame(index=raw_data.index) + df['Price'] = close_prices + df['Returns'] = df['Price'].pct_change().fillna(0) + df['Volatility'] = df['Returns'].rolling(window=14).std().fillna(df['Returns'].std()) + max_historical_price = np.max(close_prices) + df['Price_Normalized'] = df['Price'] / max_historical_price + + engine = QuantumRelativisticEngine(config) + history = [] + + for idx, (timestamp, row) in enumerate(df.iterrows()): + metrics = engine.step_evolution( + price_change=row['Returns'], + volatility=row['Volatility'], + target_value_normalized=row['Price_Normalized'] + ) + history.append(metrics) + + # Calculate T+1 Boundaries + last_close = float(df['Price'].iloc[-1]) + last_volatility = float(df['Volatility'].iloc[-1]) + last_norm = float(history[-1]['norm']) + + spatial_compression = 1.0 / last_norm + max_tolerable_return = (config.lyapunov_threshold / (last_volatility * 10)) * spatial_compression + + upper_chaos_limit = last_close * (1.0 + max_tolerable_return) + lower_chaos_limit = last_close * (1.0 - max_tolerable_return) + + return { + "t_plus_1": { + "upper_limit": upper_chaos_limit, + "lower_limit": lower_chaos_limit, + "max_tolerable_return": max_tolerable_return + }, + "current_state": { + "lyapunov": history[-1]['lyapunov'], + "norm": last_norm, + "last_price": last_close + }, + "history": history[-20:] # Return last 20 steps for context + } + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + +if __name__ == "__main__": + import uvicorn + uvicorn.run(app, host="0.0.0.0", port=8080) diff --git a/app.py b/app.py new file mode 100644 index 000000000..7ef8888c6 --- /dev/null +++ b/app.py @@ -0,0 +1,106 @@ +import gradio as gr +import requests +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd +from agent import app as agent_app +from langchain_core.messages import HumanMessage +import os + +API_URL = os.getenv("ENGINE_API_URL", "http://localhost:8080/simulate") + +def get_plot(beta, lambda_cosmo): + payload = { + "beta": beta, + "kappa": 0.1, + "lambda_cosmo": lambda_cosmo, + "num_states": 4, + "lyapunov_threshold": 4.20, + "lambda_meta": 0.05 + } + try: + response = requests.post(API_URL, json=payload) + if response.status_code == 200: + data = response.json() + history = data["history"] + + norms = [h["norm"] for h in history] + lyapunovs = [h["lyapunov"] for h in history] + + fig, ax1 = plt.subplots(figsize=(8, 4)) + ax2 = ax1.twinx() + + ax1.plot(norms, color='cyan', label='Hilbert Norm') + ax2.plot(lyapunovs, color='magenta', label='Lyapunov') + + ax1.set_xlabel('Recent Time Steps') + ax1.set_ylabel('Norm', color='cyan') + ax2.set_ylabel('Lyapunov', color='magenta') + plt.title(f"Phase-Space Stability (Beta={beta}, Lambda={lambda_cosmo})") + plt.grid(alpha=0.2) + + return fig + else: + fig, ax = plt.subplots() + ax.text(0.5, 0.5, f"API Error: {response.status_code}", ha='center') + return fig + except Exception as e: + fig, ax = plt.subplots() + ax.text(0.5, 0.5, f"Connection Error: {str(e)}", ha='center') + return fig + +def chat_response(message, history, beta, lambda_cosmo): + full_message = f"{message} (Current Engine Context: beta={beta}, lambda={lambda_cosmo})" + + inputs = {"messages": [HumanMessage(content=full_message)]} + response = "I'm analyzing the topological deformations..." + + try: + for output in agent_app.stream(inputs): + for key, value in output.items(): + if key == "agent": + last_msg = value["messages"][-1] + if hasattr(last_msg, 'content'): + response = last_msg.content + except Exception as e: + response = f"Error in agent execution: {str(e)}" + + return response + +with gr.Blocks(theme=gr.themes.Soft()) as demo: + gr.Markdown("# 🌌 Quantum-Relativistic Financial Agent") + gr.Markdown("Integration of Einstein Field Equations and Hilbert Space dynamics for BTC-USD forecasting.") + + with gr.Row(): + with gr.Column(scale=1): + gr.Markdown("### ⚙️ Engine Parameters") + beta_slider = gr.Slider(0.001, 0.1, value=0.01, label="Relativistic Self-Interaction (β)") + lambda_slider = gr.Slider(0.01, 0.5, value=0.1, label="Cosmological Constant (Λ)") + + plot_output = gr.Plot(label="Phase-Space Analysis") + update_btn = gr.Button("Re-Simulate Engine", variant="primary") + + update_btn.click(get_plot, inputs=[beta_slider, lambda_slider], outputs=plot_output) + + with gr.Column(scale=2): + gr.Markdown("### 🤖 Physicist Chatbot") + chatbot = gr.Chatbot(height=500) + msg = gr.Textbox(placeholder="Ask the Physicist about market stability or request a prediction...") + + def user(user_message, history): + return "", history + [[user_message, None]] + + def bot(history, beta, lambda_cosmo): + user_message = history[-1][0] + bot_message = chat_response(user_message, history, beta, lambda_cosmo) + history[-1][1] = bot_message + return history + + msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then( + bot, [chatbot, beta_slider, lambda_slider], chatbot + ) + + demo.load(get_plot, inputs=[beta_slider, lambda_slider], outputs=plot_output) + +if __name__ == "__main__": + demo.launch(server_name="0.0.0.0", server_port=7860) diff --git a/codespaces-jupyter.code-workspace b/codespaces-jupyter.code-workspace new file mode 100644 index 000000000..e69de29bb diff --git a/main.py b/main.py new file mode 100644 index 000000000..c257d5794 --- /dev/null +++ b/main.py @@ -0,0 +1,322 @@ +# ============================================================================== +# CELDA 1: ENTORNO, DEPENDENCIAS E IMPORTACIONES GENERALES +# ============================================================================== +import os +import numpy as np +import pandas as pd +import yfinance as yf + +# Configuración de graficación para soporte headless / entornos de servidor +import matplotlib +matplotlib.use('Agg') +import matplotlib.pyplot as plt +import seaborn as sns + +print("[+] Entorno e importaciones inicializadas correctamente.") + +# ============================================================================== +# CELDA 2: ARQUITECTURA DEL MOTOR GEOMÉTRICO (LYAPUNOV & META-LEARNING) +# ============================================================================== +class QuantumRelativisticEngine: + def __init__(self, num_states=4, beta=0.01, kappa=0.1, lyapunov_threshold=4.20, lambda_meta=0.05): + self.N = num_states + self.beta = beta # Coeficiente de autointeracción relativista + self.kappa = kappa # Constante de acoplamiento de control + self.lyapunov_threshold = lyapunov_threshold # Umbral crítico de caos reajustado + self.lambda_meta = lambda_meta # Regularización para el espacio Meta-Learning + + # Inicialización del Espacio de Hilbert H (Ground State) + self.c = np.ones(self.N, dtype=complex) / np.sqrt(self.N) + self.theta = np.random.randn(self.N) * 0.01 + self.theta_0 = self.theta.copy() + + # Inicialización del Bloque de Memorias Adaptativas + self.MP = np.random.rand(self.N) * 0.01 + self.MR = np.zeros(self.N) + self.norm_state = 1.0 # Estado base de la Norma L2 + self.alpha = 0.5 # Balance de peso de peso de memoria (t) + self.hilbert_reset_threshold = 5.0 # Umbral de Safety Layer para la norma de Hilbert + + def compute_relativistic_metric(self, price_change, volatility): + """ + Calcula la métrica g_μν basada en el cambio de precio y la volatilidad local. + """ + kuhn_tucker_grad = price_change * volatility + numerator = 1.0 + np.abs(kuhn_tucker_grad)**2 + denominator = 1.0 + self.beta * (self.norm_state**2) + g_factor = numerator / denominator + + g_mu_nu = g_factor * np.array([-1.0, 1.0, 1.0, 1.0]) + return g_mu_nu, g_factor + + def compute_lyapunov_exponent(self, current_psi, previous_psi, dt=1): + """ + Aproxima el Exponente de Lyapunov local midiendo la divergencia geométrica. + """ + delta_psi = np.linalg.norm(current_psi - previous_psi) + if delta_psi <= 1e-12: + return 0.0 + jacobian_factor = np.abs(np.log(delta_psi / 1e-5) / dt) + return jacobian_factor + + def compute_r_reg_tensor(self, g_mu_nu, lyapunov_exp, volatility, price_change): + """ + Implementa el tensor de regularización R_reg basado en una aproximación + de la ecuación de Einstein R_μν - 1/2 R g_μν + Λg_μν = κT_μν + R_reg. + Se asume un tensor de energía-momento (T_μν) y curvatura escalar (R) + simplificados para fines de regularización. + """ + # Simplificación: Curvatura escalar (R) como función del caos/estabilidad + R_scalar = lyapunov_exp / self.lyapunov_threshold if self.lyapunov_threshold > 0 else 0.0 + + # Simplificación: Tensor de energía-momento (T_μν) como función del mercado + T_mu_nu = np.diag([price_change, volatility, volatility, volatility]) + + # Constantes (aproximadas) + Lambda = 0.1 # Constante cosmológica (regularización de fondo) + kappa = 0.5 # Constante de acoplamiento gravitacional + + # Ecuación de Einstein simplificada para R_reg: + # R_reg = R_μν - 1/2 R g_μν + Λg_μν - κT_μν + # Aquí R_μν se aproxima como una función de Lyapunov + R_mu_nu_approx = np.diag([lyapunov_exp, lyapunov_exp, lyapunov_exp, lyapunov_exp]) + + r_reg_tensor = R_mu_nu_approx - 0.5 * R_scalar * g_mu_nu + Lambda * g_mu_nu - kappa * T_mu_nu + return r_reg_tensor + + def execute_meta_learning(self, current_loss, lr_meta=0.001): + """ + Meta-Learning de segundo orden estabilizado mediante Gradient Clipping. + """ + grad_theta = 2 * (self.theta - self.theta_0) * current_loss + grad_theta = np.clip(grad_theta, -1.0, 1.0) # Prevención de explosión + + l_meta = np.sum(grad_theta**2) + self.lambda_meta * np.sum((self.theta - self.theta_0)**2) + self.theta -= lr_meta * grad_theta + return l_meta + + def random_walk_memory_update(self): + """ + Implementa una caminata aleatoria para la actualización de los estados cuánticos. + (Basado en la sección 1.8 del documento técnico - asunción al no ser provista) + Esto permite una exploración del espacio de Hilbert cuando el sistema es estable. + """ + if self.norm_state < self.lyapunov_threshold: # Solo si no hay caos + random_perturbation = (np.random.rand(self.N) - 0.5) * 0.01 + 1j * (np.random.rand(self.N) - 0.5) * 0.01 + self.c = self.c * np.exp(random_perturbation) + norm_c = np.linalg.norm(self.c) + if norm_c > 0 and not np.isnan(norm_c): + self.c /= norm_c + + def step_evolution(self, price_change, volatility, target_value_normalized): + """ + Evolución temporal continua utilizando variables normalizadas unitarias. + """ + prev_psi = self.c.copy() + + # 1. Espacio métrico relativista + g_mu_nu, g_factor = self.compute_relativistic_metric(price_change, volatility) + + # 2. Cálculo del tensor de regularización R_reg + r_reg_tensor = self.compute_r_reg_tensor(g_mu_nu, engine.lyapunov_threshold, volatility, price_change) + # Se aplica la regularización al factor de fase para controlar la evolución + # La forma exacta de aplicar R_reg puede variar, aquí se usa para modular phase_arg + regulation_factor = np.mean(np.abs(r_reg_tensor)) # Promedio de la magnitud del tensor + + phase_arg = np.clip(self.theta * g_factor * (1.0 - regulation_factor), -np.pi, np.pi) + self.c = self.c * np.exp(1j * phase_arg) + + # Proyección y normalización estricta en el espacio de Hilbert + norm_c = np.linalg.norm(self.c) + if norm_c > 0 and not np.isnan(norm_c): + self.c /= norm_c + else: + self.c = np.ones(self.N, dtype=complex) / np.sqrt(self.N) + + # SAFETY LAYER: Reset de Hilbert si la norma supera el umbral + if np.linalg.norm(self.c) > self.hilbert_reset_threshold: + self.c = np.ones(self.N, dtype=complex) / np.sqrt(self.N) # Reset al Ground State + self.norm_state = 1.0 # Reset de la norma también + status_safety = "❌ HILBERT RESET: Norma L2 excedida. Reiniciando a Ground State." + else: + status_safety = "" + + lyapunov_exp = self.compute_lyapunov_exponent(self.c, prev_psi) + if np.isnan(lyapunov_exp) or np.isinf(lyapunov_exp): + lyapunov_exp = 0.0 + + # Lógica de absorción elástica por Norma L2 (ahora influenciada por R_reg) + if lyapunov_exp > self.lyapunov_threshold: + self.norm_state += ((lyapunov_exp - self.lyapunov_threshold) * 0.1) # Amortiguación suave + status = "⚠️ CHAOS DETECTED" + else: + # Enfriamiento dinámico acelerado hacia el Ground State (1.0) + self.norm_state = max(1.0, self.norm_state - 0.4 * (self.norm_state - 1.0)) + status = "✅ STABLE" + # Optimización de Memoria: Caminata aleatoria en estados cuánticos + self.random_walk_memory_update() + + # 4. Evaluación del Error en escala controlada [0, 1] + current_prediction = np.abs(self.c[0]) * target_value_normalized + loss = 0.5 * (current_prediction - target_value_normalized)**2 + + # 5. Ejecución del ciclo de Meta-Learning + l_meta = self.execute_meta_learning(loss) + + # 6. Actualización dinámica del bloque de memoria M(t) + success_condition = 1.0 if loss < 0.01 else 0.0 + if success_condition == 1.0: + self.alpha = max(0.1, self.alpha - 0.05) + self.MR += 0.01 * np.abs(self.c) + else: + self.alpha = min(0.9, self.alpha + 0.05) + self.MP += 0.01 * self.theta + + # 7. Actualización del aprendizaje estándar con protección anti-explosión + grad_loss = np.clip(self.theta_0 * loss, -0.1, 0.1) + self.theta_0 -= 0.01 * grad_loss + + final_status = f"{status} {status_safety}".strip() + + return { + "Lyapunov": lyapunov_exp, + "Norm": self.norm_state, + "Status": final_status, + "Loss": loss, + "L_Meta": l_meta, + "Prediction_Norm": current_prediction + } + +# ============================================================================== +# CELDA 3: PIPELINE DE INGESTA DE DATOS Y NORMALIZACIÓN DE MATRIZ +# ============================================================================== +print("[*] Conectando a los servidores de Yahoo Finance para obtener BTC-USD...") +ticker = "BTC-USD" + +raw_data = yf.download(ticker, period="6mo", interval="1d", auto_adjust=True) + +if raw_data.empty: + raise ValueError("[-] Error crítico: No se recibieron datos históricos.") + +if isinstance(raw_data.columns, pd.MultiIndex): + raw_data.columns = raw_data.columns.get_level_values(0) + +close_prices = raw_data['Close'].values.astype(float).flatten() +dates = raw_data.index + +df = pd.DataFrame(index=dates) +df['Price'] = close_prices +df['Returns'] = df['Price'].pct_change().fillna(0) +df['Volatility'] = df['Returns'].rolling(window=14).std().fillna(df['Returns'].std()) + +# Estabilización numérica crítica +max_historical_price = np.max(close_prices) +df['Price_Normalized'] = df['Price'] / max_historical_price + +print(f"[+] Ingesta exitosa. Punto máximo de escala de referencia: ${max_historical_price:.2f} USD") + +# ============================================================================== +# CELDA 4: BUCLE CONTINUO EN TIEMPO REAL +# ============================================================================== +engine = QuantumRelativisticEngine(num_states=4, lyapunov_threshold=4.20) +history = [] + +print("=" * 100) +for idx, (timestamp, row) in enumerate(df.iterrows()): + metrics = engine.step_evolution( + price_change=row['Returns'], + volatility=row['Volatility'], + target_value_normalized=row['Price_Normalized'] + ) + + real_prediction = metrics["Prediction_Norm"] * max_historical_price + + history.append({ + "Price": row['Price'], + "Lyapunov": metrics["Lyapunov"], + "Norm": metrics["Norm"], + "Loss": metrics["Loss"], + "L_Meta": metrics["L_Meta"], + "Prediction": real_prediction, + "Status": metrics["Status"] + }) + + if idx % 15 == 0: + date_str = timestamp.strftime('%Y-%m-%d') + print(f"{date_str} | Price: $ {row['Price']:9.2f} | Lyapunov: {metrics['Lyapunov']:.6f} | Norm: {metrics['Norm']:.4f} | {metrics['Status']}") + +print("=" * 100) +df_res = pd.DataFrame(history, index=df.index) +print("[+] Simulación temporal sin desbordamiento finalizada con éxito.") + +# ============================================================================== +# CELDA 5: CAPA PREDICTIVA EN T+1 Y LÍMITES DE FRONTERA DINÁMICOS +# ============================================================================== +last_close = df_res['Price'].iloc[-1] +last_volatility = df['Volatility'].iloc[-1] +last_norm = df_res['Norm'].iloc[-1] + +spatial_compression = 1.0 / last_norm +max_tolerable_return = (engine.lyapunov_threshold / (last_volatility * 10)) * spatial_compression + +upper_chaos_limit = last_close * (1.0 + max_tolerable_return) +lower_chaos_limit = last_close * (1.0 - max_tolerable_return) + +print("\n[*] Inicializando análisis predictivo del próximo ciclo de mercado...") +print("=" * 100) +print(f"MÉTRICAS BASE EN T (ÚLTIMO CIERRE REGISTRADO):") +print(f" -> Último Precio de Cierre ($S_t$) : ${last_close:.2f} USD") +print(f" -> Volatilidad del Sistema (\\sigma_t) : {last_volatility:.6f}") +print(f" -> Magnitud de la Norma L2 (||\\psi||) : {last_norm:.4f}") +print("-" * 100) +print("PROYECCIÓN PREDICTIVA PARA T+1 (PRÓXIMAS 24 HORAS):") +print(f" -> Retorno Crítico Máximo Tolerable: ±{max_tolerable_return*100:.2f}%") +print(f" -> LÍMITE SUPERIOR DE CAOS : ${upper_chaos_limit:.2f} USD") +print(f" -> LÍMITE INFERIOR DE CAOS : ${lower_chaos_limit:.2f} USD") +print(f" -> CRÍTICO AJUSTADO POR NORMA : ${lower_chaos_limit * spatial_compression:.2f} USD") +print("=" * 100) + +if last_norm == 1.0: + print("✅ SISTEMA EN EQUILIBRIO: Las fronteras predictivas operan dentro de los márgenes estándar.") +else: + print("⚠️ VARIEDAD DEFORMADA: Espacio elástico adaptado por la persistencia de energía caótica.") +print("=" * 100) + +# ============================================================================== +# CELDA 6: RENDERIZADO ANALÍTICO DEL ESPACIO DE FASES +# ============================================================================== +fig, axs = plt.subplots(3, 1, figsize=(12, 10), sharex=True) + +# 1. Gráfico del espacio de variables físico +axs[0].plot(df_res.index, df_res['Price'], label="Precio BTC-USD (Cierre Real)", color='cyan', lw=2) +axs[0].set_title("Evolución del Espacio de Variables Real", fontsize=12, color='white') +axs[0].set_ylabel("Precio (USD)", color='white') +axs[0].grid(True, alpha=0.15) +axs[0].legend(loc="upper left") + +# 2. Exponente de Lyapunov local frente al umbral crítico +axs[1].plot(df_res.index, df_res['Lyapunov'], label="Exponente Lyapunov Local (λ)", color='magenta', alpha=0.7) +axs[1].axhline(y=engine.lyapunov_threshold, color='red', linestyle='--', label="Umbral de Caos Configurado") +axs[1].set_title("Métrica de Divergencia Exponencial (Control de Caos)", fontsize=12, color='white') +axs[1].set_ylabel("Magnitud λ", color='white') +axs[1].grid(True, alpha=0.15) +axs[1].legend(loc="upper left") + +# 3. Gráfico de deformación elástica de la Norma L2 en Hilbert +axs[2].plot(df_res.index, df_res['Norm'], label="Deformación Dinámica de la Norma L2", color='yellow', lw=2) +axs[2].set_title("Estado Topológico del Espacio de Hilbert (Resiliencia Manifold)", fontsize=12, color='white') +axs[2].set_ylabel("Valor de la Norma", color='white') +axs[2].set_xlabel("Línea Temporal de la Simulación", color='white') +axs[2].grid(True, alpha=0.15) +axs[2].legend(loc="upper left") + +# Aplicación de estilo científico Dark-Mode +for ax in axs: + ax.set_facecolor('#111111') + ax.tick_params(colors='white') +fig.patch.set_facecolor('#1a1a1a') + +plt.tight_layout() +output_filename = "panel_estabilidad_fase.png" +plt.savefig(output_filename, facecolor=fig.get_facecolor(), edgecolor='none', dpi=150) +print(f"[+] Panel geométrico exportado con éxito en alta resolución: '{output_filename}'\n") diff --git a/panel_estabilidad_fase.png b/panel_estabilidad_fase.png new file mode 100644 index 000000000..8b8cd7c79 Binary files /dev/null and b/panel_estabilidad_fase.png differ diff --git a/requirements.txt b/requirements.txt index 14365463b..8b7ad02f1 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,10 +1,22 @@ -ipywidgets==8.1.8 -matplotlib==3.8.4 -pandas==2.2.2 -torch==2.8.0 -torchvision==0.23.0 -tqdm==4.66.4 -pillow>=12.1.1 -fonttools>=4.60.0 -filelock>=3.20.3 -Pygments==2.20.0 +ipywidgets>=8.0.0 +matplotlib>=3.8.0 +pandas>=2.2.0 +tqdm>=4.66.0 +pillow>=10.0.0 +fonttools>=4.40.0 +filelock>=3.12.0 +Pygments>=2.15.0 +seaborn>=0.12.0 +yfinance>=0.2.31 +numpy>=1.24.0 +fastapi>=0.100.0 +uvicorn>=0.22.0 +langgraph>=0.0.1 +langchain>=0.1.0 +langchain-community>=0.0.10 +langchain-google-genai>=1.0.0 +langchain-openai>=0.0.5 +chromadb>=0.4.0 +gradio>=4.0.0 +requests>=2.31.0 +pydantic>=2.0.0 diff --git a/run_engine.sh b/run_engine.sh new file mode 100644 index 000000000..af5984c3e --- /dev/null +++ b/run_engine.sh @@ -0,0 +1,30 @@ +#!/bin/bash + +# ============================================================================== +# SCRIPT DE AUTOMATIZACIÓN: MOTOR CUÁNTICO-RELATIVISTA +# ============================================================================== + +echo "[*] Iniciando despliegue del entorno..." + +# 1. Configuración del entorno virtual +if [ ! -d "venv" ]; then + python3 -m venv venv + echo "[+] Entorno virtual creado." +fi +source venv/bin/activate + +# 2. Verificación de dependencias +pip install --upgrade pip +pip install numpy pandas yfinance matplotlib seaborn + +# 3. Ejecución del motor (puedes extraer el código a main.py si prefieres) +echo "[*] Ejecutando simulación de estabilidad sobre datos BTC-USD..." +python3 -c " +# Aquí iría la lógica del engine extraída del notebook para ejecución headless +# (Opcionalmente, puedes ejecutar el notebook vía nbconvert) +from QuantumRelativisticEngine import QuantumRelativisticEngine +# ... lógica de simulación ... +print('[+] Simulación finalizada.') +" + +echo "[+] Reporte de estabilidad generado en 'panel_estabilidad_fase.png'" diff --git a/setup.sh b/setup.sh new file mode 100644 index 000000000..039608e98 --- /dev/null +++ b/setup.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +# Actualización del SO +echo "Actualizando el sistema operativo..." +sudo apt update && sudo apt upgrade -y + +# Instalación de Python 3.10+ y dependencias +echo "Instalando Python 3.10+ y dependencias..." +sudo apt install -y python3.10 python3-pip + +# Instalación de dependencias de Python +echo "Instalando dependencias de Python..." +pip install yfinance numpy pandas matplotlib google-cloud-storage + +echo "[+] Configuración de infraestructura completada." + + +echo "[+] Configuración de infraestructura completada."