# AI research assistant (/features/ai/ai-research-assistant)

Can an assistant that knows VBT help you write and fix research code? ChatVBT is an AI assistant for
quant research in Python that brings VBT's documentation, code examples, and community discussions
into the conversation. Ask how a feature works, get help adapting a backtest, or work through an
error without leaving your notebook or terminal.

```python title="Ask the Portfolio class how to add a trailing stop"
>>> vbt.PF.chat("How do I add a 10% trailing stop to a signal backtest?")  # (1)
```

1.  Needs an API key for a model provider, such as `OPENAI_API_KEY`. With an OpenAI key, the default
    model is `gpt-5.4`.

````markdown title="Answer"
You want to add a 10% trailing stop to a signal-based portfolio backtest.

Use the `tsl_stop` argument in `vbt.PF.from_signals` and set it to `0.1`.

```python
import vectorbtpro as vbt

data = vbt.YFData.pull("BTC-USD")
fast_ma = data.run("vbt:ma", window=20, hide_params=True)
slow_ma = data.run("vbt:ma", window=50, hide_params=True)

entries = fast_ma.ma_crossed_above(slow_ma)
exits = fast_ma.ma_crossed_below(slow_ma)

pf = vbt.PF.from_signals(
    data,
    entries=entries,
    exits=exits,
    tsl_stop=0.1
)

print(pf.sharpe_ratio)
```

If you want to combine it with other stops, you can also pass
`sl_stop` and/or `tp_stop` in the same call.
...
````

The question went to the `Portfolio` class, so the model received code examples that use it as
context. The returned code ran unchanged and printed a Sharpe ratio of 1.28 for the full Bitcoin
history on October 2, 2026. Answers vary between runs and models, so treat them like code from a
colleague: read them, run them, and check the result.

## Help with the next step in your research \[#help-with-the-next-step-in-your-research]

Start with a specific change or question. For example:

*   "How do I add a trailing stop to this signal backtest?"
*   "How can I test several moving-average windows across multiple assets?"
*   "What does this error mean when I pass an array to my signal callback?"
*   "How do I get trade statistics for each portfolio group?"

Include the relevant function, code, or error message so the answer can address your setup. You can
then ask a follow-up using the same `chat_history`, such as adding fees or changing how assets share
cash. Ask for Python code that you can run and inspect in your own research.

## Choose how to work with it \[#choose-how-to-work-with-it]

| What you need                                                             | Use                                                                               |
| ------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| An answer that draws on VBT documentation and examples                    | `vbt.chat`, or `vbt.quick_chat` for keyword-based retrieval.                      |
| Help with a particular class or method                                    | Class-level chat, such as `vbt.PF.chat`, with relevant material about that class. |
| An assistant that can look things up or run a calculation while answering | `vbt.interact` with a model that supports tool calls.                             |
| Changes across files in an existing project                               | A coding agent with VBT skills, documentation, and access to your installation.   |

## Grounded chat \[#grounded-chat]

