Skip to content

About

PineScript Expert: A Retrieval-Augmented Generation (RAG) agent using Pydantic AI that provides accurate Pine Script v6 guidance. It answers questions, offers code examples, and generates custom indicators/strategies for TradingView. Combines vector search with LLM capabilities for precise Pine Script programming assistance.

Topics

Resources

Contributing

Stars

71 stars

Watchers

3 watching

Forks

Repository files navigation

PineScript Expert

GitHub Stars GitHub Forks Python 3.11+ License: MIT

A Pydantic AI agent that answers questions about Pine Script v6, TradingView's language for indicators and strategies, and writes Pine Script code. It looks up the official documentation, indexed in PostgreSQL with pgvector, through a retrieval tool (RAG).

Streamlit chat: a question about an EMA and Bollinger Bands strategy and the Pine Script v6 answer Streamlit chat with the status sidebar and example queries, answering a question on RSI

Features

  • Answers and Pine Script code grounded in the v6 documentation, found by hybrid search: vector and full-text results merged by rank fusion, then picked by MMR to leave out near-duplicates
  • Three interfaces: a Streamlit web UI that keeps the chat history between sessions, an interactive shell, and single queries from the command line
  • OpenAI by default, or any OpenRouter model, with presets for common choices
  • Answers evaluated on recent Pine Script features, with and without the documents, and with RAGAS (results below)

Evaluation

New Pine Script features

tests/new_features_eval.py asks the model 31 questions, each about one feature of the Pine Script release notes from November 2024 to November 2026, five times with the retrieved documents and five times without.

Right answers Without documents With documents
Round 1 21 of 31 27 of 31
Round 2 16 of 31 29 of 31
Round 3 18 of 31 28 of 31
Round 4 19 of 31 28 of 31
Round 5 19 of 31 27 of 31
Right in most rounds 19 of 31 28 of 31
Released in 2024, all rounds 34 of 35 35 of 35
Released in 2025, all rounds 39 of 45 43 of 45
Released in 2026, all rounds 20 of 75 61 of 75

The columns are close on the features of 2024 and 2025 and differ on those of 2026. The questions come from release notes that the index holds, so the table is about new features, not about Pine Script code in general.

Measured on 2 December 2026 with python tests/new_features_eval.py --rounds 5, on an index built with step 5 of the Quick Start, with the default settings and gpt-6-luna as answer model. An answer is right when its script contains the feature, found with a regular expression; no script is compiled.

RAGAS

RAGAS scores the answers to the 40 questions of tests/ragas_testset.json, ten for each category: function lookup, conceptual, code generation and complex multi-concept.

Retrieval Faithfulness Context Relevance Command
Vector search, 8 chunks 0.3979 0.8125 python tests/ragas_eval.py --retrieval baseline
Hybrid search, 15 chunks, as in the agent 0.4211 0.8562 python tests/ragas_eval.py --retrieval tier1

Measured on the same day and index, one run per row, with gpt-6-luna as answer model and as judge.

  • Context Relevance says whether the retrieved chunks are about the question. Hybrid search scores higher in this run.
  • Faithfulness is the share of the statements in an answer that the retrieved chunks support. The judge also counts the choices of a script, such as a length or a plot color, and no document states those: with hybrid search the command prints 0.67 for the conceptual questions and 0.30 for code generation. Faithfulness does not measure whether the code is right, and on it the two rows are too close to rank.

In both tables each answer is one direct call to the model, with the agent's instructions and, in all but the column without documents, the retrieved chunks in the message. tests/README.md has the steps to rerun them.

Prerequisites

  • Python 3.11+
  • PostgreSQL with pgvector extension
  • OpenAI API key (required for embeddings and default LLM)
  • OpenRouter API key (optional, for alternative LLM providers)
  • Docker (optional, for running PostgreSQL with pgvector)

Quick Start

  1. Clone the repository

    git clone https://github.com/FaustoS88/Pydantic-AI-Pinescript-Expert.git
    cd Pydantic-AI-Pinescript-Expert
  2. Start PostgreSQL with pgvector

    docker run --name pinescript-pgvector \
      -e POSTGRES_PASSWORD=postgres \
      -p 54322:5432 \
      -v pinescript_pgdata:/var/lib/postgresql/data \
      -d pgvector/pgvector:pg16
  3. Install the dependencies and create your .env

    python -m venv venv
    source venv/bin/activate  # on Windows: venv\Scripts\activate
    pip install .
    cp -n .env.example .env   # then add your API keys

    pip install . installs the dependencies only; the scripts run from this folder.

  4. Initialize the database

    python db.py init
  5. Build the index of the Pine Script documentation

    python crawler.py

    The crawler fetches the pages over plain HTTP. With --browser it renders them in a headless browser through Crawl4AI instead: install it with pip install ".[browser]", then download its browser once with crawl4ai-setup.

  6. Ask questions in the web UI or in the terminal

    streamlit run streamlit_ui.py   # web UI
    python run.py interactive       # terminal

