Skip to content

trading_agent.trading.result_formatter

Turns what tradingmachine returns into compact text for a model.

Tables of candles become CSV, which models read well and which costs few tokens; only the last rows are kept, with a note of how many there were. Dictionaries and lists become JSON. Dates and NumPy values are written as plain text and numbers, and not-a-number values as null.

Typical usage example:

text = ResultFormatter().format(frame, rows=50)

ResultFormatter

Formats tradingmachine values as text.

format

format(value, rows=50)

Formats any value tradingmachine returns.

Parameters:

Name Type Description Default
value Any

A DataFrame, a dictionary, a list or a plain value; None means no data.

required
rows int

For a table, how many of the last rows to keep.

50

Returns:

Type Description
str

The text, at most 15,000 characters.

Source code in src/trading_agent/trading/result_formatter.py
def format(self, value: Any, rows: int = 50) -> str:
    """Formats any value tradingmachine returns.

    Args:
        value (Any): A DataFrame, a dictionary, a list or a plain value; None means no data.
        rows (int): For a table, how many of the last rows to keep.

    Returns:
        str: The text, at most 15,000 characters.
    """
    if value is None:
        return 'No data.'
    if isinstance(value, pandas.DataFrame):
        text = self._table(value, rows)
    else:
        text = json.dumps(self._plain(value), indent=1, ensure_ascii=False)
    if len(text) > _MAXIMUM_CHARACTERS:
        text = (
            text[:_MAXIMUM_CHARACTERS]
            + '\n[cut: the answer was too long; ask for fewer rows]'
        )
    return text