ZVT Quantitative Trading Framework

repository·master·Indexed 26 days ago

https://github.com/zvtvz/zvt

A comprehensive quantitative trading framework for data capture, machine learning-based prediction, and strategy backtesting and execution. ZVT supports multiple markets including China, USA, and HK, providing a Dash & Plotly UI for research and a scalable REST API for real-time trading. It features a unified interface for recording and querying market data across various asset classes (Stocks, Indices, ETFs, Funds) and supports a three-step factor calculation model (data_df, factor_df, result_df) for formal strategy development.

Tokens
19.8K
Snippets
37
Records
136
Agent score
88%

What's inside ZVT

  1. Overview of the Trader facility

    master

    The Trader facility is a tool designed for backtesting and generating trading signals. It supports several built-in strategies and allows for custom implementations. You can use it with:

    • Factor
    • TargetSelector
    • MLMachine
    • Custom freestyle algorithms
  2. Overview of the ZVT Market Model

    master

    ZVT abstracts the market into three core components that form its market model:

    1. TradableEntity: The assets or instruments being traded.
    2. ActorEntity: The market participants (e.g., traders, institutions).
    3. EntityEvent: The events that occur involving both TradableEntities and ActorEntities.
  3. Introduction to zvt

    master
    zvt is a facility designed for building straightforward trading algorithms. It focuses on using basic programming concepts, providing a concise abstraction of the market, and ensuring that correctness is obvious. The project is structured around four core pillars: Data, Factors, Traders, and Machine Learning (ML).
  4. Understand the core data abstractions in zvt

    master

    In zvt, data is modeled through two primary types of entities. Data itself is defined as the events that occur on these entities:

    1. Tradable Entity: Entities that can be traded (e.g., financial instruments).
    2. Actor Entity: Entities that perform actions (e.g., traders, algorithms, or market participants).

    Understanding this distinction is fundamental to how data is structured and queried within the system.

  5. Understand Drawer Intent classifications

    master

    In zvt, data visualization and analysis are driven by 'intent'. The system classifies intents into three primary categories:

    1. compare: Comparing different entities (e.g., comparing the S&P 500 index with the Shanghai index).
    2. distribute: Analyzing the distribution of data.
    3. composite: Analyzing composite structures.

    Different intents use different data structures, such as NormalData, to express their specific analytical goals.

  6. Understand ZVT Core Concepts

    master

    ZVT is built around several key domain concepts for market data and trading:

    • Entity: The fundamental existential concept being described.
    • EntityEvent: An event that occurs on an Entity.
    • TradableEntity: An Entity that can be traded (e.g., Stock, Future).
    • ActorEntity: An Entity acting in the market (e.g., Fund, Individual, Government).
    • IntervalLevel: A fixed time interval (e.g., 5m, 1d).
    • Schema: A data structure with fields. A single Schema can utilize multiple storages via different Providers.
    • Kdata (Quote): Candlestick data containing OHLC (Open, High, Low, Close) values.
    • Provider: The source of the data.
    • Storage: The underlying SQL database (e.g., sqlite, mysql).
    • Recorder: A class used to record data for a specific Schema.
    • Factor: Market data computed from a Schema. Factors can be saved as new Schemas.
    • TargetSelector: A class that selects targets based on a Factor.
    • Trader: The backtesting engine that utilizes a TargetSelector, MLMachine, or a custom freestyle approach.
    • Tagger: A tool to classify TradableEntity across different dimensions, often used as features for ML categories.
    • MLMachine: The machine learning engine.
    • TradingSignal: Contains information regarding how to execute a trade.
    • Drawer: A class used for drawing charts.
    • Intent: Defines the desired operation, such as compare, distribute, or composite.
  7. Understand the zvt data structure

    master

    zvt uses a SQL database (defaulting to SQLite) to store data and provides a uniform API for recording and querying. Data is organized around entities (like TradableEntity or ActorEntity) and the events that happen to them.

    An entity is defined by:

    • entity_type: The type of entity (e.g., stock, future, bond).
    • exchange: The exchange where the entity is traded.
    • code: The entity's symbol/code.

    The unique entity_id is constructed as: {entity_type}_{exchange}_{code}.

    Common data fields include:

    • entity_id: The unique identifier for the entity.
    • timestamp: The time the event occurred.
    • id: The unique record ID, typically formatted as {entity_id}_{timestamp}.
  8. Define a new TradableEntity schema

    master

    To add a new type of entity (e.g., a Country), create a class that inherits from TradableEntity and a SQLAlchemy declarative_base. Use the @register_entity decorator with an entity_type to identify the entity. Finally, call register_schema to link the entity to specific providers and a database name.

    An entity is uniquely identified by its entity_type, exchange, and code (e.g., entity_type='country', exchange='galaxy', code='CN').

    from sqlalchemy import Column, String, Float
    from sqlalchemy.orm import declarative_base
    from zvt.contract.schema import TradableEntity
    from zvt.contract.register import register_schema, register_entity
    
    CountryMetaBase = declarative_base()
    
    @register_entity(entity_type="country")
    class Country(CountryMetaBase, TradableEntity):
        __tablename__ = "country"
        region = Column(String(length=128))
        capital_city = Column(String(length=128))
        income_level = Column(String(length=64))
        lending_type = Column(String(length=64))
        longitude = Column(Float)
        latitude = Column(Float)
    
    register_schema(providers=["wb"], db_name="country_meta", schema_base=CountryMetaBase)
  9. Implement a custom Transformer

    master

    A Transformer is a stateless object used to manipulate NormalData. To implement one, override the transform_one method to process a single entity's DataFrame.

    Note: transform_one is ideal for libraries that calculate single targets. If you need to calculate multiple targets simultaneously for better performance, you can implement the transform method directly.

  10. Add a new TradableEntity

    master

    To add a new TradableEntity to zvt, follow these four steps:

    1. Define the Entity Schema: Create a SQLAlchemy model that inherits from TradableEntity. Use the @register_entity decorator to specify the entity_type. Use register_schema to link the schema to specific providers and a database name.
    2. Implement a Recorder: Create a class inheriting from Recorder. Define the provider and data_schema. In the run() method, fetch data (e.g., via an API) and use df_to_db to persist it.
    3. Define additional schemas: If the entity has specific data attributes (like treasury yields for a country), define those as separate SQLAlchemy models using Mixin and register them with register_schema.
    4. Use the data: Use the generated domain classes to record_data() and query_data().
    # 1. Define entity Schema
    from sqlalchemy import Column, String, Float
    from sqlalchemy.orm import declarative_base
    from zvt.contract.schema import TradableEntity
    from zvt.contract.register import register_schema, register_entity
    
    CountryMetaBase = declarative_base()
    
    @register_entity(entity_type="country")
    class Country(CountryMetaBase, TradableEntity):
        __tablename__ = "country"
        region = Column(String(length=128))
        capital_city = Column(String(length=128))
        income_level = Column(String(length=64))
        lending_type = Column(String(length=64))
        longitude = Column(Float)
        latitude = Column(Float)
    
    register_schema(providers=["wb"], db_name="country_meta", schema_base=CountryMetaBase)
    
    # 2. Implement recorder
    from zvt.contract.api import df_to_db
    from zvt.contract.recorder import Recorder
    from zvt.recorders.wb import wb_api
    
    class WBCountryRecorder(Recorder):
        provider = "wb"
        data_schema = Country
    
        def run(self):
            df = wb_api.get_countries()
            df_to_db(df=df, data_schema=self.data_schema, provider=self.provider, force_update=self.force_update)