From dd771a07c189ef41b6a37b83a077cc023578af40 Mon Sep 17 00:00:00 2001 From: moshferatu Date: Tue, 9 Jan 2024 11:39:40 -0800 Subject: [PATCH] Add logic for inserting data into the backtest results table and example usage --- database/backtest/__init__.py | 1 + database/backtest/insert.py | 17 +++++++++++++ insert_backtest_results_example.py | 38 ++++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+) create mode 100644 database/backtest/__init__.py create mode 100644 database/backtest/insert.py create mode 100644 insert_backtest_results_example.py diff --git a/database/backtest/__init__.py b/database/backtest/__init__.py new file mode 100644 index 0000000..b6af71d --- /dev/null +++ b/database/backtest/__init__.py @@ -0,0 +1 @@ +from .insert import insert \ No newline at end of file diff --git a/database/backtest/insert.py b/database/backtest/insert.py new file mode 100644 index 0000000..665c3b7 --- /dev/null +++ b/database/backtest/insert.py @@ -0,0 +1,17 @@ +import json +import pandas as pd + +from dotenv import load_dotenv +from os import getenv +from sqlalchemy import create_engine + +load_dotenv() + +def insert(backtest_data: pd.DataFrame): + backtest_data['Spreads'] = backtest_data['Spreads'].apply(lambda x: json.dumps(x) if isinstance(x, list) else x) + database_url = ( + f"postgresql+psycopg2://{getenv('DATABASE_USER')}:{getenv('DATABASE_PASSWORD')}" + f"@{getenv('DATABASE_HOST')}:{getenv('DATABASE_PORT')}/{getenv('DATABASE_NAME')}" + ) + engine = create_engine(database_url) + backtest_data.to_sql('Backtest', engine, if_exists='append', index=False, method='multi') \ No newline at end of file diff --git a/insert_backtest_results_example.py b/insert_backtest_results_example.py new file mode 100644 index 0000000..3385969 --- /dev/null +++ b/insert_backtest_results_example.py @@ -0,0 +1,38 @@ +import pandas as pd + +from database.backtest import insert + +backtest_data = { + 'Date': ['2024-01-08'], + 'Symbol': ['SPX'], + 'Strategy': ['Iron Condor @ Market Open'], + 'Entry Time': [pd.Timestamp('2024-01-08 09:30:00')], + 'Exit Time': [pd.Timestamp('2024-01-08 16:00:00')], + 'Spreads': [ + [ + { + 'Legs': [ + {'Action': 'BUY', 'Strike': 150, 'Type': 'CALL'}, + {'Action': 'SELL', 'Strike': 155, 'Type': 'CALL'} + ], + 'Open': 1.5, + 'High': 2.0, + 'Low': 1.0, + 'Close': 1.8 + }, + { + 'Legs': [ + {'Action': 'SELL', 'Strike': 160, 'Type': 'PUT'}, + {'Action': 'BUY', 'Strike': 155, 'Type': 'PUT'} + ], + 'Open': 2.5, + 'High': 3.0, + 'Low': 2.0, + 'Close': 2.8 + } + ] + ], + 'Profit': [100.00] +} + +insert(pd.DataFrame(backtest_data)) \ No newline at end of file