Add logic for inserting data into the backtest results table and example usage
This commit is contained in:
parent
4228d95711
commit
dd771a07c1
1
database/backtest/__init__.py
Normal file
1
database/backtest/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
from .insert import insert
|
17
database/backtest/insert.py
Normal file
17
database/backtest/insert.py
Normal file
@ -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')
|
38
insert_backtest_results_example.py
Normal file
38
insert_backtest_results_example.py
Normal file
@ -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))
|
Loading…
Reference in New Issue
Block a user