`vbt.chat` searches the whole knowledge base for the question, ranks the most relevant pages,
examples, and discussions, and sends them to the model with the question. `vbt.quick_chat` ranks
with keyword search instead of embeddings, which is faster and works offline apart from the model
itself once the knowledge assets are available locally. Both take a `chat_history` to continue a
conversation, stream the answer, and print it as plain text, render it in a notebook, or open it as
an HTML page in the browser. The same commands run in a terminal as `vbt chat` and `vbt quick-chat`,
as the [ChatVBT](#chatvbt) highlight below shows.

Models come from OpenAI, Anthropic, Google Gemini, Hugging Face Inference, a local Ollama server, or
any provider LiteLLM supports. VBT picks the first one with a key set, and every call can name a
provider, a model, and the provider's own arguments. `vbt.chat` also needs embeddings to rank the
knowledge base, which the [Knowledge search](/features/ai/knowledge-search/) page sets up.

Give the assistant your code, data, or an error message to work through a specific task. Each answer
uses your question, conversation history, and relevant VBT material. Enable tools through
`vbt.interact` to let it inspect your environment and run code. You can also use local Ollama models
and local embeddings after downloading the knowledge assets. Choose the model provider separately
from the search provider, so a local search setup can also be used with a hosted chat model. For
changes across your own files, see [Coding agents](#coding-agents) below.

## Tools and reasoning \[#tools-and-reasoning]

`vbt.interact` lets the model call tools while it answers. It can search the documentation, look up
an object's API, read source code, and run Python code through the same tools as the MCP server, and
you can add your own functions as tools. Supported models can show the reasoning summaries or
thought segments their provider supplies. See the [Function calling](#function-calling) and
[Reasoning steps](#reasoning-steps) highlights below.

## Ask any object \[#ask-any-object]

VBT classes with the knowledge interface can find material about themselves. `find_api`,
`find_docs`, `find_examples`, and `find_messages` return its API pages, documentation, code
examples, and community discussions. `chat` answers with the code examples as context by default,
and `asset_names` adds the other kinds, as the [Self-aware classes](#self-aware-classes) highlight
below shows.

## Coding agents \[#coding-agents]

ChatVBT helps with questions and code snippets. For work across your project, coding agents such as
Claude Code or Codex can work with VBT directly:

*   **Agent skills:** `vbt agents install` adds step-by-step procedures for common tasks, such as
    generating signals, backtesting, and optimizing parameters, matched to your installed version.
*   **Documentation:** members get `llms.txt` indexes, Markdown versions of every page, and
    downloadable knowledge assets that an agent can search.
*   **Tools:** the MCP server, or the same functions called from Python, let an agent search the
    documentation and run code in your installation. See the [MCP server](/features/ai/mcp-server/)
    for the available tools.
*   **Refactoring:** `vbt.refactor_source` improves code with a model and VBT knowledge, as the
    [Source refactorer](#source-refactorer) highlight below shows.

!!! info "Guide"
    The members-only [Using AI](https://members.vectorbt.pro/using-ai/) guide sets up agent skills, documentation
    access, and the MCP server step by step.

## Function calling \[#function-calling]

New in v2025.10.15

✅ VBT now supports function calling with compatible models, allowing you to use the MCP server and
define custom functions that the model can invoke, and all of this without any additional setup!
This feature is particularly useful for complex queries, research tasks, and interactive
applications where you want the model to perform specific tasks or calculations on your behalf.

```python title="Ask VBT a question using ChatGPT and let it use the MCP server"
>>> env["OPENAI_API_KEY"] = "<YOUR_OPENAI_API_KEY>"

>>> vbt.interact(  # (1)
...     "How to backtest a weekly rebalancing strategy with vbt.PF.from_orders?",
...     tool_display_format="compact",  # (2)
...     formatter="html",
... )
```

1.  Use `interact()` instead of `chat()` to enable function calling.
2.  Optional. Use a compact display format for tools. By default, tools are displayed in a collapsed
    format.

![](/assets/images/features/intelligence/function_calling.light.gif#only-light)
![](/assets/images/features/intelligence/function_calling.dark.gif#only-dark)

## Reasoning steps \[#reasoning-steps]

New in v2025.10.15

✅ VBT now displays reasoning summaries and thought segments from supported models, helping you
follow the explanation alongside the answer. This is particularly useful for complex queries that
require multiple steps to answer.

```python title="Ask VBT a question using ChatGPT and see its reasoning steps"
>>> env["GITHUB_TOKEN"] = "<YOUR_GITHUB_TOKEN>"
>>> env["OPENAI_API_KEY"] = "<YOUR_OPENAI_API_KEY>"

>>> vbt.chat(
...     "How to backtest a weekly rebalancing strategy with vbt.PF.from_orders?",
...     reasoning=dict(effort="low", summary="auto"),  # (1)
...     formatter="html"
... )
```

1.  Enable reasoning with low effort and automatic summary for OpenAI models.

![](/assets/images/features/intelligence/reasoning_steps.light.gif#only-light)
![](/assets/images/features/intelligence/reasoning_steps.dark.gif#only-dark)

## ChatVBT \[#chatvbt]

New in v2025.3.1

✅ Similar to SearchVBT, ChatVBT takes search results and forwards them to your chosen model. This
lets you ask questions about the VBT knowledge base and receive answers informed by the retrieved
material.

```python title="Ask VBT a question using ChatGPT"
>>> env["GITHUB_TOKEN"] = "<YOUR_GITHUB_TOKEN>"
>>> env["OPENAI_API_KEY"] = "<YOUR_OPENAI_API_KEY>"

>>> vbt.chat("How to rebalance weekly?", formatter="html")
```

![](/assets/images/features/intelligence/chatvbt.light.gif#only-light)
![](/assets/images/features/intelligence/chatvbt.dark.gif#only-dark)

## Self-aware classes \[#self-aware-classes]

New in v2024.12.15

✅ Each VBT class offers methods to explore its features, including its API, associated
documentation, Discord messages, and code examples. You can even ask it questions directly through a
model!

```python title="Ask portfolio optimizer a question"
>>> env["GITHUB_TOKEN"] = "<YOUR_GITHUB_TOKEN>"
>>> env["OPENAI_API_KEY"] = "<YOUR_API_KEY>"

>>> vbt.PortfolioOptimizer.find_assets().get("link")
['https://members.vectorbt.pro/api/portfolio/pfopt/base/#vectorbtpro.portfolio.pfopt.base',
 'https://members.vectorbt.pro/api/generic/analyzable/#vectorbtpro.generic.analyzable.Analyzable',
 'https://members.vectorbt.pro/api/base/wrapping/#vectorbtpro.base.wrapping.Wrapping',
 ...
 'https://members.vectorbt.pro/features/optimization/portfolio-optimization/#riskfolio-lib',
 'https://members.vectorbt.pro/features/optimization/portfolio-optimization/#portfolio-optimization',
 'https://members.vectorbt.pro/features/optimization/portfolio-optimization/#pyportfolioopt',
 ...
 'https://discord.com/channels/x/918629995415502888/1064943203071045753',
 'https://discord.com/channels/x/918629995415502888/1067718833646874634',
 'https://discord.com/channels/x/918629995415502888/1067718855734075403',
 ...]

>>> vbt.PortfolioOptimizer.chat("How to rebalance weekly?", formatter="html")
```

![](/assets/images/features/intelligence/knowledge_assets.light.gif#only-light)
![](/assets/images/features/intelligence/knowledge_assets.dark.gif#only-dark)

## Source refactorer \[#source-refactorer]

New in v2025.5.11

✅ Use the source refactorer to automatically enhance any Python code, whether it is a full package,
Python object, or raw string. For larger sources, it uses the Python syntax tree to split the code
into chunks, refactors each with a model, and merges the results. You can choose to return the
result, update the source in place, or copy it to your clipboard. For full transparency, you can
also preview the diff directly in your browser ✏️

```python title="Complete a signal function"
>>> env["GITHUB_TOKEN"] = "<YOUR_GITHUB_TOKEN>"
>>> env["OPENAI_API_KEY"] = "<YOUR_OPENAI_API_KEY>"

>>> source = """
... @njit
... def signal_func_nb(ctx, entries, exits):
...     is_entry = vbt.pf_nb.select_nb(ctx, entries)
...     is_exit = vbt.pf_nb.select_nb(ctx, exits)
...
...     # TODO: Enter only if no other asset is active
...
...     return is_entry, is_exit, False, False
... """  # (1)

>>> new_source = vbt.refactor_source(
...     source,
...     attach_knowledge=True,  # (2)
...     model="gpt-5-mini",
...     reasoning=dict(effort="high"),
...     show_diff=True,  # (3)
... )
>>> print(new_source)

@njit
def signal_func_nb(ctx, entries, exits):
    is_entry = vbt.pf_nb.select_nb(ctx, entries)
    is_exit = vbt.pf_nb.select_nb(ctx, exits)
    for col in range(ctx.from_col, ctx.to_col):
        if col != ctx.col and ctx.last_position[col] != 0:
            is_entry = False
            break
    return is_entry, is_exit, False, False
```

1.  Use **TODO** or **FIXME** comments to provide custom instructions.
2.  Attach relevant knowledge from the website and Discord.
3.  Show the produced changes in a browser.

![](/assets/images/features/intelligence/source_refiner.light.png#only-light)
![](/assets/images/features/intelligence/source_refiner.dark.png#only-dark)


## Related pages

*   [Knowledge search](/features/ai/knowledge-search/): Search documentation, API, examples, and community answers with keyword and embedding ranking
*   [AI](/features/ai/): Get help with Python backtests, search VBT knowledge, and connect your coding assistant
*   [MCP server](/features/ai/mcp-server/): Let your coding assistant search VBT documentation, look up the API, and run code over MCP
*   [Workflow automation](/features/tooling/workflow-automation/): Schedule data updates, send Telegram alerts, run tasks in parallel, and track progress