myquant-strategy

repository·master·Indexed 21 days ago

https://github.com/myquant/strategy

A collection of open-source quantitative trading strategies for the Juejin (掘金) platform, implemented in Python and C#. The repository includes alpha strategies focusing on the CSI 300 index, PE-based stock selection, and momentum strategies. It features a Python Strategy Framework that simplifies development using a Mixin-based architecture, automated data management, and configuration via .ini files, allowing users to implement core logic within a single algo function.

Tokens
1.7K
Snippets
4
Records
9
Agent score
76%

What's inside myquant-strategy

  1. Overview of the Python Strategy Framework

    master

    The Python Strategy Framework is designed to simplify quantitative strategy development. It aims to reduce the complexity of writing a strategy to just implementing a single algo function and providing a configuration .ini file.

    Key features include:

    • Mixin-based Architecture: Functional modules are organized using the Mixin pattern.
    • Automated Data Management: Handles both historical and real-time data updates automatically.
    • Data Access: Provides convenient storage and retrieval for K-line (Bar) data and market depth (L2/Tick) data.
    • Simplified Order Execution: Simplifies order pricing by automatically using the counterparty price (opposite side of the book) based on market depth.
    • Position Management: Includes a Mixin for basic take-profit and stop-loss logic, which can be controlled via configuration parameters.
    • Data Conversion: Provides interfaces to convert data into pandas.DataFrame structures via to_dataframe (for Bar data) and ticks_to_dataframe (for latest market depth data).
    • Simplified Interfaces: Offers helper and physics-based methods for external simplified access.
  2. Overview of Alpha Strategy Implementation

    master

    This repository contains a collection of quantitative alpha strategies, specifically focusing on the CSI 300 index (000300).

    Core Concepts

    • Symbol Selection: Strategies typically target specific symbols within the CSI 300 index.
    • Data Initialization: Use md_init to initialize data for a specific bar/timeframe.
    • Strategy Execution:
      • Strategies are implemented as classes.
      • The on_bar method is used to execute logic when a new bar is received.
      • The on_order_filled method is used to handle logic specifically when an order has been filled.

    Implementation Lifecycle

    1. Initialization: Set up parameters and data via md_init.
    2. Bar Processing: Implement signal generation and order management within on_bar.
    3. Order Management: Handle execution feedback via on_order_filled to update state or trigger subsequent actions.
  3. Understand the strategy repository structure

    master

    The repository is organized by strategy name. Each strategy contains a directory named after the strategy, which includes an info.md file for a brief description and subdirectories for specific language implementations (e.g., python/ or csharp/).

    Directory Layout:

    strategy_name/
    ├── info.md             # Strategy description
    ├── python/
    │   ├── strategy.py     # Python implementation
    │   └── strategy.ini    # Configuration file
    └── csharp/
        ├── strategy.cs     # C# implementation
        └── strategy.ini    # Configuration file
  4. Implement a PE-based stock selection strategy

    master

    This strategy follows a specific logic: always buy the 5 stocks with the smallest market capitalization among the 1000 stocks with the lowest PE (Price-to-Earnings) ratio.

    Strategy Workflow

    1. Market Data Subscription: Subscribe to a specific symbol's minute-level market data (e.g., 000016) to act as a trigger for the strategy execution.
    2. Stock Selection: Perform stock selection within the md_init method upon the arrival of the first bar.
    3. Portfolio Management:
      • Compare the selected stock pool with current holdings.
      • If no holdings exist: Buy the selected stocks using equal weighting.
      • If holdings exist: Sell any stocks that are no longer present in the newly selected stock pool.
    4. Execution Synchronization: Use the on_order_filled callback to monitor sell orders. Ensure all sell orders are fully executed before initiating new buy orders to avoid liquidity or position conflicts.
  5. Prepare environment for Python strategies

    master

    Some complex Python strategies require external libraries for time-series data processing and time handling. Before running these strategies, ensure you have installed the following packages via pip:

    • pandas (for time-series data processing)
    • arrow (for time handling)
    pip install pandas arrow
  6. Implement a strategy using the algo function and ini configuration

    master

    To create a new strategy, you only need to implement two components:

    1. An algo function containing your core logic.
    2. A .ini configuration file to define strategy parameters.

    For a concrete implementation reference, consult the demo.py and demo.ini files provided in the repository. Note that the framework is compatible with Python 3.

    # Reference implementation pattern
    # Implement your logic in the algo function
    def algo():
        # Your strategy logic here
        pass
    
    # Configure parameters in a .ini file
    # [StrategyConfig]
    # parameter1 = value
  7. Configure strategies using .ini files

    master

    Every strategy implementation includes a .ini configuration file. To run a strategy successfully, you must update this file with your specific credentials and identifiers:

    1. Credentials: Enter your registered username and password for the Juejin (掘金) platform.
    2. Strategy ID: You must provide the Strategy ID generated by the strategy terminal. To get this:
      • Go to the strategy wizard in the terminal.
      • Select "Create Empty Strategy" (新建空策略).
      • Copy the generated Strategy ID and paste it into the .ini file.

    Important Note on File Editing: When editing .ini files, avoid using standard Windows Notepad, as it may introduce newline issues that cause Python runtime errors. It is recommended to use Notepad++ or a similar editor to ensure file integrity.

    # Example .ini structure (conceptual)
    username = YOUR_USERNAME
    password = YOUR_PASSWORD
    strategy_id = YOUR_GENERATED_ID
  8. Run the Momentum Stock Selection strategy

    master

    The momentum strategy (growth.py or growth.exe) identifies stocks based on their price growth over a specific period. To run the strategy, you must provide three positional arguments via the command line:

    1. Start Date: The beginning of the observation period (format: YYYY-MM-DD).
    2. End Date: The end of the observation period (format: YYYY-MM-DD).
    3. Growth Threshold: A numerical value representing the percentage growth required (e.g., 25 for a 25% increase).
    # Using Python
    python growth.py 2017-03-01 2017-03-28 25
    
    # Using Executable
    growth.exe 2017-03-01 2017-03-28 25
  9. Handle futures trading codes and stock pools

    master

    When using the provided strategies, pay attention to the following data requirements:

    • Stock Pools: You can add or remove stock codes in the stock pool files used by the strategy, but ensure you maintain the original file format.
    • Futures Codes: Trading codes in .ini or code files may expire. You must update futures codes to match current exchange rules to receive market data. For example, an expired code like CFFEX.IF1601 must be updated to a current month's contract (e.g., CFFEX.IF2406).