### Install Configuration File - Shell Source: https://github.com/ufund-me/qbot/blob/main/qbot/engine/trade/trading/bitcoin-arbitrage/README.md Copies the example configuration file to be edited for user preferences. This is a prerequisite for setting up the arbitrage bot. ```shell cp arbitrage/config.py-example arbitrage/config.py ``` -------------------------------- ### Setup Development Environment and Dependencies Source: https://github.com/ufund-me/qbot/blob/main/docs/tutorials_code/15.rl_learning/README.md Commands to create a Python virtual environment and install the necessary dependencies for the reinforcement learning project. ```bash # 虚拟环境 virtualenv -p python3.6 venv source ./venv/bin/activate # 安装库依赖 pip install -r requirements.txt ``` -------------------------------- ### Start Node.js Application Source: https://github.com/ufund-me/qbot/blob/main/pyfunds/fund-strategies/README.md Starts the Node.js development server. This command is used after installing dependencies. ```bash npm start ``` -------------------------------- ### Setup and Run LightGBM Model on CSI500 Source: https://github.com/ufund-me/qbot/blob/main/pytrader/strategies/benchmarks/README.md This snippet demonstrates how to set up a LightGBM model for the CSI500 benchmark. It includes installing dependencies, creating a new configuration file, modifying it for CSI500, and running the model either once or multiple times for summarized results. ```bash cd examples/benchmarks/LightGBM pip install -r requirements.txt # create new config and set the benchmark to csi500 cp workflow_config_lightgbm_Alpha158.yaml workflow_config_lightgbm_Alpha158_csi500.yaml sed -i "s/csi300/csi500/g" workflow_config_lightgbm_Alpha158_csi500.yaml sed -i "s/SH000300/SH000905/g" workflow_config_lightgbm_Alpha158_csi500.yaml # you can either run the model once qrun workflow_config_lightgbm_Alpha158_csi500.yaml # or run it for multiple times automatically and get the summarized results. cd ../../ python run_all_model.py run 3 lightgbm Alpha158 csi500 # for models with randomness. please run it for 20 times. ``` -------------------------------- ### Client Setup Source: https://github.com/ufund-me/qbot/blob/main/qbot/engine/trade/easytrader/docs/usage.md This section covers how to import the library and set up different trading client types. ```APIDOC ## Client Setup ### Import Library ```python import easytrader ``` ### Set Trading Client Type **Haitong Client** ```python user = easytrader.use('htzq_client') ``` **Huatai Client** ```python user = easytrader.use('ht_client') ``` **Guojin Client** ```python user = easytrader.use('gj_client') ``` **Universal Tonghuashun Client** ```python user = easytrader.use('universal_client') ``` Note: The Universal Tonghuashun client is a fallback for when brokers do not directly provide a Tonghuashun client. It supports trading through multiple brokers. **Other Broker-Specific Tonghuashun Clients** ```python user = easytrader.use('ths') ``` Note: These are versions modified by brokers based on Tonghuashun, such as Yinhe's Gemini (Tonghuashun version) or Guojin Securities' independent trading program (Kernew PC version). **Xueqiu** ```python user = easytrader.use('xq') ``` ``` -------------------------------- ### Install xalpha Source: https://github.com/ufund-me/qbot/blob/main/pyfunds/backtest/README.md Methods to install the xalpha library via pip or from source. ```bash pip install xalpha git clone https://github.com/refraction-ray/xalpha.git cd xalpha && python3 setup.py install ``` -------------------------------- ### Install EasyTrader Library Source: https://github.com/ufund-me/qbot/blob/main/qbot/engine/trade/easytrader/docs/install.md Installs the EasyTrader package using pip. Windows users may need to manually install missing dependencies if prompted. ```shell pip install easytrader ``` -------------------------------- ### Clone and Install Project Dependencies Source: https://github.com/ufund-me/qbot/blob/main/pytrader/frontend/readme.md This snippet shows the commands to clone the Element Plus Admin project from GitHub, navigate into the project directory, and install all necessary dependencies using npm. ```bash git clone https://github.com/hsiangleev/element-plus-admin.git cd element-plus-admin npm install ``` -------------------------------- ### Install Baostock Data Library Source: https://github.com/ufund-me/qbot/blob/main/docs/tutorials_code/15.rl_learning/README.md Installs the Baostock library using a specific mirror for faster package retrieval, used for fetching historical stock market data. ```bash pip install baostock -i https://pypi.tuna.tsinghua.edu.cn/simple/ --trusted-host pypi.tuna.tsinghua.edu.cn ``` -------------------------------- ### Start Development Server Source: https://github.com/ufund-me/qbot/blob/main/pytrader/frontend/readme.md Commands to start the local development server for the Element Plus Admin project. After running this, the application can be accessed via a browser at http://localhost:3002. ```bash npm run dev ``` -------------------------------- ### Configure for Quantitative Platforms Source: https://github.com/ufund-me/qbot/blob/main/pyfunds/backtest/README.md Setup commands to use xalpha within cloud-based quantitative research environments like JoinQuant. ```python !pip3 install xalpha --user import sys sys.path.insert(0, "/home/jquser/.local/lib/python3.6/site-packages") import xalpha as xa # For development version !git clone https://github.com/refraction-ray/xalpha.git !cd xalpha && python3 setup.py develop --user ``` -------------------------------- ### Web Server API Source: https://github.com/ufund-me/qbot/blob/main/qbot/plugins/investool/README.md This API endpoint allows you to start the QBot web server. You can specify a configuration file path. ```APIDOC ## POST /ufund-me/qbot/webserver ### Description Starts the QBot web server. It's recommended to increase the reverse proxy timeout for this service as the stock screening process can be time-consuming. ### Method POST ### Endpoint /ufund-me/qbot/webserver ### Parameters #### Query Parameters - **config** (string) - Optional - Path to the configuration file. Defaults to `./config.toml` in the current directory. ### Request Example ```bash ./investool webserver --config /path/to/your/config.toml ``` ### Response #### Success Response (200) - **status** (string) - Server status message (e.g., "Web server started successfully."). #### Response Example ```json { "status": "Web server started successfully on port 8080." } ``` ``` -------------------------------- ### Install FinRL Library Source: https://github.com/ufund-me/qbot/blob/main/docs/notebook/Stock_NeurIPS2018_SB3.ipynb Installs the FinRL library directly from its GitHub repository using pip. This command ensures that the latest version of the library and its dependencies are fetched and installed. ```bash !pip install git+https://github.com/AI4Finance-Foundation/FinRL.git ``` -------------------------------- ### Start Investool Web Server Source: https://github.com/ufund-me/qbot/blob/main/qbot/plugins/investool/README.md Launches the web server component of the tool. It reads configuration from config.toml by default, and users should ensure reverse proxy timeouts are adjusted for high-load scenarios. ```bash ./investool webserver ``` -------------------------------- ### Configure and Start Online Trading Engine Source: https://github.com/ufund-me/qbot/blob/main/pytrader/README.md Demonstrates how to initialize the MainEngine for online trading using the Eastmoney broker. It sets up logging and enables automatic strategy reloading. ```python import easyquant from easyquant import DefaultLogHandler broker = 'eastmoney' need_data = 'account.json' log_handler = DefaultLogHandler(name='测试', log_type='file', filepath='logs.log') m = easyquant.MainEngine(broker, need_data, quotation='online', bar_type="1m", log_handler=log_handler) m.is_watch_strategy = True m.load_strategy() m.start() ``` -------------------------------- ### Install Node.js Dependencies Source: https://github.com/ufund-me/qbot/blob/main/pyfunds/fund-strategies/README.md Installs project dependencies using npm. Requires a Node.js development environment. ```bash npm install ``` -------------------------------- ### Exportor CLI Examples Source: https://github.com/ufund-me/qbot/blob/main/qbot/plugins/investool/README.md Demonstrates various command-line invocations of the investool exportor tool to export stock data into different file formats and with custom parameters. ```bash ./investool -l error exportor -f ./stocks.json ``` ```bash ./investool -l error exportor -f ./stocks.csv ``` ```bash ./investool -l error exportor -f ./stocks.xlsx ``` ```bash ./investool -l error exportor -f ./stocks.png ``` ```bash ./investool -l error exportor -f ./stocks.all ``` ```bash ./investool -l error exportor -f ./stocks.xlsx --filter.min_roe=6 --checker.min_roe=6 ``` ```bash ./investool -l error exportor -f ./stocks.xlsx --filter.special_security_name_abbr_list 福莱特 --filter.special_security_name_abbr_list 旗滨集团 --disable_check ``` -------------------------------- ### Import Libraries and Setup Source: https://github.com/ufund-me/qbot/blob/main/docs/notebook/choose_stock.ipynb Imports necessary Python libraries for data analysis, plotting, and financial data retrieval. It also sets up plotting configurations and initializes the Tushare API. ```python %matplotlib inline %matplotlib widget import backtrader.plot import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt plt.rcParams['figure.figsize'] = [15, 8] import tushare as ts from datetime import datetime import backtrader as bt import pandas as pd import os import numpy as np ``` -------------------------------- ### Qbot CLI Get Account Information Source: https://github.com/ufund-me/qbot/blob/main/qbot/engine/trade/easytrader/docs/usage.md This command retrieves various account details, such as balance, holdings, and other relevant variables, from the Qbot system. ```bash python cli.py --get balance ``` -------------------------------- ### Example Tushare API Usage Parameters Source: https://github.com/ufund-me/qbot/blob/main/docs/02-经典策略/01-股票/量化一-均值策略.md Illustrates the parameters required for fetching historical data using the Tushare API. This includes the stock code (e.g., '600515.SH'), the start date in 'YYYYMMDD' format, and the end date in 'YYYYMMDD' format. These parameters are essential for specifying the data range for analysis. ```python ts_code='600515.SH' start_date='20190101' end_date='20191231' ``` -------------------------------- ### Qbot CLI Help Source: https://github.com/ufund-me/qbot/blob/main/qbot/engine/trade/easytrader/docs/usage.md This command displays the help information for the Qbot command-line interface, listing all available commands and their options. ```bash python cli.py --help ``` -------------------------------- ### Install Python Dependencies - Shell Source: https://github.com/ufund-me/qbot/blob/main/qbot/engine/trade/trading/bitcoin-arbitrage/README.md Installs Python 3 and necessary packages like pip and python-nose on Debian-based systems. For the XMPPMessager observer, sleekxmpp is also installed via pip3. ```shell sudo apt-get install python3 python3-pip python-nose ``` ```shell pip3 install sleekxmpp ``` -------------------------------- ### Build Documentation Locally Source: https://github.com/ufund-me/qbot/blob/main/pyfunds/backtest/README.md Commands to generate HTML documentation from the source files. ```bash cd doc make html ``` -------------------------------- ### Get Daily Financial Data with xalpha Source: https://github.com/ufund-me/qbot/blob/main/pyfunds/backtest/doc/source/quickstart.md Fetches daily historical data for a given financial instrument code. Supports stocks, funds, ETFs, bonds, currencies, and indices from various markets (China, Hong Kong, US) and sources like investing.com, FT, and S&P. The function returns a pandas DataFrame. Optional parameters like 'prev', 'start', and 'end' can be used to specify the date range. ```python >>> xa.get_daily("EUR/CNY", prev=5) # 人民币中间价数据 date close 4 2020-03-30 7.8288 3 2020-03-31 7.8088 2 2020-04-01 7.8090 1 2020-04-02 7.7678 0 2020-04-03 7.7081 ``` ```python >>> xa.get_daily("currencies/usd-cnh") # 英为离岸人民币 date open close high low percent 260 2019-04-05 6.7167 6.7122 6.7194 6.7033 -0.07% 259 2019-04-08 6.7100 6.7173 6.7278 6.7082 0.08% 258 2019-04-09 6.7172 6.7195 6.7241 6.7127 0.03% 257 2019-04-10 6.7188 6.7187 6.7270 6.7164 -0.01% .. 3 2020-03-31 7.1133 7.0940 7.1177 7.0796 -0.29% 2 2020-04-01 7.0932 7.1230 7.1336 7.0772 0.41% 1 2020-04-02 7.1216 7.0929 7.1422 7.0846 -0.42% 0 2020-04-03 7.0919 7.1108 7.1197 7.0857 0.25% ``` ```python >>> xa.get_daily("FT-ZGLD:SWX:CHF", start="2020-03-01") # ft.com 基金数据 date open close high low 24 2020-03-02 470.10 465.30 472.05 463.75 23 2020-03-03 465.95 477.20 477.85 465.30 22 2020-03-04 477.05 478.00 480.85 475.35 21 2020-03-05 476.75 479.15 481.30 476.75 .. 3 2020-03-31 475.70 474.00 475.70 469.80 2 2020-04-01 466.90 468.10 470.80 464.10 1 2020-04-02 468.45 476.75 479.80 467.40 0 2020-04-03 477.80 481.00 483.00 477.55 ``` ```python >>> xa.get_daily("HK00700", prev=5, end="2018-08-08") # 雪球港股数据 date open close high low percent 198 2018-08-03 347.2475 348.8432 353.6300 345.6519 1.39 199 2018-08-06 356.8213 352.0344 356.8213 349.0426 0.91 200 2018-08-07 354.0289 356.0235 357.4196 347.6464 1.13 201 2018-08-08 365.5972 363.0043 365.5972 359.6136 1.96 ``` ```python >>> xa.get_daily("SH000050", prev=10) # 雪球A股指数数据 date open close high low percent 3 2020-03-25 2203.7900 2206.63 2216.0700 2188.3800 2.41 4 2020-03-26 2187.4600 2193.85 2208.5900 2179.9800 -0.58 5 2020-03-27 2219.5900 2203.25 2232.4400 2202.3000 0.43 6 2020-03-30 2172.8685 2188.88 2196.6724 2168.4372 -0.65 7 2020-03-31 2207.6900 2176.42 2208.7200 2173.4300 -0.57 8 2020-04-01 2170.1100 2171.34 2203.6400 2168.4400 -0.23 9 2020-04-02 2160.1300 2204.57 2204.5700 2159.0300 1.53 10 2020-04-03 2197.7113 2195.55 2210.2124 2188.8462 -0.41 ``` -------------------------------- ### Initialize and Summarize Fund Portfolio Source: https://github.com/ufund-me/qbot/blob/main/pyfunds/backtest/doc/samples/mul.ipynb Demonstrates how to load transaction data from a CSV file, initialize a fund portfolio object, and generate a summary of current holdings and performance. ```python import xalpha as xa import pandas as pd xa.set_display("notebook") path = "../../tests/demo.csv" read = xa.record(path) sysopen = xa.mul(status=read.status) summary = sysopen.combsummary().sort_values(by="基金现值", ascending=False) ``` -------------------------------- ### Build and Preview Project Source: https://github.com/ufund-me/qbot/blob/main/pytrader/frontend/readme.md Commands to build the Element Plus Admin project for production and preview the built application locally. This is typically done before deploying the application. ```bash npm run build npm run preview ``` -------------------------------- ### Configure and Execute Backtest and Analysis in Qlib Source: https://github.com/ufund-me/qbot/blob/main/docs/notebook/workflow_by_code.ipynb This Python snippet defines the configuration for a backtesting and analysis process, including executor, strategy, and backtest parameters. It then loads a trained model and generates prediction and portfolio analysis records. ```python ################################### # prediction, backtest & analysis ################################### port_analysis_config = { "executor": { "class": "SimulatorExecutor", "module_path": "qlib.backtest.executor", "kwargs": { "time_per_step": "day", "generate_portfolio_metrics": True, }, }, "strategy": { "class": "TopkDropoutStrategy", "module_path": "qlib.contrib.strategy.signal_strategy", "kwargs": { "model": model, "dataset": dataset, "topk": 50, "n_drop": 5, }, }, "backtest": { "start_time": "2017-01-01", "end_time": "2020-08-01", "account": 100000000, "benchmark": benchmark, "exchange_kwargs": { "freq": "day", "limit_threshold": 0.095, "deal_price": "close", "open_cost": 0.0005, "close_cost": 0.0015, "min_cost": 5, }, }, } # backtest and analysis with R.start(experiment_name="backtest_analysis"): recorder = R.get_recorder(recorder_id=rid, experiment_name="train_model") model = recorder.load_object("trained_model") # prediction recorder = R.get_recorder() ba_rid = recorder.id sr = SignalRecord(model, dataset, recorder) sr.generate() # backtest & analysis par = PortAnaRecord(recorder, port_analysis_config, "day") par.generate() ``` -------------------------------- ### Configure and Run Backtest Source: https://github.com/ufund-me/qbot/blob/main/docs/02-经典策略/01-股票/多因子选股.md This snippet initializes the backtesting environment with parameters such as strategy ID, time range, initial capital, commission rates, and slippage. It uses the run function to execute the strategy in a specified mode. ```python run(strategy_id='strategy_id', filename='main.py', mode=MODE_BACKTEST, token='token_id', backtest_start_time='2017-07-01 08:00:00', backtest_end_time='2017-10-01 16:00:00', backtest_adjust=ADJUST_PREV, backtest_initial_cash=10000000, backtest_commission_ratio=0.0001, backtest_slippage_ratio=0.0001) ``` -------------------------------- ### Initialize and Configure Xueqiu Follower Source: https://github.com/ufund-me/qbot/blob/main/qbot/engine/trade/easytrader/docs/usage.md This section covers initializing a follower for Xueqiu (snowball) portfolios. It includes logging in using Xueqiu cookies and configuring the follower to track a specific portfolio ID. For Xueqiu, which uses percentage-based rebalancing, `total_assets` or `initial_assets` must be set to define the portfolio's capital. The `adjust_sell` parameter can be used to refine sell order quantities based on actual holdings. ```python xq_follower = easytrader.follower('xq') ``` ```python xq_follower.login(cookies='雪球 cookies,登陆后获取,获取方式见 https://smalltool.github.io/2016/08/02/cookie/') ``` ```python xq_follower.follow(xq_user, 'xq组合ID,类似ZH123456', total_assets=100000) ``` -------------------------------- ### GET /thsauto/cancel Source: https://github.com/ufund-me/qbot/blob/main/qbot/engine/trade/trading/thsauto/README.md Cancels an existing active order. ```APIDOC ## GET /thsauto/cancel ### Description Cancels a pending order based on the provided entrustment number. ### Method GET ### Endpoint /thsauto/cancel ### Parameters #### Query Parameters - **entrust_no** (string) - Required - The entrustment number of the order to cancel ### Response #### Success Response (200) - **message** (string) - Confirmation message #### Response Example { "status": "success", "message": "Order cancelled successfully" } ``` -------------------------------- ### GET /thsauto/buy Source: https://github.com/ufund-me/qbot/blob/main/qbot/engine/trade/trading/thsauto/README.md Executes a buy order for a specified stock. ```APIDOC ## GET /thsauto/buy ### Description Places a buy order for a specific stock using the provided price and quantity. ### Method GET ### Endpoint /thsauto/buy ### Parameters #### Query Parameters - **stock_no** (string) - Required - The stock code - **price** (float) - Required - The buy price - **amount** (int) - Required - The number of shares ### Response #### Success Response (200) - **entrust_no** (string) - The order entrustment number #### Response Example { "status": "success", "entrust_no": "12345678" } ``` -------------------------------- ### Create a Trading Environment Source: https://github.com/ufund-me/qbot/blob/main/docs/notebook/Stock_NeurIPS2018_SB3.ipynb Sets up a custom trading environment using the FinRL library. This environment simulates stock market conditions for backtesting trading strategies. ```python from finrl.meta.env_stock_trading.env_stocktrading import StockTradingEnv # Define environment parameters stock_list = ['AAPL', 'MSFT', 'GOOG'] initial_capital = 100000 # Create the environment env = StockTradingEnv(df=None, stock_list=stock_list, initial_capital=initial_capital, hmax=100, # Max number of shares to trade each time reward_scaling=1e-4) # Access environment details obs = env.reset() print(f'Observation Space: {env.observation_space}') print(f'Action Space: {env.action_space}') ``` -------------------------------- ### GET /thsauto/balance Source: https://github.com/ufund-me/qbot/blob/main/qbot/engine/trade/trading/thsauto/README.md Retrieves the current balance information for the connected trading account. ```APIDOC ## GET /thsauto/balance ### Description Fetches the current capital and balance details from the trading account. ### Method GET ### Endpoint /thsauto/balance ### Response #### Success Response (200) - **balance** (object) - Account balance details #### Response Example { "status": "success", "data": { "total_asset": 100000.00, "available_cash": 50000.00 } } ``` -------------------------------- ### Acquire Market Data with easyquotation Source: https://context7.com/ufund-me/qbot/llms.txt Demonstrates how to initialize a data source and fetch real-time stock quotes or K-line data using the easyquotation library. ```python import easyquotation # Use sina source for real-time quotes quotation = easyquotation.use("sina") stock_info = quotation.real(["000001"]) # Fetch daily K-line data daykline = easyquotation.use("daykline") kline_data = daykline.real(["000001"]) ``` -------------------------------- ### Initialize Snowball Portfolio Simulation Source: https://github.com/ufund-me/qbot/blob/main/qbot/engine/trade/easytrader/docs/other/xueqiu.md Demonstrates how to initialize the `easytrader` library for simulating trades with a Snowball (Xueqiu) portfolio. It shows how to set initial assets based on the portfolio's net value. ```python import easytrader # Initialize with default initial assets # For custom initial assets, use: easytrader.use('xq', initial_assets=1000000.0) ``` -------------------------------- ### Get Bar Data Source: https://github.com/ufund-me/qbot/blob/main/pyfunds/backtest/doc/samples/newparadigm.ipynb Fetches bar data (e.g., minute, hour) for indices. ```APIDOC ## Get Bar Data for Indices ### Description Fetches bar data (e.g., minute, hour) for indices. ### Method GET ### Endpoint /api/indices/bar/{symbol} ### Parameters #### Path Parameters - **symbol** (string) - Required - The index symbol (e.g., indices/germany-30). #### Query Parameters - **interval** (integer) - Required - The interval in seconds (e.g., 3600 for hourly data). ### Request Example ```python xa.get_bar("indices/germany-30", interval=3600) ``` ### Response #### Success Response (200) - **timestamp** (integer) - The Unix timestamp of the bar. - **open** (float) - The opening price. - **high** (float) - The highest price. - **low** (float) - The lowest price. - **close** (float) - The closing price. - **volume** (integer) - The trading volume. #### Response Example ```json { "timestamp": 1678886400, "open": 15000.50, "high": 15050.75, "low": 14980.25, "close": 15020.00, "volume": 100000 } ``` ``` -------------------------------- ### Get Real-time Data Source: https://github.com/ufund-me/qbot/blob/main/pyfunds/backtest/doc/source/quickstart.md Retrieves real-time quote data for a specified financial instrument. ```APIDOC ## GET /api/data/rt ### Description Fetches real-time quote data for a specified financial instrument. ### Method GET ### Endpoint /api/data/rt ### Parameters #### Query Parameters - **code** (string) - Required - The unique identifier for the financial instrument (e.g., "SH501018", "indices/germany-30"). ### Request Example ```python import xalpha as xa # Get real-time data for a Chinese fund rt_data_cn = xa.get_rt("SH501018") print(rt_data_cn) # Get real-time data for a German index rt_data_de = xa.get_rt("indices/germany-30") print(rt_data_de) ``` ### Response #### Success Response (200) - **JSON Object** - A JSON object containing real-time quote information, typically including 'name', 'current', 'percent', 'currency', and 'market'. #### Response Example ```json { "name": "南方原油LOF", "current": 0.826, "percent": -0.48, "current_ext": null, "currency": "CNY", "market": "CN" } ``` ``` -------------------------------- ### Upgrade EasyTrader Library Source: https://github.com/ufund-me/qbot/blob/main/qbot/engine/trade/easytrader/docs/install.md Updates the existing EasyTrader installation to the latest version available on PyPI. ```shell pip install easytrader -U ``` -------------------------------- ### Initialize Xalpha Library Source: https://github.com/ufund-me/qbot/blob/main/pyfunds/backtest/doc/samples/newparadigm.ipynb Imports the library and sets up the global local cache backend. It is recommended to use the xa.meth pattern for function calls to ensure dynamic features function correctly. ```python import xalpha as xa xa.set_backend(backend="csv", path="../../../lof/data", precached="20170101") ``` -------------------------------- ### GET /fund/managers Source: https://github.com/ufund-me/qbot/blob/main/qbot/plugins/investool/statics/html/fund_managers.html Retrieves a paginated list of fund managers based on various performance and profile filters. ```APIDOC ## GET /fund/managers ### Description Retrieves a filtered list of fund managers with pagination support. ### Method GET ### Endpoint /fund/managers ### Parameters #### Query Parameters - **page_num** (integer) - Optional - Current page number - **page_size** (integer) - Optional - Number of records per page - **sort** (string) - Optional - Sorting criteria - **min_working_years** (integer) - Optional - Minimum years of experience - **min_yieldse** (float) - Optional - Minimum annualized yield percentage - **max_current_fund_count** (integer) - Optional - Maximum number of funds managed - **min_scale** (float) - Optional - Minimum management scale in billions - **fund_type** (string) - Optional - Category of funds managed ### Response #### Success Response (200) - **Managers** (array) - List of manager objects - **Pagination** (object) - Pagination metadata #### Response Example { "Managers": [{ "Name": "John Doe", "WorkingYears": 10, "Score": 85, "CurrentBestReturn": 15.5 }], "Pagination": { "PageNum": 1, "PagesCount": 5 } } ``` -------------------------------- ### Execute Backtest Strategy Source: https://github.com/ufund-me/qbot/blob/main/docs/notebook/Pairs_Trading.ipynb Example usage of the Multidata_Strategy_runner to instantiate and run a trading strategy, followed by plotting the results. ```python strategy_runner = Multidata_Strategy_runner(strategy=PairTradingStrategy, ts_code=bank_choose[0], ts_code1=bank_choose[1], start_date=start_date, end_date=end_date, pro=True) cerebro, strat = strategy_runner.run() strategy_runner.plot() ``` -------------------------------- ### Restart Tonghuashun Client (HTTP API) Source: https://github.com/ufund-me/qbot/blob/main/qbot/engine/trade/trading/thsauto/README.md Restarts the Tonghuashun client application. This is a GET request to the specified API endpoint. ```http http://192.168.0.116:5000/thsauto/client/restart ``` -------------------------------- ### Initialize Pyecharts Online Mode Source: https://github.com/ufund-me/qbot/blob/main/pyfunds/backtest/doc/samples/schedulestudy.ipynb Initializes the pyecharts library for online rendering. This is a setup step and typically only needs to be run once. ```python import sys sys.path.insert(0, "../../") from pyecharts import online online() # 演示必要的准备代码,使用该库时不需重复此单元格命令 ``` -------------------------------- ### Configure Incremental IO with SQL Backend Source: https://github.com/ufund-me/qbot/blob/main/pyfunds/backtest/doc/samples/info.ipynb Demonstrates how to use a SQLAlchemy engine as a backend for incremental IO. This allows fund data to be stored and retrieved from a relational database instead of local files. ```python from sqlalchemy import create_engine engine = create_engine("mysql://user:pass@host/db_name?charset=utf8") sqlconf = {"save": True, "fetch": True, "path": engine, "form": "sql"} zzhli = xa.indexinfo("1399922", **sqlconf) ``` -------------------------------- ### Executing Fund Estimation Analysis Source: https://github.com/ufund-me/qbot/blob/main/pyfunds/backtest/doc/samples/netvalueestimation.ipynb Example usage of the estimation functions to generate a comparative dataframe for various fund holdings. ```python cache_table = {} cache_data(cache_table, holdings_160216_19s4, holdings_162411_19s4, holdings_501018_19s3, holdings_501018_19s4, holdings_501018_bc_cash, ["F501018", "USD/CNY", "2111", "F160216", "F162411"]) nfyydf = estimate_table("20190101", "20200305", ("real", "", {"F501018": 100}), ("fund_est", "USD/CNY", holdings_501018_19s4), ("fund_est_2111", "2111", holdings_501018_19s4), ("bc_est", "USD/CNY", holdings_501018_bc_cash), ("bc_est_2111", "2111", holdings_501018_bc_cash), _default=cache_table) nfyydf.iloc[-20:] ``` -------------------------------- ### Multi-User and Multi-Strategy Following Source: https://github.com/ufund-me/qbot/blob/main/qbot/engine/trade/easytrader/docs/usage.md This section demonstrates how to follow multiple strategies for multiple users simultaneously, specifying the total assets for each user. ```APIDOC ## POST /ufund-me/qbot/multi-follow ### Description Follow multiple strategies for multiple users concurrently. This endpoint allows specifying lists of users, strategies, and their corresponding total asset values. ### Method POST ### Endpoint /ufund-me/qbot/multi-follow ### Parameters #### Request Body - **users** (array of strings) - Required - A list of user identifiers. - **strategies** (array of strings) - Required - A list of strategy identifiers, corresponding to the users. - **total_assets** (array of numbers) - Required - A list of total asset values, corresponding to the users and strategies. ### Request Example ```json { "users": ["user1_id", "user2_id"], "strategies": ["strategyA", "strategyB"], "total_assets": [50000, 75000] } ``` ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating that multiple strategies are being followed. #### Response Example ```json { "message": "Successfully started following multiple strategies for multiple users." } ``` ``` -------------------------------- ### Set Benchmark for SSE 50 Index (Extended) Source: https://github.com/ufund-me/qbot/blob/main/pyfunds/backtest/doc/samples/schedulestudy.ipynb Sets the cash information as a benchmark for the SSE 50 index, starting from '2011-01-01'. ```python sz50.bcmkset(xa.cashinfo(), start="2011-01-01") ``` -------------------------------- ### Initialize Python Data Structures Source: https://github.com/ufund-me/qbot/blob/main/docs/notebook/pandas.ipynb Demonstrates the syntax for creating lists, dictionaries, and tuples in Python. It highlights the mutability of lists and dictionaries versus the immutability of tuples. ```python is_list = ['a', 1, False, 1.0] is_dict = {'a': 1, 1: 'b'} is_tuple = (1, 2, 1, 'a') ``` -------------------------------- ### Command Line Interface (CLI) - Get Information Source: https://github.com/ufund-me/qbot/blob/main/qbot/engine/trade/easytrader/docs/usage.md This section explains how to retrieve account information such as balance and holdings using the CLI. ```APIDOC ## CLI Get Information ### Description Retrieve various account information using the command line interface. This includes fetching account balances, current holdings, and other relevant variables. ### Command ```bash python cli.py --get ``` ### Parameters #### Command Line Arguments - **--get** (string) - Required - The type of information to retrieve (e.g., 'balance', 'positions'). ### Example ```bash python cli.py --get balance ``` ### Response - The command will output the requested information directly to the console. ``` -------------------------------- ### Get Intraday Bar Data Source: https://github.com/ufund-me/qbot/blob/main/pyfunds/backtest/doc/source/quickstart.md Retrieves intraday bar data (minute, 5-minute, hourly, weekly) for a specified financial instrument. ```APIDOC ## GET /api/data/bar ### Description Fetches intraday bar data for a specified financial instrument at a given interval. ### Method GET ### Endpoint /api/data/bar ### Parameters #### Query Parameters - **code** (string) - Required - The unique identifier for the financial instrument (e.g., "LK", "commodities/brent-oil"). - **interval** (integer) - Required - The interval for the bar data in seconds (e.g., 60 for minute, 3600 for hourly). - **prev** (integer) - Optional - The number of previous bars to retrieve. - **start** (string) - Optional - The start date/time for the data. - **end** (string) - Optional - The end date/time for the data. ### Request Example ```python import xalpha as xa # Get hourly data for a US stock data_hourly = xa.get_bar("LK", interval=3600, prev=12) print(data_hourly) # Get minute data for Brent oil data_minute = xa.get_bar("commodities/brent-oil", interval=60) print(data_minute) ``` ### Response #### Success Response (200) - **DataFrame** - A pandas DataFrame containing the intraday bar data with columns like 'date', 'open', 'high', 'low', 'close', 'volume', etc. #### Response Example ``` date open high low close volume turnoverrate percent 0 2020-04-03 00:30:00 7.3001 7.60 6.71 7.0497 30253047 12.58 -3.23 1 2020-04-03 01:30:00 7.0500 7.20 6.51 6.5450 17016394 7.09 -7.16 ... (more data) ``` ``` -------------------------------- ### Direct Binance and CCXT Trading Source: https://context7.com/ufund-me/qbot/llms.txt Demonstrates how to place market and limit orders on Binance directly and how to use the CCXT unified interface for multi-exchange trading, including fetching positions and executing trades based on signals. ```python binance.order_market_buy(symbol="BTCUSDT", quantity=0.001) binance.order_limit_sell(symbol="BTCUSDT", quantity=0.001, price="50000") ``` ```python ccxt_account = { "apikey": "your_api_key", "secretkey": "your_secret_key" } ccxt_opts = {"platform": "币安Binance", "strategy": "macd"} ccxt_engine = CcxtTradeEngine(ccxt_account, ccxt_opts) position = ccxt_engine.get_positions("BTC") ccxt_engine.execute_trade(signal="buy", symbol="BTC/USDT", amount=0.001) import pandas as pd df = pd.DataFrame({"macd": [-0.1, 0.05, 0.1]}) # 示例数据 signal = ccxt_engine.check_trade_signals(df) ``` -------------------------------- ### Kill Tonghuashun Client (HTTP API) Source: https://github.com/ufund-me/qbot/blob/main/qbot/engine/trade/trading/thsauto/README.md Forcefully closes the Tonghuashun client application. This is a GET request to the specified API endpoint. ```http http://192.168.0.116:5000/thsauto/client/kill ``` -------------------------------- ### Qbot CLI Login Source: https://github.com/ufund-me/qbot/blob/main/qbot/engine/trade/easytrader/docs/usage.md This command logs into the Qbot system using the specified trading client (e.g., 'yh') and prepares configuration from a JSON file. Upon successful login, an `account.session` file is generated to store the user object. ```bash python cli.py --use yh --prepare gf.json ``` -------------------------------- ### Query Filled Orders (HTTP API) Source: https://github.com/ufund-me/qbot/blob/main/qbot/engine/trade/trading/thsauto/README.md Retrieves a list of orders that have been successfully filled. This is a GET request to the specified API endpoint. ```http http://192.168.0.116:5000/thsauto/orders/filled ``` -------------------------------- ### Initialize Database Engines and Load SQL Data Source: https://github.com/ufund-me/qbot/blob/main/docs/notebook/新闻分析.ipynb This snippet uses a custom setting module to initialize database engines for stock and news databases. It then reads the 'tb_cnstock' table from both sources into pandas DataFrames. ```python from setting import get_engine import pandas as pd first = get_engine('db_stock') df = pd.read_sql('tb_cnstock', first) second = get_engine('db_news') df2 = pd.read_sql('tb_cnstock', second) ``` -------------------------------- ### Configure Backtesting Parameters in Backtrader Source: https://github.com/ufund-me/qbot/blob/main/docs/README.md This snippet demonstrates how to initialize a backtesting environment using the Backtrader framework, including setting the asset symbol, time range, and broker commission rates. ```python symbol = "华正新材(603186)" Starting_Portfolio_Value = 10000.00 Startdate = datetime.datetime(2010, 1, 1) Enddate = datetime.datetime(2020, 4, 21) # 设置佣金为0.001, 除以100去掉%号 cerebro.broker.setcommission(commission=0.001) ``` -------------------------------- ### Fix ImportError for Matplotlib in Backtrader Source: https://github.com/ufund-me/qbot/blob/main/docs/tutorials_code/README.md Resolves the 'ImportError: cannot import name warnings' error by installing a specific compatible version of the matplotlib library. ```bash pip install matplotlib==3.2.2 ``` -------------------------------- ### Fund Trading and Backtesting with xalpha Source: https://context7.com/ufund-me/qbot/llms.txt Explains how to manage fund trading records and perform backtesting analysis using the xalpha library. It covers creating trade records, simulating operations like subscriptions and redemptions, and calculating performance metrics. ```python from xalpha import trade, itrade from xalpha.record import record import pandas as pd from xalpha.info import fundinfo status = pd.DataFrame({ 'date': pd.to_datetime(['2023-01-05', '2023-02-10', '2023-03-15']), '000001': [1000, 500, -200] # 正数为买入金额,负数为卖出份额 }) fund = fundinfo("000001") # 华夏成长基金 t = trade(fund, status) print(t.cftable) report = t.dailyreport() xirr_rate = t.xirrrate() print(f"年化收益率: {xirr_rate:.2%}") unit_cost = t.unitcost() print(f"单位成本: {unit_cost:.4f}") t.v_tradevolume(freq="M") t.v_tradecost() it = itrade("SH510300", status) it_report = it.dailyreport() ``` -------------------------------- ### Build Docker Image for Fund Strategy Source: https://github.com/ufund-me/qbot/blob/main/pyfunds/fund-strategies/README.md Builds a Docker image for the fund strategy application. This command should be run from the project's root directory. ```bash docker build -t fund_strategy . ``` -------------------------------- ### Trading Operations Source: https://github.com/ufund-me/qbot/blob/main/qbot/engine/trade/easytrader/docs/usage.md This section details various trading functions, including getting account balance, positions, placing orders, and canceling orders. ```APIDOC ## Trading Operations ### 1. Get Account Balance ```python user.balance ``` **Return Example:** ```json [{'reference_market_value': 21642.0, 'available_funds': 28494.21, 'currency': '0', 'total_assets': 50136.21, 'stock_reference_profit_loss': -90.21, 'fund_balance': 28494.21, 'fund_account': 'xxx'}] ``` ### 2. Get Positions ```python user.position ``` **Return Example:** ```json [{'buy_frozen': 0, 'trading_market': '沪A', 'sell_frozen': '0', 'reference_market_price': 4.71, 'reference_market_value': 10362.0, 'reference_cost_price': 4.672, 'reference_profit_loss': 82.79, 'current_holdings': 2200, 'profit_loss_percentage': '0.81%', 'shareholder_code': 'xxx', 'stock_balance': 2200, 'stock_available': 2200, 'security_code': '601398', 'security_name': '工商银行'}] ``` ### 3. Buy Order ```python user.buy('162411', price=0.55, amount=100) ``` **Return Example:** ```json {'entrust_no': 'xxxxxxxx'} ``` Note: System can be configured to return trade confirmations. If not configured, the default return is `{"message": "success"}`. ### 4. Sell Order ```python user.sell('162411', price=0.55, amount=100) ``` **Return Example:** ```json {'entrust_no': 'xxxxxxxx'} ``` ### 5. One-Click IPO Subscription ```python user.auto_ipo() ``` ### 6. Cancel Order ```python user.cancel_entrust('entrust_no obtained from buy/sell') ``` **Return Example:** ```json {'message': 'Order cancellation successful'} ``` ### 7. Query Today's Trades ```python user.today_trades ``` **Return Example:** ```json [{'buy_sell_flag': 'Buy', 'trading_market': '深A', 'entrust_seq': '12345', 'trade_price': 0.626, 'trade_amount': 100, 'trade_date': '20170313', 'trade_time': '09:50:30', 'trade_amount_total': 62.60, 'shareholder_code': 'xxx', 'security_code': '162411', 'security_name': '华宝油气'}] ``` ### 8. Query Today's Entrusts ```python user.today_entrusts ``` **Return Example:** ```json [{'buy_sell_flag': 'Buy', 'trading_market': '深A', 'entrust_price': 0.627, 'entrust_seq': '111111', 'entrust_amount': 100, 'entrust_date': '20170313', 'entrust_time': '09:50:30', 'trade_amount': 100, 'cancel_amount': 0, 'status_description': 'Filled', 'shareholder_code': 'xxxxx', 'security_code': '162411', 'security_name': '华宝油气'}, {'buy_sell_flag': 'Buy', 'trading_market': '深A', 'entrust_price': 0.6, 'entrust_seq': '1111', 'entrust_amount': 100, 'entrust_date': '20170313', 'entrust_time': '09:40:30', 'trade_amount': 0, 'cancel_amount': 100, 'status_description': 'Cancelled', 'shareholder_code': 'xxx', 'security_code': '162411', 'security_name': '华宝油气'}] ``` ### 9. Query Today's IPO Subscription Data ```python from easytrader.utils.stock import get_today_ipo_data ipo_data = get_today_ipo_data() print(ipo_data) ``` **Return Example:** ```json [{'stock_code': 'stock_code', 'stock_name': 'stock_name', 'price': issue_price, 'apply_code': 'apply_code'}] ``` ### 10. Refresh Data ```python user.refresh() ``` ### 11. Xueqiu Portfolio Weight Adjustment ```python user.adjust_weight('stock_code', target_weight) ``` Example: `user.adjust_weight('000001', 10)` adjusts the holding weight of Ping An Bank to 10% in the portfolio. ``` -------------------------------- ### Cancel Order (HTTP API) Source: https://github.com/ufund-me/qbot/blob/main/qbot/engine/trade/trading/thsauto/README.md Cancels a previously placed order using its entrustment number. This is a GET request to the specified API endpoint. ```http http://192.168.0.116:5000/thsauto/cancel?entrust_no=2060704404 ```