Usage

Web Interface

The chat history is saved to chat_history.pkl and reloaded at the next start. The sidebar has a button that clears it.

Interactive Shell

Each answer sees the earlier turns. Type clear to forget the conversation and exit to quit.

Single Query Mode

python run.py query "How do I calculate RSI in Pine Script?"

Database Inspection

# Validate the schema and count the stored chunks
python run.py check

# List the first 20 chunks, with their ids
python db.py list

# Print one chunk by its id
python db.py view 508

# Print the 5 chunks closest to a query by vector
python db.py search "how to use request.security for different timeframes"

Retrieval Pipeline

  • Search: full-text and vector search with a similarity threshold, merged by rank fusion, then MMR to drop near-duplicates
  • Chunks: recursive chunking with overlap, fenced code blocks never split, a header with the context of each chunk, content type and metadata columns
  • Contextual Retrieval (optional, --contextual): an LLM writes a prefix for each chunk at crawl time

docs/retrieval.md follows the pipeline step by step, and docs/evaluations.md has the measurements behind the chunk size and the number of chunks.

Rebuilding the Index

Both commands fetch over plain HTTP; add --browser to render the pages through Crawl4AI.

# Standard crawl (no LLM prefix, about 3 minutes)
python crawler.py --clear

# Contextual re-crawl (one LLM call per chunk, up to 5 in parallel)
python crawler.py --contextual --clear

Key Components

  • agent.py: the Pydantic AI agent, its retrieve tool and the model selection
  • rag_utils.py: chunking and hybrid search
  • crawler.py: fetches the documentation, splits it into chunks and stores them with their embeddings
  • db.py: the database schema and connection, plus the commands to set up, inspect and clear it (python db.py -h)
  • config.py: the settings, read from the environment and .env, and the model presets
  • run.py: the query, interactive and check commands
  • streamlit_ui.py: the web UI
  • tests/: the offline tests and the two evaluations, described in tests/README.md

Advanced Configuration

Model Presets

Switch between LLM providers using the --model flag. Presets are defined in config.py:

Preset Model
default openai/gpt-6-luna
sol openai/gpt-6.2-sol
opus anthropic/claude-opus-5.5
flash google/gemini-3.8-flash

Since December 2026 the answers default to gpt-6-luna, with and without OpenRouter. OpenAI shuts down the snapshots of the earlier defaults, gpt-4.1-mini-2025-04-14 and gpt-4o-mini-2024-07-18, on 14 January 2027.

Models that reason run with effort low, and each model request has up to 4,000 output tokens, reasoning included. PINESCRIPT_THINKING_EFFORT and PINESCRIPT_MAX_TOKENS change them.

# Use a preset
python run.py query "How to use request.security?" --model sol
python run.py interactive --model opus

# Or pass any OpenRouter model ID directly
python run.py query "Explain ta.sma()" --model "anthropic/claude-sonnet-5.5"

All presets route through OpenRouter — add your API key to .env as OPENROUTER_API_KEY. Without this key, the agent answers with the default OpenAI model.

Settings

Every variable, with its default and what it does, is in .env.example. Only OPENAI_API_KEY is required.

Troubleshooting

  • Database status: python run.py check validates the schema and counts the stored chunks.
  • Docker: make sure Docker is running and port 54322 is free, or map another port and set it in DATABASE_URL.
  • Database connection: check DATABASE_URL in .env.
  • pgvector: python db.py init creates the vector extension and lists the installed ones. It needs a server that has pgvector, such as the image of the Quick Start.
  • Embeddings: make sure your OpenAI API key is valid and has quota left.

Star History

Star History Chart

Contributors

Contributors

Contributing

Issues and pull requests are welcome. CONTRIBUTING.md has the setup, the checks and what a pull request should say.

Related Projects

  • tickerflow — One async Python call for crypto, stocks, and forex OHLCV data with automatic provider fallback, pandas DataFrame support, and Pydantic AI agent integration.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

About

PineScript Expert: A Retrieval-Augmented Generation (RAG) agent using Pydantic AI that provides accurate Pine Script v6 guidance. It answers questions, offers code examples, and generates custom indicators/strategies for TradingView. Combines vector search with LLM capabilities for precise Pine Script programming assistance.

Topics

Resources

Contributing

Stars

71 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages