🚀 AI One-Click Generation of quantconnect Strategy Code

How to Perform Final Analysis or Save Data When Your Algorithm Finishes

quantconnect | Published on: 2025/11/27
The following content is generated by EasyQuant .

Problem Description

How can I run a function to save my portfolio's final value to a file after a backtest is complete?

Solution

To save your portfolio's final value to a file after a backtest is complete, you should use the on_end_of_algorithm event handler. This method is automatically called by the LEAN engine when the backtest finishes processing all data.

For file storage in the QuantConnect Cloud environment, the best practice is to use the ObjectStore. This allows you to save data persistently that can be retrieved later from the "Object Store" tab in the project panel.

Implementation

Here is a complete example demonstrating how to implement this.

# region imports
from AlgorithmImports import *
# endregion

class SaveFinalValueAlgorithm(QCAlgorithm):

    def initialize(self):
        self.set_start_date(2023, 1, 1)
        self.set_end_date(2023, 12, 31)
        self.set_cash(100000)
        
        self.spy = self.add_equity("SPY", Resolution.DAILY).symbol

    def on_data(self, data: Slice):
        # Simple logic to ensure we have exposure
        if not self.portfolio.invested:
            self.set_holdings(self.spy, 1.0)

    def on_end_of_algorithm(self):
        """
        This method is called when the backtest is terminated.
        We will use it to capture the final portfolio value and save it.
        """
        # 1. Retrieve the final total portfolio value
        final_value = self.portfolio.total_portfolio_value
        
        # 2. Create the content string to save
        # You can format this as CSV, JSON, or plain text
        content = f"Date: {self.time}\nFinal Value: ${final_value:.2f}"
        
        # 3. Define a filename (Key)
        file_key = "final_portfolio_value.txt"
        
        # 4. Save to ObjectStore
        # This saves the file to the 'Object Store' tab in your project
        self.object_store.save(file_key, content)
        
        # 5. Log to console for immediate verification
        self.log(f"Backtest Complete. Saved value to {file_key}: {final_value}")

Key Concepts

  1. on_end_of_algorithm: This is the specific event handler designed for final analysis, resource cleanup, or state saving. It runs exactly once at the very end of the execution flow.
  2. self.object_store.save(key, value):
    • Key: The filename (e.g., "results.txt").
    • Value: The string or byte data you wish to write.
    • In the QuantConnect Web IDE, files saved here appear in the Object Store section of the Organization panel.
  3. self.portfolio.total_portfolio_value: This property gives the total equity (Cash + Unrealized Profit + Reserved Cash) at the specific moment the method is called.

Q&A

Q: Can I use standard Python open() to save files instead of ObjectStore?
A: In a local LEAN environment, yes, you can use standard Python file I/O (e.g., with open('file.txt', 'w') as f:). However, in the QuantConnect Cloud, the file system is ephemeral. While you can write files temporarily, they may not be accessible after the container shuts down. ObjectStore is the required method for persistent storage in the Cloud.

Q: Does on_end_of_algorithm run if the algorithm crashes with an error?
A: No. If the algorithm encounters a runtime error that stops execution, on_end_of_algorithm will not be called. It is only called upon successful completion of the backtest period or a clean stop command.

Q: How do I save the data in JSON format instead of text?
A: You can import the json library. Create a dictionary with your data, convert it using json.dumps(), and pass that string to self.object_store.save().

Q: Is the on_end_of_algorithm method available in live trading?
A: Yes. In live trading, this method is called when you manually stop the algorithm or if the brokerage disconnects and the algorithm shuts down gracefully. It is useful for saving the final state to reload it later.