### Install MongoDB on macOS Source: https://github.com/yutiansut/quantaxis/blob/master/doc/getting-started/installation.md Install and start the MongoDB service using Homebrew. ```bash # 使用Homebrew安装 brew tap mongodb/brew brew install mongodb-community@6.0 # 启动MongoDB brew services start mongodb-community@6.0 # 验证安装 mongosh --version ``` -------------------------------- ### Install ClickHouse on Linux Source: https://github.com/yutiansut/quantaxis/blob/master/doc/getting-started/installation.md Install and start the ClickHouse server and client for large-scale data analysis. ```bash # Ubuntu/Debian sudo apt-get install -y apt-transport-https ca-certificates dirmngr sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 8919F6BD2B48D754 echo "deb https://packages.clickhouse.com/deb stable main" | sudo tee /etc/apt/sources.list.d/clickhouse.list sudo apt-get update sudo apt-get install -y clickhouse-server clickhouse-client # 启动服务 sudo systemctl start clickhouse-server sudo systemctl enable clickhouse-server ``` -------------------------------- ### Install QUANTAXIS dependencies Source: https://github.com/yutiansut/quantaxis/blob/master/doc/advanced/resource-manager.md Install the necessary drivers for MongoDB, RabbitMQ, ClickHouse, and Redis. ```bash # 基础依赖 (MongoDB) pip install pymongo motor # RabbitMQ pip install pika # ClickHouse pip install clickhouse-driver # Redis pip install redis # 完整安装 pip install quantaxis[full] ``` -------------------------------- ### Install MongoDB on Linux Source: https://github.com/yutiansut/quantaxis/blob/master/doc/getting-started/installation.md Install and start the MongoDB service on Ubuntu or Debian systems. ```bash # 导入MongoDB公钥 wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add - # 添加MongoDB源 echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list # 安装MongoDB sudo apt-get update sudo apt-get install -y mongodb-org # 启动MongoDB sudo systemctl start mongod sudo systemctl enable mongod # 验证安装 mongo --version ``` -------------------------------- ### Perform full installation Source: https://github.com/yutiansut/quantaxis/blob/master/README.md Install all components including Rust core, data swap, and Polars support. ```bash # 安装所有组件 pip install -e .[full] # 包含: # - QARS2 Rust核心 # - QADataSwap跨语言通信 # - Polars高性能DataFrame # - 所有可选依赖 ``` -------------------------------- ### Install QADataSwap via PyPI Source: https://github.com/yutiansut/quantaxis/blob/master/doc/getting-started/installation.md Install the QADataSwap component using pip. ```bash pip install qadataswap ``` -------------------------------- ### Install QARS3 Source: https://github.com/yutiansut/quantaxis/blob/master/UPGRADE_PLAN.md Install the Rust-based core engine for QUANTAXIS. ```bash pip install qars3 # 或从源码编译 ``` -------------------------------- ### Run QUANTAXIS examples and benchmarks Source: https://github.com/yutiansut/quantaxis/blob/master/doc/getting-started/quickstart.md Use these shell commands to explore available examples and execute performance tests. ```bash # 查看所有示例 ls examples/ # 运行QARSBridge示例 python examples/qarsbridge_example.py # 运行QADataBridge示例 python examples/qadatabridge_example.py # 运行性能测试 python scripts/benchmark_databridge.py ``` -------------------------------- ### Run the project Source: https://github.com/yutiansut/quantaxis/blob/master/qapro-rs/readme.md Executes the project or the API example using the provided configuration file. ```bash cargo run --release example.toml ``` ```bash cargo run --example api --release example.toml [开启的服务在example.toml中配置 默认5000端口] ``` -------------------------------- ### Install with Cython Acceleration Source: https://github.com/yutiansut/quantaxis/wiki/ABOUT-QUANTAXIS Optional steps to build with Cython for performance optimization before installing in editable mode. ```bash python setup_cython.py build_ext --inplace 再继续 pip install -e . ``` -------------------------------- ### Install for Local Development Source: https://github.com/yutiansut/quantaxis/wiki/ABOUT-QUANTAXIS Clone the repository and install in editable mode for local development. ```bash git clone https://github.com/quantaxis/quantaxis --depth 1 cd quantaxis pip install -e . ``` -------------------------------- ### Install Docker on Ubuntu Source: https://github.com/yutiansut/quantaxis/blob/master/doc/deployment/docker.md Use the provided script to install Docker on Linux systems. ```bash wget https://raw.githubusercontent.com/QUANTAXIS/QUANTAXIS/master/config/install_docker.sh sudo bash install_docker.sh ``` -------------------------------- ### Setup Pre-commit Hooks Source: https://github.com/yutiansut/quantaxis/blob/master/doc/development/testing.md Configures pre-commit hooks for linting and formatting, along with installation and execution commands. ```bash # .pre-commit-config.yaml repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.4.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer - id: check-yaml - repo: https://github.com/psf/black rev: 23.3.0 hooks: - id: black - repo: https://github.com/PyCQA/pylint rev: v2.17.4 hooks: - id: pylint # 安装 pip install pre-commit pre-commit install # 运行所有文件 pre-commit run --all-files ``` -------------------------------- ### Install and Use Rust Performance Components Source: https://github.com/yutiansut/quantaxis/blob/master/doc/migration/v2.0-to-v2.1.md Install the optional Rust-accelerated components and initialize the high-performance account class. ```bash # 安装Rust组件 (可选) pip install quantaxis[rust] ``` ```python # 使用Rust加速的账户 from QUANTAXIS import QARSAccount account = QARSAccount("account_id", init_cash=100000.0) # 性能提升100x! ``` -------------------------------- ### Install New Version Source: https://github.com/yutiansut/quantaxis/blob/master/doc/getting-started/installation.md Install the latest version including Rust support. ```bash # 安装完整版 pip install quantaxis[rust] ``` -------------------------------- ### Run and Connect to QAEXCHANGE-RS Source: https://github.com/yutiansut/quantaxis/blob/master/UPGRADE_PLAN.md Start the simulated exchange server and connect using Python clients. ```bash cd /home/quantaxis/qaexchange-rs cargo run --release --bin qaexchange-server ``` ```python from QUANTAXIS.QAExchange import QAExchangeClient, QAExchangeWebSocket # HTTP客户端 client = QAExchangeClient("http://localhost:8080") client.login("user1", "password") order = client.send_order("000001", 100, 10.5, "BUY") # WebSocket实时行情 ws = QAExchangeWebSocket("ws://localhost:8080/ws") ws.on_tick = lambda data: print(f"收到tick: {data}") ws.connect(token=client.token) ws.subscribe_market(["000001", "000002"]) ``` -------------------------------- ### Install QUANTAXIS via Git Source: https://github.com/yutiansut/quantaxis/blob/master/README.md Clone the repository and install the package in editable mode. ```bash # 克隆仓库 git clone https://github.com/QUANTAXIS/QUANTAXIS.git cd QUANTAXIS # 安装依赖 pip install -e . ``` -------------------------------- ### Deploy Core Services Source: https://github.com/yutiansut/quantaxis/blob/master/doc/deployment/overview.md Initializes the core QUANTAXIS services by cloning the repository and starting the containers. ```bash # 克隆仓库 git clone https://github.com/QUANTAXIS/QUANTAXIS.git cd QUANTAXIS/docker/qa-service-v2.1 # 复制环境变量配置 cp .env.example .env # 编辑.env修改密码(生产环境必须!) # 启动服务 docker-compose up -d # 查看日志 docker-compose logs -f ``` -------------------------------- ### Initialize QA_SERVICE on Windows/Mac Source: https://github.com/yutiansut/quantaxis/blob/master/docker/readme.md Commands to create Docker volumes and start the service on non-Linux platforms. ```bash docker volume create --name=qamg docker volume create --name=qacode ``` ```bash cd D:/qa (此处就是你心爱的文件夹的目录) docker-compose up ``` ```bash cd D:/qa (此处就是你心爱的文件夹的目录) docker-compose pull (这里的意思是更新docker文件) docker-compose up ``` -------------------------------- ### Install QADataSwap Source: https://github.com/yutiansut/quantaxis/blob/master/doc/advanced/data-bridge.md Install the necessary dependencies to resolve ImportError issues. ```bash # 方式1: 安装QUANTAXIS with Rust pip install quantaxis[rust] # 方式2: 单独安装QADataSwap cd /home/quantaxis/qadataswap pip install -e . ``` -------------------------------- ### Run QA_SERVICE on Mac/Windows Source: https://github.com/yutiansut/quantaxis/blob/master/doc/deployment/docker.md Navigate to the directory containing the docker-compose.yaml file and start the services. ```bash cd D:/qa (此处就是你心爱的文件夹的目录) docker-compose up ``` -------------------------------- ### Deploy Full Services Source: https://github.com/yutiansut/quantaxis/blob/master/doc/deployment/overview.md Starts all available services including ClickHouse and market data collection. ```bash # 启动所有服务(包括ClickHouse和行情采集) docker-compose --profile full up -d ``` -------------------------------- ### Install via Pip Source: https://github.com/yutiansut/quantaxis/wiki/ABOUT-QUANTAXIS Standard command to install or upgrade the QUANTAXIS package. ```bash pip install quantaxis -U ``` -------------------------------- ### Verify installation Source: https://github.com/yutiansut/quantaxis/blob/master/README.md Check the installed version and verify Rust support status. ```python import QUANTAXIS as QA from QUANTAXIS.QARSBridge import has_qars_support print(f"QUANTAXIS版本: {QA.__version__}") print(f"QARS2支持: {has_qars_support()}") # 预期输出: # QUANTAXIS版本: 2.1.0.alpha2 # QARS2支持: True ``` -------------------------------- ### Install QUANTAXIS with various configurations Source: https://github.com/yutiansut/quantaxis/blob/master/README.md Use these pip commands to install the package with different levels of feature support, including Rust components and performance optimizations. ```bash # 基础安装 pip install -e . # 包含Rust组件 (推荐) pip install -e .[rust] # 包含性能优化包 pip install -e .[performance] # 完整安装 pip install -e .[full] ``` -------------------------------- ### Install QUANTAXIS with Rust support Source: https://github.com/yutiansut/quantaxis/blob/master/README.md Install the package with QARS2 Rust components for performance, or install QARS2 manually. ```bash # 安装QUANTAXIS + QARS2 pip install -e .[rust] # 或手动安装QARS2 cd /home/quantaxis/qars2 pip install -e . ``` -------------------------------- ### Install Helm Source: https://github.com/yutiansut/quantaxis/blob/master/doc/deployment/overview.md Commands to download and verify the Helm installation on a Linux-based system. ```bash # 下载Helm curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash # 验证安装 helm version ``` -------------------------------- ### Start QA_SERVICE Source: https://github.com/yutiansut/quantaxis/blob/master/doc/deployment/docker.md Launch the QUANTAXIS service containers in detached mode. ```bash docker-compose up -d ``` -------------------------------- ### Execute QIFI Account Operations Source: https://github.com/yutiansut/quantaxis/blob/master/doc/api-reference/overview.md Example demonstrating account creation, order execution via receive_simpledeal, and position/balance inspection. ```python # 创建账户 account = QA.QIFI_Account("test", "test", "stock", 100000) # 买入 account.receive_simpledeal({ 'code': '000001', 'price': 10.5, 'amount': 1000, 'datetime': '2024-01-15', 'towards': 'buy' }) # 查看持仓 print(account.positions) # 卖出 account.receive_simpledeal({ 'code': '000001', 'price': 11.0, 'amount': 1000, 'datetime': '2024-01-20', 'towards': 'sell' }) # 查看盈亏 print(f"总盈亏: {account.balance - account.init_cash}") ``` -------------------------------- ### Install MacTeX on macOS Source: https://github.com/yutiansut/quantaxis/blob/master/qabook/README.md Use Homebrew to install the MacTeX distribution. ```bash # 使用Homebrew安装MacTeX brew install --cask mactex # 或下载完整安装包 # https://www.tug.org/mactex/ ``` -------------------------------- ### Compile QARS2 from Source Source: https://github.com/yutiansut/quantaxis/blob/master/doc/getting-started/installation.md Build QARS2 from the repository, ensuring Rust is installed on the system. ```bash # 克隆QARS2仓库 cd /home/quantaxis git clone https://github.com/yutiansut/qars2.git cd qars2 # 安装Rust(如果未安装) curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh source $HOME/.cargo/env # 编译安装 pip install -e . ``` -------------------------------- ### Install QARS2 via PyPI Source: https://github.com/yutiansut/quantaxis/blob/master/doc/getting-started/installation.md Use pip to install the QARS2 Rust account engine. ```bash pip install qars3 ``` -------------------------------- ### Verify LaTeX installation Source: https://github.com/yutiansut/quantaxis/blob/master/qabook/README.md Check the installed version of XeLaTeX to confirm the environment is ready. ```bash # 检查XeLaTeX版本 xelatex --version # 应该输出类似: # XeTeX 3.141592653-2.6-0.999995 (TeX Live 2024) ``` -------------------------------- ### Install TeX Live on Linux Source: https://github.com/yutiansut/quantaxis/blob/master/qabook/README.md Install the full TeX Live distribution or a minimal set with Chinese language support on Ubuntu/Debian systems. ```bash # 安装完整的TeX Live sudo apt-get update sudo apt-get install texlive-full # 或者安装基础版本 + 中文支持 sudo apt-get install texlive-base texlive-latex-extra \ texlive-xetex texlive-lang-chinese texlive-fonts-recommended ``` -------------------------------- ### Initialize and Start Live Trading Source: https://github.com/yutiansut/quantaxis/blob/master/doc/api-reference/qastrategy.md Instantiates the live trading engine, assigns a strategy and configuration, and initiates the execution loop. ```python from QUANTAXIS import QA_LiveTrading # 创建实盘交易实例 live_trading = QA_LiveTrading() # 设置策略和配置 live_trading.set_strategy(MyTrendStrategy) live_trading.set_config(live_config) # 启动实盘交易 live_trading.start() ``` -------------------------------- ### Stock Trading Strategy Example Source: https://github.com/yutiansut/quantaxis/blob/master/doc/api-reference/qamarket.md Shows how to place a buy order and a corresponding stop-loss order for a stock. ```python # 股票买卖示例 def stock_trading_strategy(): # 买入信号 buy_order = QA_Order( code='000001', price=10.50, volume=1000, direction=ORDER_DIRECTION.BUY, market_type=MARKET_TYPE.STOCK_CN ) # 设置止损单 stop_loss_order = QA_Order( code='000001', price=9.50, volume=1000, direction=ORDER_DIRECTION.SELL, order_type='STOP_LOSS' ) return [buy_order, stop_loss_order] ``` -------------------------------- ### Minimal MongoDB usage example Source: https://github.com/yutiansut/quantaxis/blob/master/doc/advanced/resource-manager.md Demonstrates the recommended context manager approach for MongoDB operations. ```python from QUANTAXIS.QAUtil.QAResourceManager import QAMongoResourceManager # 使用with语句(推荐) with QAMongoResourceManager() as mongo: db = mongo.get_database('quantaxis') result = db.stock_day.find_one({'code': '000001'}) print(result) # 自动关闭连接,无需手动close() ``` -------------------------------- ### Install Rust Toolchain Source: https://github.com/yutiansut/quantaxis/blob/master/doc/getting-started/installation.md Required for components utilizing Rust; ensure the environment is sourced after installation. ```bash # 安装Rust curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh source $HOME/.cargo/env # 更新Rust rustup update # 重新安装 pip install --force-reinstall quantaxis[rust] ``` -------------------------------- ### Start database services with Docker Compose Source: https://github.com/yutiansut/quantaxis/blob/master/qapro-rs/readme.md Launches the required infrastructure services (ClickHouse, Redis, MongoDB, RabbitMQ) using a Docker Compose file. ```bash docker-compose -f database.yaml up -d ``` -------------------------------- ### Export Documentation to PDF Source: https://github.com/yutiansut/quantaxis/blob/master/doc/MDBOOK_GUIDE.md Install the mdbook-pdf plugin and configure the output settings in book.toml to enable PDF generation. ```bash # 安装mdbook-pdf cargo install mdbook-pdf # 配置book.toml [output.pdf] enable = true # 构建PDF mdbook build ``` -------------------------------- ### 更新 setup.py 中的 Python 版本检查 Source: https://github.com/yutiansut/quantaxis/blob/master/UPGRADE_PLAN.md 修改 setup.py 以强制要求 Python 3.9-3.12 版本。 ```python # 当前 if sys.version_info.major != 3 or sys.version_info.minor not in [5, 6, 7, 8, 9, 10]: print('wrong version, should be 3.5/3.6/3.7/3.8/3.9 version') # 升级后 if sys.version_info < (3, 9) or sys.version_info >= (4, 0): print('错误: 需要 Python 3.9-3.12 版本') print('当前版本: {}.{}.{}'.format(*sys.version_info[:3])) sys.exit(1) ``` -------------------------------- ### Deploy QUANTAXIS with Helm Source: https://github.com/yutiansut/quantaxis/blob/master/doc/deployment/overview.md Workflow for configuring, installing, upgrading, and uninstalling the QUANTAXIS chart. ```bash cd QUANTAXIS/docker/helm-charts # 1. 添加仓库(如果有) # helm repo add quantaxis https://quantaxis.github.io/charts # helm repo update # 2. 查看默认配置 helm show values ./quantaxis # 3. 自定义配置 cat > custom-values.yaml << EOF # MongoDB配置 mongodb: auth: rootPassword: "your-root-password" password: "your-quantaxis-password" persistence: size: 100Gi # QUANTAXIS配置 quantaxis: replicas: 3 resources: limits: cpu: 4 memory: 8Gi requests: cpu: 1 memory: 2Gi EOF # 4. 安装 helm install quantaxis ./quantaxis \ --namespace quantaxis \ --create-namespace \ --values custom-values.yaml # 5. 查看状态 helm status quantaxis -n quantaxis helm list -n quantaxis # 6. 升级 helm upgrade quantaxis ./quantaxis \ --namespace quantaxis \ --values custom-values.yaml # 7. 卸载 helm uninstall quantaxis -n quantaxis ``` -------------------------------- ### Initialize QA_SERVICE on Linux Source: https://github.com/yutiansut/quantaxis/blob/master/doc/deployment/docker.md Download and run the service initialization script for Linux environments. ```bash wget https://raw.githubusercontent.com/QUANTAXIS/QUANTAXIS/master/docker/qaservice_docker.sh sudo bash qaservice_docker.sh ``` -------------------------------- ### Define Rust Integration File Structure Source: https://github.com/yutiansut/quantaxis/blob/master/UPGRADE_PLAN.md Lists the recommended file structure for new Rust integration examples. ```text examples/rust_integration/ ├── 01_qars_account_basic.py # QARS账户基础用法 ├── 02_polars_data_processing.py # Polars数据处理 ├── 03_dataswap_pubsub.py # 跨语言通信 ├── 04_qaexchange_trading.py # 模拟交易所对接 ├── 05_performance_comparison.py # 性能对比测试 └── README.md # 示例说明 ``` -------------------------------- ### Install Dependencies Source: https://github.com/yutiansut/quantaxis/blob/master/doc/advanced/resource-manager.md Install required packages to resolve ImportError. ```bash pip install pymongo motor pika clickhouse-driver redis # 或 pip install quantaxis[full] ``` -------------------------------- ### Install ELK Stack for Logging Source: https://github.com/yutiansut/quantaxis/blob/master/doc/deployment/overview.md Deploys Elasticsearch, Kibana, and Filebeat to the logging namespace. Filebeat automatically collects QUANTAXIS logs. ```bash # 安装Elastic Stack helm repo add elastic https://helm.elastic.co helm install elasticsearch elastic/elasticsearch -n logging --create-namespace helm install kibana elastic/kibana -n logging helm install filebeat elastic/filebeat -n logging # QUANTAXIS日志会被Filebeat收集 ``` -------------------------------- ### Install Prometheus via Helm Source: https://github.com/yutiansut/quantaxis/blob/master/doc/deployment/overview.md Deploys the kube-prometheus-stack to the monitoring namespace. QUANTAXIS includes pre-configured annotations for automatic metric discovery. ```bash # 安装Prometheus Operator helm repo add prometheus-community \ https://prometheus-community.github.io/helm-charts helm install prometheus \ prometheus-community/kube-prometheus-stack \ --namespace monitoring \ --create-namespace # QUANTAXIS已配置Prometheus注解 # 自动被Prometheus发现和抓取指标 ``` -------------------------------- ### Initialize QADataSwap Module Source: https://github.com/yutiansut/quantaxis/blob/master/UPGRADE_PLAN.md Sets up the QADataSwap module with conditional imports and fallback functions for environments where the library is not installed. ```python """ QADataSwap集成 - 跨语言零拷贝数据交换 支持Python/Rust/C++之间的高效数据传输: - 共享内存零拷贝 - Apache Arrow格式 - 支持DataFrame/行情/订单等数据 """ try: from qadataswap import ( SharedDataFrame, create_writer, create_reader, has_arrow_support ) HAS_DATASWAP = True except ImportError: HAS_DATASWAP = False import warnings warnings.warn( "QADataSwap未安装,跨语言通信功能不可用", ImportWarning ) __all__ = [ 'SharedDataFrame', 'create_writer', 'create_reader', 'has_dataswap_support', 'publish_market_data', 'subscribe_market_data', ] def has_dataswap_support(): return HAS_DATASWAP if HAS_DATASWAP: from .market_publisher import publish_market_data from .market_subscriber import subscribe_market_data else: def publish_market_data(*args, **kwargs): raise RuntimeError("QADataSwap未安装") def subscribe_market_data(*args, **kwargs): raise RuntimeError("QADataSwap未安装") ``` -------------------------------- ### Futures Cross-Month Arbitrage Example Source: https://github.com/yutiansut/quantaxis/blob/master/doc/api-reference/qamarket.md Demonstrates creating buy and sell orders for different contract months to execute an arbitrage strategy. ```python # 跨期套利示例 def cross_month_arbitrage(): # 买入近月合约 near_order = QA_Order( code='AU2012', price=400.0, volume=1, direction=ORDER_DIRECTION.BUY_OPEN ) # 卖出远月合约 far_order = QA_Order( code='AU2103', price=405.0, volume=1, direction=ORDER_DIRECTION.SELL_OPEN ) return [near_order, far_order] ``` -------------------------------- ### Automate LaTeX compilation with latexmk Source: https://github.com/yutiansut/quantaxis/blob/master/qabook/README.md Install latexmk, configure the build environment via .latexmkrc, and run compilation or continuous monitoring. ```bash # 安装latexmk sudo apt-get install latexmk # 创建.latexmkrc配置文件 cat > .latexmkrc << 'EOF' $pdf_mode = 5; # XeLaTeX模式 $xelatex = 'xelatex -interaction=nonstopmode -synctex=1 %O %S'; $out_dir = 'build'; EOF # 编译 latexmk quantaxis.tex # 持续监控模式 latexmk -pvc quantaxis.tex ``` -------------------------------- ### Verify QADataSwap Installation Source: https://github.com/yutiansut/quantaxis/blob/master/doc/getting-started/installation.md Check if the QADataSwap component is correctly installed and supported. ```python from QUANTAXIS.QADataBridge import has_dataswap_support if has_dataswap_support(): print("✅ QADataSwap已安装") else: print("❌ QADataSwap未安装") ``` -------------------------------- ### Verify and Reinstall QUANTAXIS Source: https://github.com/yutiansut/quantaxis/blob/master/doc/migration/v2.0-to-v2.1.md Use these commands to check the current installation version or perform a clean reinstall if the import fails. ```python # 检查安装 python -c "import QUANTAXIS; print(QUANTAXIS.__version__)" # 如果失败,重新安装 pip uninstall quantaxis -y pip install quantaxis==2.1.0a2 --no-cache-dir ``` -------------------------------- ### Initialize a Basic QIFI Account Source: https://github.com/yutiansut/quantaxis/blob/master/doc/api-reference/qifi.md Demonstrates creating a simulation account with initial cash settings. ```python from QUANTAXIS.QIFI import QIFI_Account # 创建模拟账户 account = QIFI_Account( username='test_user', password='password', model='SIM', init_cash=1000000 ) # 获取账户信息 print(f"用户ID: {account.user_id}") print(f"账户模式: {account.model}") print(f"初始资金: {account.init_cash}") ``` -------------------------------- ### Verify QARS2 Installation Source: https://github.com/yutiansut/quantaxis/blob/master/doc/getting-started/installation.md Check if the QARS2 engine is correctly installed and supported. ```python from QUANTAXIS.QARSBridge import has_qars_support if has_qars_support(): print("✅ QARS2已安装") else: print("❌ QARS2未安装") ``` -------------------------------- ### Install Loki Stack Source: https://github.com/yutiansut/quantaxis/blob/master/doc/deployment/overview.md Deploys the Loki logging stack via Helm. Requires adding Loki as a data source in Grafana. ```bash # 安装Loki Stack helm repo add grafana https://grafana.github.io/helm-charts helm install loki grafana/loki-stack -n logging --create-namespace # 在Grafana中添加Loki数据源 ``` -------------------------------- ### 实现多标的轮动策略 Source: https://github.com/yutiansut/quantaxis/blob/master/doc/user-guide/strategy-development.md 通过继承 QAMultiBase 类并实现 user_init 和 on_bar 方法来构建多标的交易逻辑。该策略根据动量指标选择标的并进行自动调仓。 ```python from QUANTAXIS.QAStrategy.qamultibase import QAMultiBase class MultiAssetStrategy(QAMultiBase): """多标的轮动策略""" def user_init(self): """初始化""" # 设置标的池 self.codes = ['rb2501', 'hc2501', 'i2501'] # 螺纹钢、热轧卷板、铁矿石 # 策略参数 self.momentum_period = 20 # 动量周期 self.top_n = 2 # 持仓数量 def on_bar(self, bars): """多标的K线回调 参数: bars: dict, {code: bar_data} """ # 1. 计算每个标的的动量 momentums = {} for code in self.codes: market_data = self.get_code_marketdata(code) if len(market_data) >= self.momentum_period: # 计算动量 = 当前价格 / N日前价格 - 1 current_price = market_data[-1]['close'] past_price = market_data[-self.momentum_period]['close'] momentum = (current_price / past_price) - 1 momentums[code] = momentum # 2. 选择动量最大的N个标的 sorted_codes = sorted(momentums.items(), key=lambda x: x[1], reverse=True) target_codes = [code for code, _ in sorted_codes[:self.top_n]] # 3. 调整持仓 positions = self.acc.positions # 平掉不在目标池的持仓 for code in list(positions.keys()): if code not in target_codes: pos = positions[code] if pos.volume_long > 0: self.SellClose(code, pos.volume_long) print(f"平仓 {code}") # 开仓目标标的 available_cash = self.acc.cash_available position_value = available_cash / len(target_codes) for code in target_codes: if code not in positions or positions[code].volume_long == 0: # 计算手数 price = bars[code].close volume = int(position_value / (price * 10)) # 假设合约乘数10 if volume > 0: self.BuyOpen(code, volume) print(f"开仓 {code}, 手数: {volume}") ``` -------------------------------- ### Configure Strategy Deployment Stages Source: https://github.com/yutiansut/quantaxis/blob/master/doc/user-guide/live-trading.md Demonstrates the progression from simulation to live trading with varying initial capital. ```python # 阶段1: 模拟盘测试(1-2周) strategy = MyStrategy(model='sim', init_cash=1000000) # 阶段2: 小资金实盘(1-2周) strategy = MyStrategy(model='live', init_cash=100000) # 阶段3: 正常资金实盘 strategy = MyStrategy(model='live', init_cash=1000000) ``` -------------------------------- ### Manage Multiple Accounts with QA_QIFIMANAGER Source: https://github.com/yutiansut/quantaxis/blob/master/doc/api-reference/qifi.md Shows how to instantiate multiple accounts, register them with a manager, and perform bulk updates. ```python from QUANTAXIS.QIFI import QA_QIFIMANAGER # 创建管理器 manager = QA_QIFIMANAGER() # 创建多个账户 accounts = [] for i in range(5): account = QIFI_Account( username=f'user_{i}', password='password', portfolio=f'portfolio_{i}' ) accounts.append(account) manager.add_account(account) # 批量管理 manager.update_all_positions() manager.calculate_total_pnl() ``` -------------------------------- ### Install LaTeX dependencies Source: https://github.com/yutiansut/quantaxis/blob/master/qabook/README.md Commands to install missing LaTeX packages on various operating systems. ```bash # Linux sudo apt-get install texlive-latex-extra # macOS sudo tlmgr install # Windows (MiKTeX) # 使用MiKTeX Package Manager安装缺失的包 ``` -------------------------------- ### Create Docker Volumes Source: https://github.com/yutiansut/quantaxis/blob/master/docker/kite/qa-community-rust2/qa-community-rust2.md Initialize the necessary persistent storage volumes for Kite, QAMG, and QACODE before the first container startup. ```bash docker volume create kite docker volume create qamg docker volume create qacode ``` -------------------------------- ### Configure MongoDB and RabbitMQ Connections Source: https://github.com/yutiansut/quantaxis/blob/master/doc/advanced/resource-manager.md Demonstrates initializing resource managers with custom URIs or authentication credentials. ```python # 从环境变量获取 import os mongo_uri = os.getenv('MONGODB_URI', 'mongodb://localhost:27017') with QAMongoResourceManager(uri=mongo_uri) as mongo: db = mongo.get_database('quantaxis') ``` ```python with QARabbitMQResourceManager( host='rabbitmq.example.com', username='quantaxis_user', password='secure_password', vhost='/quantaxis' ) as rabbitmq: channel = rabbitmq.get_channel() ``` -------------------------------- ### Install LaTeX Packages on macOS Source: https://github.com/yutiansut/quantaxis/blob/master/doc/qabook/build-guide.md Command to install missing packages using tlmgr on macOS. ```bash # 使用tlmgr安装缺失的包 sudo tlmgr install ``` -------------------------------- ### QA_util_get_trade_date(start, end) Source: https://github.com/yutiansut/quantaxis/blob/master/doc/api-reference/overview.md Retrieves a list of trading dates between the specified start and end dates. ```APIDOC ## QA_util_get_trade_date(start, end) ### Parameters - **start** (str): Start date - **end** (str): End date ### Returns - **list**: List of trading dates ``` -------------------------------- ### Install LaTeX Packages on Linux Source: https://github.com/yutiansut/quantaxis/blob/master/doc/qabook/build-guide.md Commands to install necessary LaTeX packages on Debian-based Linux distributions. ```bash # 安装扩展包 sudo apt-get install texlive-latex-extra # 或安装完整版 sudo apt-get install texlive-full ``` -------------------------------- ### Implement and Test a Simple MA Strategy Source: https://github.com/yutiansut/quantaxis/blob/master/doc/development/testing.md Demonstrates defining a strategy class inheriting from QAStrategyCtaBase and verifying backtest results using assertions. ```python # tests/test_backtest.py from QUANTAXIS.QAStrategy import QAStrategyCtaBase import QUANTAXIS as QA class TestBacktest: """回测测试""" def test_simple_ma_strategy(self): """测试简单MA策略""" class SimpleMAStrategy(QAStrategyCtaBase): def user_init(self): self.ma_period = 20 def on_bar(self, bar): market_data = self.get_code_marketdata(bar.code) if len(market_data) < self.ma_period: return close_prices = [x['close'] for x in market_data] ma = sum(close_prices[-self.ma_period:]) / self.ma_period positions = self.acc.positions if bar.close > ma and bar.code not in positions: self.BuyOpen(bar.code, 1) elif bar.close < ma and bar.code in positions: self.SellClose(bar.code, 1) # 运行回测 strategy = SimpleMAStrategy( code='rb2501', frequence='5min', start='2024-01-01', end='2024-12-31', init_cash=1000000 ) strategy.run_backtest() # 验证结果 acc = strategy.acc assert acc.balance > 0 assert acc.total_return is not None assert len(acc.trades) > 0 def test_strategy_metrics(self): """测试策略指标""" strategy = create_test_strategy() strategy.run_backtest() acc = strategy.acc # 基本指标 assert acc.sharpe_ratio is not None assert acc.max_drawdown is not None assert acc.win_rate >= 0 and acc.win_rate <= 1 # 收益率 total_return = (acc.balance / acc.init_cash - 1) * 100 assert total_return >= -100 # 最大亏损100% ``` -------------------------------- ### Install Rust Performance Components Source: https://github.com/yutiansut/quantaxis/blob/master/doc/migration/v2.0-to-v2.1.md Installs optional Rust-based components to improve performance for account operations and data handling. ```bash # 完整安装 (包括Rust组件) pip install quantaxis[rust] # 或分别安装 pip install qars3>=0.0.45 pip install qadataswap>=0.1.0 ``` -------------------------------- ### 使用build.sh脚本编译 Source: https://github.com/yutiansut/quantaxis/blob/master/doc/qabook/build-guide.md 通过build.sh脚本执行编译、清理及监控任务。 ```bash cd qabook/ # 编译PDF bash build.sh # 清理临时文件 bash build.sh clean # 监控模式 (文件变更自动重新编译) bash build.sh watch ``` -------------------------------- ### Install Chinese Fonts on Linux Source: https://github.com/yutiansut/quantaxis/blob/master/doc/qabook/build-guide.md Commands to install Chinese language support and fonts, followed by a font cache refresh. ```bash # 安装中文字体 sudo apt-get install -y \ texlive-lang-chinese \ fonts-wqy-microhei \ fonts-wqy-zenhei \ fonts-arphic-ukai \ fonts-arphic-uming # 刷新字体缓存 fc-cache -f -v ``` -------------------------------- ### Install Required Python Version Source: https://github.com/yutiansut/quantaxis/blob/master/doc/migration/v2.0-to-v2.1.md Commands to install Python 3.11+ on various operating systems to meet runtime requirements. ```bash # Ubuntu/Debian sudo apt install python3.11 # CentOS/RHEL sudo yum install python311 # macOS brew install python@3.11 # Windows # 从python.org下载安装3.11+ ``` -------------------------------- ### Deploy to Production Source: https://github.com/yutiansut/quantaxis/blob/master/doc/appendix/faq.md Deployment methods using Docker, Kubernetes, and Systemd service configuration. ```bash # 1. 使用Docker docker-compose up -d # 2. 使用Kubernetes kubectl apply -f k8s/ # 3. 使用Systemd # /etc/systemd/system/quantaxis.service [Unit] Description=QUANTAXIS Strategy After=network.target [Service] Type=simple User=quantaxis WorkingDirectory=/home/quantaxis/strategies ExecStart=/usr/bin/python3 strategy.py Restart=always [Install] WantedBy=multi-user.target # 启动服务 sudo systemctl enable quantaxis sudo systemctl start quantaxis ``` -------------------------------- ### Troubleshoot Pod startup failures Source: https://github.com/yutiansut/quantaxis/blob/master/doc/deployment/kubernetes.md Use these commands to inspect Pod status, events, and logs to identify common issues like image pull errors or resource constraints. ```bash # 查看Pod详情 kubectl describe pod -n quantaxis # 查看事件 kubectl get events -n quantaxis # 常见原因: # 1. 镜像拉取失败 → 检查镜像名称和权限 # 2. 资源不足 → kubectl top nodes # 3. 配置错误 → kubectl logs ``` -------------------------------- ### QAWebServer Web服务模块使用示例 Source: https://github.com/yutiansut/quantaxis/blob/master/doc/RemainingModules.md 展示如何创建基于 Tornado 的 Web 服务并添加路由。 ```python from QUANTAXIS.QAWebServer import QAWebServer # 创建Web服务 app = QAWebServer() # 添加路由 @app.route('/api/data') def get_data(request): return {'data': 'sample_data'} # 启动服务 app.run(port=8888) ``` -------------------------------- ### Uninstall Old Version Source: https://github.com/yutiansut/quantaxis/blob/master/doc/getting-started/installation.md Remove the existing installation before upgrading. ```bash pip uninstall quantaxis ``` -------------------------------- ### Deploy QUANTAXIS resources Source: https://github.com/yutiansut/quantaxis/blob/master/doc/deployment/overview.md Commands to initialize namespaces, secrets, storage, and core services in a Kubernetes cluster. ```bash cd QUANTAXIS/docker/k8s-deployment # 1. 创建命名空间 kubectl apply -f 00-namespace.yaml # 2. 创建ConfigMap和Secret kubectl apply -f 01-configmap.yaml # 修改密码 (生产环境必须!) kubectl create secret generic mongodb-secret \ --from-literal=MONGO_ROOT_USER=root \ --from-literal=MONGO_ROOT_PASSWORD='your-strong-password' \ --from-literal=MONGO_USER=quantaxis \ --from-literal=MONGO_PASSWORD='quantaxis-password' \ --namespace=quantaxis --dry-run=client -o yaml | kubectl apply -f - # 3. 创建存储 kubectl apply -f 03-storage.yaml # 4. 部署数据库服务 kubectl apply -f 10-mongodb.yaml kubectl apply -f 11-rabbitmq.yaml kubectl apply -f 12-redis.yaml # 5. 等待数据库就绪 kubectl wait --for=condition=ready pod -l app=mongodb -n quantaxis --timeout=300s kubectl wait --for=condition=ready pod -l app=rabbitmq -n quantaxis --timeout=300s # 6. 部署QUANTAXIS核心服务 kubectl apply -f 50-quantaxis.yaml # 7. 验证部署 kubectl get pods -n quantaxis kubectl get svc -n quantaxis ``` -------------------------------- ### Check QARS Support Source: https://github.com/yutiansut/quantaxis/blob/master/doc/api-reference/overview.md Verify if the QARS2 bridge is installed and available. ```python from QUANTAXIS.QARSBridge import has_qars_support if has_qars_support(): print("✅ QARS2可用") ``` -------------------------------- ### Compile QABook using build script Source: https://github.com/yutiansut/quantaxis/blob/master/qabook/README.md Use the provided bash script to compile, clean, or watch for changes in the documentation. ```bash # 进入qabook目录 cd qabook/ # 编译PDF bash build.sh # 清理临时文件 bash build.sh clean # 监控模式(文件变更自动重新编译) bash build.sh watch ``` -------------------------------- ### GET /api/v1/positions Source: https://github.com/yutiansut/quantaxis/blob/master/UPGRADE_PLAN.md Retrieves the current list of positions for the authenticated user. ```APIDOC ## GET /api/v1/positions ### Description Fetches the current holdings and positions. ### Method GET ### Endpoint /api/v1/positions ``` -------------------------------- ### Update setup.py dependencies Source: https://github.com/yutiansut/quantaxis/blob/master/UPGRADE_PLAN.md Defines required and optional dependencies including Rust-based components for the project. ```python # 新增依赖 install_requires=[ # ... 现有依赖 ... 'polars>=0.20.0,<0.22.0', 'orjson>=3.10.0', 'msgpack>=1.1.0', ], # 可选依赖 extras_require={ 'rust': [ 'qars3>=0.0.45', 'qadataswap>=0.1.0', ], 'full': [ 'qars3>=0.0.45', 'qadataswap>=0.1.0', 'polars>=0.20.0', 'jupyter>=1.0.0', ], }, ``` -------------------------------- ### QA_util_make_min_index Source: https://github.com/yutiansut/quantaxis/blob/master/doc/api-reference/qautil.md Generates a minute-level time index based on start and end times. ```APIDOC ## QA_util_make_min_index ### Description Generates a sequence of minute-level timestamps between a start and end time. ### Parameters - **start** (string) - Start time (e.g., '09:30') - **end** (string) - End time (e.g., '15:00') - **freq** (string) - Frequency (e.g., '1min') ``` -------------------------------- ### has_qars_support Source: https://github.com/yutiansut/quantaxis/blob/master/UPGRADE_PLAN.md Utility function to check if the high-performance QARS2 Rust core is installed and available. ```APIDOC ## Function: has_qars_support() ### Description Checks if the QARS2 Rust core is installed and available for use. If not, the system will fall back to pure Python implementations. ### Returns - **bool**: True if QARS2 is available, False otherwise. ``` -------------------------------- ### Verify PyArrow Installation Source: https://github.com/yutiansut/quantaxis/blob/master/doc/advanced/data-bridge.md Ensure PyArrow is updated to support zero-copy conversion performance. ```bash # 升级PyArrow到最新版本 pip install --upgrade pyarrow>=15.0.0 # 验证PyArrow安装 python -c "import pyarrow; print(pyarrow.__version__)" ``` -------------------------------- ### Web/API 服务器硬件配置 Source: https://github.com/yutiansut/quantaxis/blob/master/doc/deployment/production.md XServer 节点的推荐硬件规格,适用于负载均衡后的 API 服务。 ```yaml XServer Node: CPU: 16核心 内存: 64GB 存储: 1TB SSD 网络: 10Gbps ``` -------------------------------- ### Verify and Reinstall Plugins Source: https://github.com/yutiansut/quantaxis/blob/master/doc/MDBOOK_GUIDE.md Check if specific mdBook plugins are installed and force a reinstall if they are not working. ```bash # 确认插件已安装 which mdbook-mermaid which mdbook-toc # 重新安装 cargo install --force mdbook-mermaid cargo install --force mdbook-toc ``` -------------------------------- ### Build and Release Commands Source: https://github.com/yutiansut/quantaxis/blob/master/UPGRADE_PLAN.md Commands for packaging the project, uploading to PyPI, and building Docker images. ```bash # 构建发布包 python setup.py sdist bdist_wheel # 上传到PyPI twine upload dist/quantaxis-2.1.0* # Docker镜像 docker build -t daocloud.io/quantaxis/qa-base:2.1.0 . docker push daocloud.io/quantaxis/qa-base:2.1.0 ``` -------------------------------- ### Verify Documentation Build Source: https://github.com/yutiansut/quantaxis/blob/master/doc/MDBOOK_GUIDE.md Use mdbook commands to validate the SUMMARY.md syntax and check for build errors. ```bash # 验证SUMMARY.md语法 mdbook test # 检查链接 mdbook build 2>&1 | grep -i error ``` -------------------------------- ### Manage MongoDB Connection Source: https://github.com/yutiansut/quantaxis/blob/master/doc/getting-started/installation.md Commands to verify status, start the service, and test the connection to MongoDB. ```bash # 检查MongoDB状态 sudo systemctl status mongod # 启动MongoDB sudo systemctl start mongod # 测试连接 mongosh ``` -------------------------------- ### Initialize QARS Backtest Source: https://github.com/yutiansut/quantaxis/blob/master/doc/api-reference/overview.md Initialize the high-performance Rust backtest engine. ```python from QUANTAXIS.QARSBridge import QARSBacktest backtest = QARSBacktest( code="000001", start_date="2024-01-01", end_date="2024-01-31", init_cash=100000.0 ) ``` -------------------------------- ### Beginner Practice Exercises Source: https://github.com/yutiansut/quantaxis/blob/master/doc/getting-started/quickstart.md Suggested exercises for users in the first two weeks to practice data acquisition and basic analysis. ```python # 练习1: 获取多只股票数据并对比 # 练习2: 计算并可视化MA、MACD等指标 # 练习3: 分析成交量与价格的关系 ``` -------------------------------- ### Deploy Specific Profiles Source: https://github.com/yutiansut/quantaxis/blob/master/doc/deployment/overview.md Starts only the specified service components using Docker Compose profiles. ```bash # 仅启动分析服务(包括ClickHouse) docker-compose --profile analytics up -d # 仅启动行情采集 docker-compose --profile market up -d ``` -------------------------------- ### Implement Portfolio Management Source: https://github.com/yutiansut/quantaxis/blob/master/doc/api-reference/qastrategy.md Extends QAMultiBase to manage multiple strategies, handle capital allocation, and aggregate trading results. ```python from QUANTAXIS.QAStrategy.qamultibase import QAMultiBase class PortfolioManager(QAMultiBase): def __init__(self): super().__init__() self.strategies = [] def add_strategy(self, strategy, weight): self.strategies.append({ 'strategy': strategy, 'weight': weight }) def allocate_capital(self, total_capital): for item in self.strategies: allocated = total_capital * item['weight'] item['strategy'].set_capital(allocated) def run_strategies(self, data): results = [] for item in self.strategies: result = item['strategy'].handle_data(data) results.append(result) return self.combine_results(results) ``` -------------------------------- ### 检查Kubernetes集群版本 Source: https://github.com/yutiansut/quantaxis/blob/master/doc/deployment/kubernetes.md 验证当前Kubernetes集群版本是否满足v1.24+的推荐要求。 ```bash # 检查集群版本 kubectl version # 推荐版本 Kubernetes: v1.24+ ``` -------------------------------- ### Compile the project Source: https://github.com/yutiansut/quantaxis/blob/master/qapro-rs/readme.md Builds the project in release mode for supported platforms. ```bash cargo build --release ```