Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions .github/workflows/python-app.yml
Original file line number Diff line number Diff line change
@@ -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
6 changes: 6 additions & 0 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"recommendations": [
"ms-python.python",
"tomoki1207.pdf"
]
}
3 changes: 3 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"pdf-preview.default.sidebar": true
}
19 changes: 19 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -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"]
391 changes: 391 additions & 0 deletions Master_Prompt_Deployment.md

Large diffs are not rendered by default.

Binary file added Script_Matematico_Completo (3).PDF
Binary file not shown.
102 changes: 102 additions & 0 deletions agent.py
Original file line number Diff line number Diff line change
@@ -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)
164 changes: 164 additions & 0 deletions api.py
Original file line number Diff line number Diff line change
@@ -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)
Loading