def write(self, aimodel, backtest\_containers: List[BacktestContainer]):
model\_list = []
for container in backtest\_containers:
logger.info(f"Writing backtest result for {container.identifier['interval\_name']}")
fitted\_model, created = FittedModel.objects.update\_or\_create(
ai\_model=aimodel,
name=container.identifier["interval\_name"],
defaults={"fit\_result": {}, "type": FittedModel.Type.BACKTEST})
# storing model can be costly and slow. we may want to schedule this but for now let's just not store it
# fitted\_model.save\_model(container.model)
walkforward, created = WalkForward.objects.get\_or\_create(
train\_start=container.identifier["train\_start"],
train\_end=container.identifier["train\_end"],
test\_start=container.identifier["test\_start"],
test\_end=container.identifier["test\_end"],
)
FittedModelWalkForward.objects.get\_or\_create(
fitted\_model=fitted\_model,
walk\_forward=walkforward
)
# save prediction
model\_list += [
PredictionResult(
walkforward=walkforward,
date=index,
prediction={"y\_pred": row["y\_pred"]},
target={"y\_true": row["y\_true"]},
)
for index, row in container.df.iterrows()
]
bulk\_upsert\_models(models=model\_list, pk\_field\_names=["date", "walkforward\_id"])
Assistant
User
I want all to use bulk_upsert_models
Assistant
If you want to use bulk_upsert_models to perform bulk create and update for all objects, you can modify the write method as follows:
css
User
I want to change this to be able to perform create and update
code
Assistant
To modify the write method to perform create and update instead of only create, you can use the get method instead of create for the WalkForward and FittedModelWalkForward objects, and the update method instead of create for the FittedModel object. Here's an example implementation:
User
I want to change this to be able to perform bulk create and bulk update
code
Assistant
User
raise error when columns doesn't exist in pandas
Assistant
To raise an error when a column does not exist in a Pandas DataFrame, you can use the assert statement to check if the column exists. Here's an example implementation:
python
It seems that the write method is used to create or update FittedModel and related objects for a given aimodel and a list of BacktestContainer objects.
The method first iterates through the list of BacktestContainer objects and performs the following steps for each container:
Updates or creates a FittedModel object with the given ai_model, name, and type.
Gets or creates a WalkForward object with the given train_start, train_end, test_start, and test_end.
Creates a FittedModelWalkForward object to associate the FittedModel and WalkForward objects.
Creates a list of PredictionResult objects based on the df attribute of the BacktestContainer object.
Finally, the method calls a function bulk_upsert_models to bulk upsert the PredictionResult objects using the date and walkforward_id fields as the primary key fields.
If you want to modify the method to perform bulk create and update for FittedModel, WalkForward, and FittedModelWalkForward objects as well, you can use the bulk_create and bulk_update methods provided by Django ORM. Here's an example implementation:
This implementation creates lists of FittedModel, WalkForward, and FittedModelWalkForward objects during the iteration, and then bulk creates them at the end of the iteration using the bulk_create method. Note that we don't need to use update_or_create since we're only doing bulk create here.
The PredictionResult objects are still bulk upserted using the bulk_upsert_models function, but you can modify it to use Django's bulk_create and bulk_update methods if needed.
In this implementation, we first create the FittedModel, WalkForward, and FittedModelWalkForward objects for each BacktestContainer as before, but instead of adding them to separate lists for bulk creation, we add them to a single list model_list along with the PredictionResult objects.
Finally, we call bulk_upsert_models with model_list and the primary key field name "id" (assuming that all models have an id field as the primary key). This will perform bulk create and update for all objects in the list, including the PredictionResult objects.
Note that bulk_upsert_models needs to be implemented separately or obtained from a third-party library.
def write(self, ai\_model, backtest\_containers: List[BacktestContainer]):
prediction\_results = []
fitted\_models = []
fitted\_model\_walkforwards = []
walkforwards = []
for container in backtest\_containers:
logger.info(f"Writing backtest result for {container.identifier['interval\_name']}")
fitted\_model = FittedModel(
ai\_model=ai\_model,
name=container.identifier["interval\_name"],
fit\_result={},
type=FittedModel.Type.BACKTEST
)
# storing model can be costly and slow. we may want to schedule this but for now let's just not store it
# fitted\_model.save\_model(container.model)
fitted\_models.append(fitted\_model)
walkforward = WalkForward(
train\_start=container.identifier["train\_start"],
train\_end=container.identifier["train\_end"],
test\_start=container.identifier["test\_start"],
test\_end=container.identifier["test\_end"],
)
walkforwards.append(walkforward)
fitted\_model\_walkforward = FittedModelWalkForward(
fitted\_model=fitted\_model,
walk\_forward=walkforward
)
fitted\_model\_walkforwards.append(fitted\_model\_walkforward)
prediction\_results += [
PredictionResult(
walkforward=walkforward,
date=index,
prediction={"y\_pred": row["y\_pred"]},
target={"y\_true": row["y\_true"]},
)
for index, row in container.df.iterrows()
]
css
def write(self, ai_model, backtest_containers: List[BacktestContainer]):
prediction_results = []
fitted_models = []
fitted_model_walkforwards = []
walkforwards = []
for container in backtest_containers:
logger.info(f"Writing backtest result for {container.identifier['interval_name']}")
fitted_model, created = FittedModel.objects.update_or_create(
ai_model=ai_model,
name=container.identifier["interval_name"],
defaults={"fit_result": {}, "type": FittedModel.Type.BACKTEST}
)
fitted_models.append(fitted_model)
walkforward, created = WalkForward.objects.get_or_create(
train_start=container.identifier["train_start"],
train_end=container.identifier["train_end"],
test_start=container.identifier["test_start"],
test_end=container.identifier["test_end"],
)
walkforwards.append(walkforward)
fitted_model_walkforward, created = FittedModelWalkForward.objects.get_or_create(
fitted_model=fitted_model,
walk_forward=walkforward
)
fitted_model_walkforwards.append(fitted_model_walkforward)
prediction_results += [ PredictionResult( walkforward=walkforward, date=index, prediction={"y_pred": row["y_pred"]},
target={"y_true": row["y_true"]},
)
for index, row in container.df.iterrows()
]
PredictionResult.objects.bulk_create(prediction_results)
In this implementation, we use update_or_create for the FittedModel object, which will update the existing object if it exists or create a new one if it doesn't. We use get_or_create for the WalkForward and FittedModelWalkForward objects, which will get the existing objects if they exist or create new ones if they don't.
Finally, we bulk create the PredictionResult objects as before.
def write(self, ai\_model, backtest\_containers: List[BacktestContainer]):
prediction\_results = []
fitted\_models = []
fitted\_model\_walkforwards = []
walkforwards = []
for container in backtest\_containers:
logger.info(f"Writing backtest result for {container.identifier['interval\_name']}")
fitted\_model = FittedModel(
ai\_model=ai\_model,
name=container.identifier["interval\_name"],
fit\_result={},
type=FittedModel.Type.BACKTEST
)
# storing model can be costly and slow. we may want to schedule this but for now let's just not store it
# fitted\_model.save\_model(container.model)
fitted\_models.append(fitted\_model)
walkforward = WalkForward(
train\_start=container.identifier["train\_start"],
train\_end=container.identifier["train\_end"],
test\_start=container.identifier["test\_start"],
test\_end=container.identifier["test\_end"],
)
walkforwards.append(walkforward)
fitted\_model\_walkforward = FittedModelWalkForward(
fitted\_model=fitted\_model,
walk\_forward=walkforward
)
fitted\_model\_walkforwards.append(fitted\_model\_walkforward)
prediction\_results += [
PredictionResult(
walkforward=walkforward,
date=index,
prediction={"y\_pred": row["y\_pred"]},
target={"y\_true": row["y\_true"]},
)
for index, row in container.df.iterrows()
]
To modify the write method to perform bulk create and bulk update for all objects, you can use the bulk_create and bulk_update methods provided by Django ORM. Here's an example implementation:
python
def write(self, ai_model, backtest_containers: List[BacktestContainer]):
fitted_models = []
fitted_model_walkforwards = []
walkforwards = []
for container in backtest_containers:
logger.info(f"Writing backtest result for {container.identifier['interval_name']}")
fitted_model = FittedModel(
ai_model=ai_model,
name=container.identifier["interval_name"],
fit_result={},
type=FittedModel.Type.BACKTEST
)
# storing model can be costly and slow. we may want to schedule this but for now let's just not store it
# fitted_model.save_model(container.model)
fitted_models.append(fitted_model)
walkforward = WalkForward(
train_start=container.identifier["train_start"],
train_end=container.identifier["train_end"],
test_start=container.identifier["test_start"],
test_end=container.identifier["test_end"],
)
walkforwards.append(walkforward)
fitted_model_walkforward = FittedModelWalkForward(
fitted_model=fitted_model,
walk_forward=walkforward
)
fitted_model_walkforwards.append(fitted_model_walkforward)
FittedModel.objects.bulk_update(
fitted_models,
fields=["ai_model", "name", "fit_result", "type"],
)
WalkForward.objects.bulk_create(walkforwards)
FittedModelWalkForward.objects.bulk_create(fitted_model_walkforwards)
prediction_results = [
PredictionResult(
walkforward=container_walkforward[0],
date=index,
prediction={"y_pred": row["y_pred"]},
target={"y_true": row["y_true"]},
)
for container, container_walkforward in zip(backtest_containers, fitted_model_walkforwards)
for index, row in container.df.iterrows()
]
PredictionResult.objects.bulk_create(prediction_results)
In this implementation, we first create the FittedModel, WalkForward, and FittedModelWalkForward objects for each BacktestContainer as before, but instead of adding them to separate lists for bulk creation or update, we add them to the appropriate list.
We use the bulk_update method to perform bulk update for the FittedModel objects, passing in the list of objects and the fields to update. We use bulk_create for the WalkForward and FittedModelWalkForward objects, passing in the list of objects.
Finally, we create the PredictionResult objects based on the df attribute of each BacktestContainer, and the associated WalkForward object for that container from the fitted_model_walkforwards list. We then use bulk_create to create all PredictionResult objects in bulk.
for container in backtest_containers:
logger.info(f"Writing backtest result for {container.identifier['interval_name']}")
assert "y_pred" in container.df.columns, f"y_pred column not found in {container.identifier['interval_name']}"
assert "y_true" in container.df.columns, f"y_true column not found in {container.identifier['interval_name']}"
fitted_model = FittedModel(
ai_model=ai_model,
name=container.identifier["interval_name"],
fit_result={},
type=FittedModel.Type.BACKTEST
)
# storing model can be costly and slow. we may want to schedule this but for now let's just not store it
# fitted_model.save_model(container.model)
fitted_models.append(fitted_model)
walkforward = WalkForward(
train_start=container.identifier["train_start"],
train_end=container.identifier["train_end"],
test_start=container.identifier["test_start"],
test_end=container.identifier["test_end"],
)
walkforwards.append(walkforward)
fitted_model_walkforward = FittedModelWalkForward(
fitted_model=fitted_model,
walk_forward=walkforward
)
fitted_model_walkforwards.append(fitted_model_walkforward)
prediction_results += [
PredictionResult(
walkforward=walkforward,
date=index,
prediction={"y_pred": row["y_pred"]},
target={"y_true": row["y_true"]},
)
for index, row in container.df.iterrows()
]
In this implementation, we use the assert statement to check if the "y_pred" and "y_true" columns exist in the df attribute of each BacktestContainer. If either column does not exist, an error message is raised with the name of the container and the missing column name.
If the assertion passes, we proceed with creating the FittedModel, WalkForward, and FittedModelWalkForward objects, and adding them to the appropriate list. We also create the PredictionResult objects based on the df attribute of each BacktestContainer, and add them to the prediction_results list as before.