Skip to content

Add Parameter Suggestion Endpoint with LibertAI Integration #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Dec 27, 2024
Merged
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
2 changes: 1 addition & 1 deletion conf/conf_client.yml
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ gateway:
gateway_api_host: localhost
gateway_api_port: '15888'

certs_path: ./certs
certs_path: certs

# Whether to enable aggregated order and trade data collection
anonymized_metrics_mode:
Expand Down
41 changes: 22 additions & 19 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,23 +1,26 @@
[build-system]
requires = ["setuptools>=42", "wheel"]
build-backend = "setuptools.build_meta"
requires = ["hatchling"]
build-backend = "hatchling.build"

[tool.black]
line-length = 130
target-version = ["py38"]

[tool.isort]
line_length = 130
profile = "black"
multi_line_output = 3
include_trailing_comma = true
use_parentheses = true
ensure_newline_before_comments = true
combine_as_imports = true
[project]
name = "robotter-backend-api"
version = "0.1.0"
authors = [
{ name="Mike Henry" },
]
description = "Robotter Backend API"
readme = "README.md"
requires-python = ">=3.10"

[tool.pre-commit]
repos = [
{ repo = "https://github.com/pre-commit/pre-commit-hooks", rev = "v3.4.0", hooks = [{ id = "check-yaml" }, { id = "end-of-file-fixer" }] },
{ repo = "https://github.com/psf/black", rev = "21.6b0", hooks = [{ id = "black" }] },
{ repo = "https://github.com/pre-commit/mirrors-isort", rev = "v5.9.3", hooks = [{ id = "isort" }] }
[tool.pytest.ini_options]
pythonpath = [
"."
]
asyncio_mode = "strict"
testpaths = [
"tests",
]
filterwarnings = [
"ignore::DeprecationWarning",
"ignore::UserWarning",
]
3 changes: 3 additions & 0 deletions routers/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
"""
Router package initialization.
"""
104 changes: 76 additions & 28 deletions routers/backtest.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

from config import CONTROLLERS_MODULE, CONTROLLERS_PATH
from routers.backtest_models import BacktestResponse, BacktestResults, BacktestingConfig, ExecutorInfo, ProcessedData
from routers.strategies_models import StrategyError

router = APIRouter(tags=["Market Backtesting"])
candles_factory = CandlesFactory()
Expand All @@ -19,37 +20,84 @@
"market_making": market_making_backtesting
}

class BacktestError(StrategyError):
"""Base class for backtesting-related errors"""

class BacktestConfigError(BacktestError):
"""Raised when there's an error in the backtesting configuration"""

class BacktestEngineError(BacktestError):
"""Raised when there's an error during backtesting execution"""

@router.post("/backtest", response_model=BacktestResponse)
async def run_backtesting(backtesting_config: BacktestingConfig) -> BacktestResponse:
try:
if isinstance(backtesting_config.config, str):
controller_config = BacktestingEngineBase.get_controller_config_instance_from_yml(
config_path=backtesting_config.config,
controllers_conf_dir_path=CONTROLLERS_PATH,
controllers_module=CONTROLLERS_MODULE
)
else:
controller_config = BacktestingEngineBase.get_controller_config_instance_from_dict(
config_data=backtesting_config.config,
controllers_module=CONTROLLERS_MODULE
)
# Load and validate controller config
try:
if isinstance(backtesting_config.config, str):
controller_config = BacktestingEngineBase.get_controller_config_instance_from_yml(
config_path=backtesting_config.config,
controllers_conf_dir_path=CONTROLLERS_PATH,
controllers_module=CONTROLLERS_MODULE
)
else:
controller_config = BacktestingEngineBase.get_controller_config_instance_from_dict(
config_data=backtesting_config.config,
controllers_module=CONTROLLERS_MODULE
)
except Exception as e:
raise BacktestConfigError(f"Invalid controller configuration: {str(e)}")

# Get and validate backtesting engine
backtesting_engine = BACKTESTING_ENGINES.get(controller_config.controller_type)
if not backtesting_engine:
raise ValueError(f"Backtesting engine for controller type {controller_config.controller_type} not found.")
backtesting_results = await backtesting_engine.run_backtesting(
controller_config=controller_config, trade_cost=backtesting_config.trade_cost,
start=int(backtesting_config.start_time), end=int(backtesting_config.end_time),
backtesting_resolution=backtesting_config.backtesting_resolution)

processed_data = backtesting_results["processed_data"]["features"].fillna(0).to_dict()
executors_info = [ExecutorInfo(**e.to_dict()) for e in backtesting_results["executors"]]
results = backtesting_results["results"]
results["sharpe_ratio"] = results["sharpe_ratio"] if results["sharpe_ratio"] is not None else 0

return BacktestResponse(
executors=executors_info,
processed_data=ProcessedData(features=processed_data),
results=BacktestResults(**results)
)
raise BacktestConfigError(
f"Backtesting engine for controller type {controller_config.controller_type} not found. "
f"Available types: {list(BACKTESTING_ENGINES.keys())}"
)

# Validate time range
if backtesting_config.end_time <= backtesting_config.start_time:
raise BacktestConfigError(
f"Invalid time range: end_time ({backtesting_config.end_time}) must be greater than "
f"start_time ({backtesting_config.start_time})"
)

try:
# Run backtesting
backtesting_results = await backtesting_engine.run_backtesting(
controller_config=controller_config,
trade_cost=backtesting_config.trade_cost,
start=int(backtesting_config.start_time),
end=int(backtesting_config.end_time),
backtesting_resolution=backtesting_config.backtesting_resolution
)
except Exception as e:
raise BacktestEngineError(f"Error during backtesting execution: {str(e)}")

try:
# Process results
processed_data = backtesting_results["processed_data"]["features"].fillna(0).to_dict()
executors_info = [ExecutorInfo(**e.to_dict()) for e in backtesting_results["executors"]]
results = backtesting_results["results"]
results["sharpe_ratio"] = results["sharpe_ratio"] if results["sharpe_ratio"] is not None else 0

return BacktestResponse(
executors=executors_info,
processed_data=ProcessedData(features=processed_data),
results=BacktestResults(**results)
)
except Exception as e:
raise BacktestError(f"Error processing backtesting results: {str(e)}")

except BacktestConfigError as e:
raise HTTPException(status_code=400, detail=str(e))
except BacktestEngineError as e:
raise HTTPException(status_code=500, detail=str(e))
except BacktestError as e:
raise HTTPException(status_code=500, detail=str(e))
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))
raise HTTPException(
status_code=500,
detail=f"Unexpected error during backtesting: {str(e)}"
)
Loading
Loading