### Installing abupy Python Package via pip Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/0-abupy量化环境部署(ABU量化使用文档).ipynb This command uses the pip package installer to download and install the `abupy` library from PyPI. Note that the documentation recommends cloning the GitHub repository instead for access to examples and tutorials. ```Shell pip install abupy ``` -------------------------------- ### Initializing Abu Environment and Imports (Python) Source: https://github.com/bbfamily/abu/blob/master/ipython/附录A-量化环境部署.ipynb Imports essential libraries (numpy, pandas, seaborn, matplotlib) for data analysis and plotting, configures plotting style, and sets up the `abupy` environment by adjusting the Python path to prioritize local installation and disabling the initial example data. ```python from __future__ import print_function from __future__ import division import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline sns.set_context(rc={'figure.figsize': (14, 7) } ) figzize_me = figsize =(14, 7) # import warnings; warnings.filterwarnings('ignore') import os import sys # 使用insert 0即只使用github,避免交叉使用了pip安装的abupy,导致的版本不一致问题 sys.path.insert(0, os.path.abspath('../')) import abupy # 本章不使用沙盒数据 abupy.env.disable_example_env_ipython() ``` -------------------------------- ### Running Backtest on US Stocks (Python) Source: https://github.com/bbfamily/abu/blob/master/ipython/附录A-量化环境部署.ipynb Defines a list of US stock symbols for backtesting. Temporarily enables the `abupy` example environment and runs a backtest simulation using `abu.run_loop_back` with the configured factors and US symbols over 2 folds. Stores the results in `abu_result_tuple` for subsequent analysis. ```python # 择时股票池 choice_symbols = ['usNOAH', 'usSFUN', 'usBIDU', 'usAAPL', 'usGOOG', 'usTSLA', 'usWUBA', 'usVIPS'] # 使用run_loop_back运行策略 abupy.env.enable_example_env_ipython() abu_result_tuple, _ = abu.run_loop_back(read_cash, buy_factors, sell_factors, stock_pickers, choice_symbols=choice_symbols, n_folds=2) abupy.env.disable_example_env_ipython() ``` -------------------------------- ### Analyzing A-Share Backtest Metrics and Plotting (Python) Source: https://github.com/bbfamily/abu/blob/master/ipython/附录A-量化环境部署.ipynb Initializes the `AbuMetricsBase` class with the results (`abu_result_tuple`) from the A-share backtest simulation. It computes the performance metrics using `fit_metrics()` and visualizes the return comparison with a benchmark using `plot_returns_cmp()`, showing the results for the A-share strategy run. ```python from abupy import AbuMetricsBase metrics = AbuMetricsBase(*abu_result_tuple) metrics.fit_metrics() metrics.plot_returns_cmp() ``` -------------------------------- ### Analyzing Backtest Metrics and Plotting Returns (Python) Source: https://github.com/bbfamily/abu/blob/master/ipython/附录A-量化环境部署.ipynb Initializes the `AbuMetricsBase` class with the results (`abu_result_tuple`) from a backtest simulation. It then computes key performance metrics using `fit_metrics()` and generates a plot comparing the strategy's returns to a benchmark using `plot_returns_cmp()`, visualizing the strategy's performance. ```python from abupy import AbuMetricsBase metrics = AbuMetricsBase(*abu_result_tuple) metrics.fit_metrics() metrics.plot_returns_cmp() ``` -------------------------------- ### Fetching Stock Data with ABuSymbolPd (Python) Source: https://github.com/bbfamily/abu/blob/master/ipython/附录A-量化环境部署.ipynb Demonstrates how to use `ABuSymbolPd.make_kl_df` to fetch historical KL data for a specific stock symbol ('601398') and displays the last few rows using `.tail()`. This shows basic data retrieval functionality from the configured source. ```python from abupy import ABuSymbolPd # 表A-1所示 ABuSymbolPd.make_kl_df('601398').tail() ``` -------------------------------- ### Installing Anaconda on macOS via Bash Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/0-abupy量化环境部署(ABU量化使用文档).ipynb This command executes the downloaded Anaconda installer script (`.sh` file) using the bash shell. It is recommended for macOS users to install Anaconda from the command line rather than the graphical installer. ```Shell bash ~/Downloads/Anaconda2-4.2.0-MacOSX-x86_64.sh ``` -------------------------------- ### Setting Market Data Source to Tencent (Python) Source: https://github.com/bbfamily/abu/blob/master/ipython/附录A-量化环境部署.ipynb Changes the global market data source setting in the `abupy` environment to Tencent (`EMarketSourceType.E_MARKET_SOURCE_tx`), preparing the system to fetch data specifically from this source for subsequent operations, particularly useful for A-share data. ```python from abupy import EMarketSourceType abupy.env.g_market_source = EMarketSourceType.E_MARKET_SOURCE_tx ``` -------------------------------- ### Running Backtest on A-Share Stocks from Network (Python) Source: https://github.com/bbfamily/abu/blob/master/ipython/附录A-量化环境部署.ipynb Switches the global `abupy` data fetch mode to explicitly use network data (`EMarketDataFetchMode.E_DATA_FETCH_FORCE_NET`). Defines a list of Chinese A-share symbols and runs a backtest simulation using `abu.run_loop_back` with the previously defined factors, but on the new set of A-share symbols fetched from the network source. ```python # 强制走网络数据源 abupy.env.g_data_fetch_mode = EMarketDataFetchMode.E_DATA_FETCH_FORCE_NET # 择时股票池 choice_symbols = ['601398', '600028', '601857', '601318', '600036', '000002', '600050', '600030'] # 使用run_loop_back运行策略 abu_result_tuple, _ = abu.run_loop_back(read_cash, buy_factors, sell_factors, stock_pickers, choice_symbols=choice_symbols, n_folds=2) ``` -------------------------------- ### Configuring Data Fetch Mode and Trading Factors (Python) Source: https://github.com/bbfamily/abu/blob/master/ipython/附录A-量化环境部署.ipynb Sets the global `abupy` data fetch mode to prioritize local cache using `EMarketDataFetchMode.E_DATA_FETCH_FORCE_LOCAL`. Defines trading strategy components: initial cash, stock pickers (none), and lists of buy and sell factors with their parameters and corresponding `abupy` class references like `AbuFactorBuyBreak` and various `AbuFactorAtrNStop` types. ```python from abupy import EMarketDataFetchMode, abu # 强制使用本地缓存数据 abupy.env.g_data_fetch_mode = \ EMarketDataFetchMode.E_DATA_FETCH_FORCE_LOCAL from abupy import AbuFactorBuyBreak from abupy import AbuFactorAtrNStop from abupy import AbuFactorPreAtrNStop from abupy import AbuFactorCloseAtrNStop # 设置初始资金数 read_cash = 1000000 # 设置选股因子,None为不使用选股因子 stock_pickers = None # 买入因子依然延用向上突破因子 buy_factors = [{'xd': 60, 'class': AbuFactorBuyBreak}, {'xd': 42, 'class': AbuFactorBuyBreak}] # 卖出因子继续使用上一章使用的因子 sell_factors = [ {'stop_loss_n': 1.0, 'stop_win_n': 3.0, 'class': AbuFactorAtrNStop}, {'class': AbuFactorPreAtrNStop, 'pre_atr_n': 1.5}, {'class': AbuFactorCloseAtrNStop, 'close_atr_n': 1.5} ] ``` -------------------------------- ### Verifying AbuPy Installation - Python Source: https://github.com/bbfamily/abu/blob/master/readme-en.md This code snippet is used to test if the abupy library has been correctly installed in the Python environment. Successfully running this import statement without errors confirms that the library is accessible. ```Python import abupy ``` -------------------------------- ### Importing Abupy and Dependencies - Python Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/4-多支股票择时回测与仓位管理(ABU量化使用文档).ipynb Imports core libraries like numpy, pandas, and matplotlib, along with required modules from abupy. It sets up the environment for running abupy examples by modifying the system path and enabling the example data environment for consistency with the book. ```python from __future__ import print_function from __future__ import division import warnings warnings.filterwarnings('ignore') warnings.simplefilter('ignore') import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import os import sys # 使用insert 0即只使用github,避免交叉使用了pip安装的abupy,导致的版本不一致问题 sys.path.insert(0, os.path.abspath('../')) import abupy # 使用沙盒数据,目的是和书中一样的数据环境 abupy.env.enable_example_env_ipython() ``` -------------------------------- ### Importing Libraries and Initializing abupy Environment (Python) Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/32-策略有效性的验证.ipynb Imports standard Python libraries (numpy, pandas, matplotlib, os, sys) and sets up the abupy environment. It specifically adds the parent directory to the sys.path to ensure the GitHub version of abupy is used and enables the abupy example environment for initial demonstrations. ```python # 基础库导入 from __future__ import print_function from __future__ import division import warnings warnings.filterwarnings('ignore') warnings.simplefilter('ignore') import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import os import sys # 使用insert 0即只使用github,避免交叉使用了pip安装的abupy,导致的版本不一致问题 sys.path.insert(0, os.path.abspath('../')) import abupy # 开始的示例先使用沙盒数据,之后的示例需要下载缓存 abupy.env.enable_example_env_ipython() ``` -------------------------------- ### Importing Core Libraries and ABuQuant Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/29-多因子策略并行执行配合.ipynb Imports standard Python libraries like numpy, pandas, and matplotlib, sets up warnings, and imports the abupy library, configuring the system to use the example environment for reproducible results. ```python # 基础库导入 from __future__ import print_function from __future__ import division import warnings warnings.filterwarnings('ignore') warnings.simplefilter('ignore') import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import os import sys # 使用insert 0即只使用github,避免交叉使用了pip安装的abupy,导致的版本不一致问题 sys.path.insert(0, os.path.abspath('../')) import abupy # 使用沙盒数据,目的是和书中一样的数据环境 abupy.env.enable_example_env_ipython() ``` -------------------------------- ### Launching Quantitative Tool UI - Python Source: https://github.com/bbfamily/abu/blob/master/abupy_ui/量化分析工具操作.ipynb This Python snippet uses the `%matplotlib inline` magic command to ensure plots are displayed inline in environments like Jupyter notebooks, imports the `widget_quant_tool` library, and then calls the `show_ui()` function to launch the graphical user interface for the quantitative trading tool. It requires the `widget_quant_tool` library to be installed. ```python %matplotlib inline import widget_quant_tool widget_quant_tool.show_ui() ``` -------------------------------- ### Importing Libraries and Setting Up ABU Environment (Python) Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/15-量化交易和搜索引擎(ABU量化使用文档).ipynb Imports necessary Python libraries including standard data science libraries (numpy, pandas, matplotlib) and system libraries (os, sys), along with the core abupy library. It modifies the system path to prioritize the local abupy source and enables the abupy sandbox environment for reproducible examples using built-in data. ```python # 基础库导入 from __future__ import print_function from __future__ import division import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import os import sys # 使用insert 0即只使用github,避免交叉使用了pip安装的abupy,导致的版本不一致问题 sys.path.insert(0, os.path.abspath('../')) import abupy # 使用沙盒数据,目的是和书中一样的数据环境 abupy.env.enable_example_env_ipython() ``` -------------------------------- ### Importing Core Libraries and Setting Environment - abupy Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/9-港股市场的回测(ABU量化使用文档).ipynb Imports fundamental Python libraries for numerical operations, data manipulation, plotting, and system interaction. It also specifically imports the `abupy` library and configures its environment to use example data suitable for demonstration purposes within an IPython notebook. ```python # 基础库导入 from __future__ import print_function from __future__ import division import warnings warnings.filterwarnings('ignore') warnings.simplefilter('ignore') import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import os import sys # 使用insert 0即只使用github,避免交叉使用了pip安装的abupy,导致的版本不一致问题 sys.path.insert(0, os.path.abspath('../')) import abupy # 使用沙盒数据,目的是和书中一样的数据环境 abupy.env.enable_example_env_ipython() ``` -------------------------------- ### Importing Core Libraries and Configuring Environment Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/31-资金仓位管理与买入策略的搭配.ipynb This snippet imports fundamental Python libraries for numerical operations (numpy), data manipulation (pandas), plotting (matplotlib), and system/file path operations (os, sys). It also configures warnings, sets matplotlib to display plots inline, adjusts the system path to prioritize the local abupy repository, and enables the example data environment for consistent backtesting results. ```python # 基础库导入 from __future__ import print_function from __future__ import division import warnings warnings.filterwarnings('ignore') warnings.simplefilter('ignore') import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import os import sys # 使用insert 0即只使用github,避免交叉使用了pip安装的abupy,导致的版本不一致问题 sys.path.insert(0, os.path.abspath('../')) import abupy # 使用沙盒数据,目的是和书中一样的数据环境 abupy.env.enable_example_env_ipython() ``` -------------------------------- ### Defining Trading Factors and Initializing Capital - Python Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/4-多支股票择时回测与仓位管理(ABU量化使用文档).ipynb Configures the trading strategy by defining two buy factors (60-day and 42-day upward breaks) and a combination of four sell factors (break, ATR-based stops) that will be active simultaneously. It also initializes the benchmark index and the starting capital for the backtesting simulation. ```python from abupy import AbuFactorBuyBreak, AbuFactorSellBreak, AbuPositionBase from abupy import AbuFactorAtrNStop, AbuFactorPreAtrNStop, AbuFactorCloseAtrNStop from abupy import ABuPickTimeExecute, AbuBenchmark, AbuCapital # buy_factors 60日向上突破,42日向上突破两个因子 buy_factors = [{'xd': 60, 'class': AbuFactorBuyBreak}, {'xd': 42, 'class': AbuFactorBuyBreak}] # 四个卖出因子同时并行生效 sell_factors = [ { 'xd': 120, 'class': AbuFactorSellBreak }, { 'stop_loss_n': 0.5, 'stop_win_n': 3.0, 'class': AbuFactorAtrNStop }, { 'class': AbuFactorPreAtrNStop, 'pre_atr_n': 1.0 }, { 'class': AbuFactorCloseAtrNStop, 'close_atr_n': 1.5 }] benchmark = AbuBenchmark() capital = AbuCapital(1000000, benchmark) ``` -------------------------------- ### Importing Core ABU Libraries Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/17-UMP边裁交易决策(ABU量化使用文档).ipynb This snippet imports essential Python libraries including numpy, pandas, matplotlib, os, and sys for data handling, plotting, and system path manipulation. It also imports the main 'abupy' library and enables the example environment for consistent data. ```python from __future__ import print_function from __future__ import division import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import os import sys # 使用insert 0即只使用github,避免交叉使用了pip安装的abupy,导致的版本不一致问题 sys.path.insert(0, os.path.abspath('../')) import abupy # 使用沙盒数据,目的是和书中一样的数据环境 abupy.env.enable_example_env_ipython() ``` -------------------------------- ### Importing Core ABu and Utility Libraries - Python Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/23-美股UMP决策(ABU量化使用文档).ipynb This snippet imports fundamental Python libraries and core ABu Quant System modules required for quantitative analysis and backtesting. It includes standard libraries like numpy, pandas, matplotlib, as well as ipywidgets for interactive elements. It also adds the parent directory to the Python path to ensure the local abupy source is used and enables the example environment for consistent data. ```python # 基础库导入 from __future__ import print_function from __future__ import division import warnings warnings.filterwarnings('ignore') warnings.simplefilter('ignore') import numpy as np import pandas as pd import matplotlib.pyplot as plt import ipywidgets %matplotlib inline import os import sys # 使用insert 0即只使用github,避免交叉使用了pip安装的abupy,导致的版本不一致问题 sys.path.insert(0, os.path.abspath('../')) import abupy # 使用沙盒数据,目的是和书中一样的数据环境 abupy.env.enable_example_env_ipython() ``` -------------------------------- ### Displaying Sample Buy-Time ML Features from Orders (Python) Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/15-量化交易和搜索引擎(ABU量化使用文档).ipynb Filters the `orders_pd_train` DataFrame to select columns that start with 'buy', representing features captured at the time of a buy signal. It explicitly drops standard non-feature columns like date, price, count, and factor details to focus on the generated machine learning features and displays the first few rows of this filtered data. ```python orders_pd_train.filter(regex='buy*').drop( ['buy_date', 'buy_price', 'buy_cnt', 'buy_factor', 'buy_pos', 'buy_type_str'], axis=1).head() ``` -------------------------------- ### Defining Stock Symbols for Backtesting - Python Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/4-多支股票择时回测与仓位管理(ABU量化使用文档).ipynb Creates a list of specific US stock symbols (`usTSLA`, `usNOAH`, `usSFUN`, `usBIDU`, `usAAPL`, `usGOOG`, `usWUBA`, `usVIPS`) that will be used as the target assets for the multi-stock backtesting examples in this section, representing the output of a hypothetical stock selection module. ```python # 我们假定choice_symbols是我们选股模块的结果, choice_symbols = ['usTSLA', 'usNOAH', 'usSFUN', 'usBIDU', 'usAAPL', 'usGOOG', 'usWUBA', 'usVIPS'] ``` -------------------------------- ### Performing Cross Validation with AbuCrossVal (Python) Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/32-策略有效性的验证.ipynb Disables the abupy example environment to use local data, then defines specific buy and sell factor parameters (derived from a presumed Grid Search result). It initializes the AbuCrossVal class and runs the fit method, which performs the cross-validation process by grouping symbols based on correlation and running multiple backtests with the specified factors across these groups (cv=10 indicates 10 folds or iterations). ```python # 交叉相关性策略验证只支持本地非沙盒数据模式 abupy.env.disable_example_env_ipython() # 使用上面grid search结果的top1参数组合进行验证 buy_factors = [{'class': AbuDownUpTrend, 'down_deg_threshold': -2, 'past_factor': 5, 'xd': 20}] sell_factors = [{'stop_loss_n': 1, 'stop_win_n': 0.5, 'class': AbuFactorAtrNStop}, {'class': AbuFactorPreAtrNStop, 'pre_atr_n': 1.5}, {'class': AbuFactorCloseAtrNStop, 'close_atr_n': 1.5}] cross_val = AbuCrossVal() cross_val.fit(buy_factors, sell_factors, cv=10) ``` -------------------------------- ### Defining Hong Kong Stock Symbols for Backtesting - abupy Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/9-港股市场的回测(ABU量化使用文档).ipynb Defines a Python list containing the stock symbols (with 'hk' prefix for Hong Kong) that will constitute the selection pool for the backtesting simulation in this example. ```python # 择时股票池 choice_symbols = ['hk03333', 'hk00700', 'hk02333', 'hk01359', 'hk00656', 'hk03888', 'hk02318'] ``` -------------------------------- ### Analyzing Sell Factor Usage Per Buy Factor (Default) Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/29-多因子策略并行执行配合.ipynb Groups the backtest results by the buy factor that initiated the trade and counts which sell factor (`sell_type_extra`) was responsible for closing the trade. This demonstrates that in the default setup, `AbuFactorSellNDay` was used for all trades. ```python abu_result_tuple.orders_pd.groupby('buy_factor')['sell_type_extra'].value_counts() ``` -------------------------------- ### Displaying First 10 Backtest Actions - Python Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/4-多支股票择时回测与仓位管理(ABU量化使用文档).ipynb Presents the beginning entries of the `action_pd` DataFrame, which logs various actions and events during the backtest, including signals and whether the resulting trades (`deal` column) were successfully executed based on internal logic like position management. ```python action_pd[:10] ``` -------------------------------- ### Configuring Backtesting Parameters and Factors (Python) Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/15-量化交易和搜索引擎(ABU量化使用文档).ipynb Sets the initial capital for the backtest (`read_cash`). Defines the buy side of the trading strategy using two instances of `AbuFactorBuyBreak` with different lookback periods (60 and 42). Configures the sell side using three different ATR-based stop-loss and stop-win factor implementations. ```python # 设置初始资金数 read_cash = 1000000 # 买入因子依然延用向上突破因子 buy_factors = [{'xd': 60, 'class': AbuFactorBuyBreak}, {'xd': 42, 'class': AbuFactorBuyBreak}] # 卖出因子继续使用上一节使用的因子 sell_factors = [ {'stop_loss_n': 1.0, 'stop_win_n': 3.0, 'class': AbuFactorAtrNStop}, {'class': AbuFactorPreAtrNStop, 'pre_atr_n': 1.5}, {'class': AbuFactorCloseAtrNStop, 'close_atr_n': 1.5} ] ``` -------------------------------- ### Displaying General Backtest Metrics (Python) Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/15-量化交易和搜索引擎(ABU量化使用文档).ipynb Uses the `AbuMetricsBase.show_general` function to display summarized performance metrics for the training backtest results. The `returns_cmp=True` parameter specifies that metrics are calculated based on trade returns, and `only_info=True` limits the output to summary information without comparison to a benchmark index. ```python AbuMetricsBase.show_general(*abu_result_tuple_train, returns_cmp=True, only_info=True) ``` -------------------------------- ### Running ABuQuant Backtest (Initial Configuration) Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/29-多因子策略并行执行配合.ipynb Defines a helper function `run_loo_back` to execute a backtest using the specified buy and sell factors and a list of US stocks. It sets the market target, runs the backtest loop, cleans up progress output, and displays general metrics. ```python # 使用沙盒內的美股做为回测目标 us_choice_symbols = ['usTSLA', 'usNOAH', 'usSFUN', 'usBIDU', 'usAAPL', 'usGOOG', 'usWUBA', 'usVIPS'] # 初始资金量 cash = 3000000 def run_loo_back(choice_symbols, ps=None, n_folds=2, start=None, end=None, only_info=False): """封装一个回测函数,返回回测结果,以及回测度量对象""" if choice_symbols[0].startswith('us'): abupy.env.g_market_target = EMarketTargetType.E_MARKET_TARGET_US else: abupy.env.g_market_target = EMarketTargetType.E_MARKET_TARGET_CN abu_result_tuple, _ = abu.run_loop_back(cash, buy_factors, sell_factors, ps, start=start, end=end, n_folds=n_folds, choice_symbols=choice_symbols) """ 这里把所有因子的唯一名称只取类名,不要参数了: eg:AbuDoubleMaBuy:fast=5,slow=60->AbuDoubleMaBuy """ abu_result_tuple.orders_pd['buy_factor'] = abu_result_tuple.orders_pd[ 'buy_factor'].apply(lambda bf: bf.split(':')[0]) ABuProgress.clear_output() metrics = AbuMetricsBase.show_general(*abu_result_tuple, returns_cmp=only_info, only_info=only_info, only_show_returns=True) return abu_result_tuple, metrics abu_result_tuple, metrics = run_loo_back(us_choice_symbols) ``` -------------------------------- ### Displaying General Backtest Returns - abupy Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/9-港股市场的回测(ABU量化使用文档).ipynb Calls the `show_general` method from `AbuMetricsBase` to display key performance metrics of the completed backtest simulation. The `only_show_returns=True` parameter limits the output to only show the return-related metrics. ```python AbuMetricsBase.show_general(*abu_result_tuple, only_show_returns=True) ``` -------------------------------- ### Performing Cross Validation with Constrained Top Parameters (Python) Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/32-策略有效性的验证.ipynb Defines specific buy and sell factor parameters obtained from a constrained Grid Search (where stop_win_n was fixed at 3.0), disabling the example environment to use local data. It initializes the AbuCrossVal class and runs the fit method with these factors and cv=10, performing cross-validation to validate the strategy's robustness across different symbol groups under these specific parameter constraints. ```python # grid search结果的带参数限制条件的top1参数 buy_factors = [{'class': AbuDownUpTrend, 'down_deg_threshold': -3, 'past_factor': 4, 'xd': 20}] # 限制条件为stop_win_n值为3.0 sell_factors = [{'stop_loss_n': 1.5, 'stop_win_n': 3.0, 'class': AbuFactorAtrNStop}, {'class': AbuFactorPreAtrNStop, 'pre_atr_n': 1.5}, {'class': AbuFactorCloseAtrNStop, 'close_atr_n': 1.5}] cross_val.fit(buy_factors, sell_factors, cv=10) ``` -------------------------------- ### Initializing Abu Quant Backtesting UI - Python Source: https://github.com/bbfamily/abu/blob/master/abupy_ui/历史回测界面操作.ipynb This Python snippet imports the necessary module and calls a function to display the interactive backtesting user interface for the Abu Quant system. It uses the `%matplotlib inline` magic command, typically for use within Jupyter notebooks, to ensure plots are displayed directly below the code cell. ```python %matplotlib inline import widget_loop_back widget_loop_back.show_ui() ``` -------------------------------- ### Analyzing Backtest Performance Metrics - Python Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/4-多支股票择时回测与仓位管理(ABU量化使用文档).ipynb Imports the `AbuMetricsBase` class from abupy's metrics module and uses the results (orders_pd, action_pd, capital, benchmark) of the completed backtest to calculate various performance statistics. It then plots the cumulative returns of the strategy and the benchmark. ```python from abupy import AbuMetricsBase metrics = AbuMetricsBase(orders_pd, action_pd, capital, benchmark) metrics.fit_metrics() metrics.plot_returns_cmp(only_show_returns=True) ``` -------------------------------- ### Running Backtest on Training Data and Storing Results (Python) Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/15-量化交易和搜索引擎(ABU量化使用文档).ipynb Executes the main quantitative backtesting simulation using the configured parameters (cash, factors, dates, training symbols). It uses `abu.run_loop_back` for the simulation, clears the progress output afterwards, saves the complete backtest results tuple locally for future use, and extracts the `orders_pd` DataFrame, which includes trade details and generated features. ```python abu_result_tuple_train, _ = abu.run_loop_back(read_cash, buy_factors, sell_factors, start='2014-07-26', end='2016-07-26', choice_symbols=train_choice_symbols) ABuProgress.clear_output() # 把运行的结果保存在本地,以便后面的章节直接使用,保存回测结果数据代码如下所示 abu.store_abu_result_tuple(abu_result_tuple_train, n_folds=2, store_type=EStoreAbu.E_STORE_CUSTOM_NAME, custom_name='lecture_train') orders_pd_train = abu_result_tuple_train.orders_pd ``` -------------------------------- ### Executing Multi-Stock Backtest with Same Factors - Python Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/4-多支股票择时回测与仓位管理(ABU量化使用文档).ipynb Runs a backtest across the selected list of stocks using the identical set of buy and sell factors defined earlier. It utilizes `ABuPickTimeExecute.do_symbols_with_same_factors` to simulate trading and includes the `%%time` IPython magic to measure the execution duration of this sequential backtest process. ```python %%time capital = AbuCapital(1000000, benchmark) orders_pd, action_pd, all_fit_symbols_cnt = ABuPickTimeExecute.do_symbols_with_same_factors(choice_symbols, benchmark, buy_factors, sell_factors, capital, show=False) ``` -------------------------------- ### Running Basic Backtest with AbuDownUpTrend Strategy (Python) Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/32-策略有效性的验证.ipynb Defines a backtesting function run_loo_back that sets the market target, runs the backtest using abu.run_loop_back with specified capital, buy factors, and sell factors, and then displays general metrics using AbuMetricsBase.show_general. It then defines specific buy factors using AbuDownUpTrend with custom parameters (xd=30, past_factor=4, down_deg_threshold=-4) and standard sell factors, and executes a backtest using this function with sample US symbols. ```python # 初始资金量 cash = 3000000 def run_loo_back(choice_symbols, ps=None, n_folds=3, start=None, end=None, only_info=False): """封装一个回测函数,返回回测结果,以及回测度量对象""" if choice_symbols[0].startswith('us'): abupy.env.g_market_target = EMarketTargetType.E_MARKET_TARGET_US else: abupy.env.g_market_target = EMarketTargetType.E_MARKET_TARGET_CN abu_result_tuple, _ = abu.run_loop_back(cash, buy_factors, sell_factors, ps, start=start, end=end, n_folds=n_folds, choice_symbols=choice_symbols) ABuProgress.clear_output() metrics = AbuMetricsBase.show_general(*abu_result_tuple, returns_cmp=only_info, only_info=only_info, only_show_returns=True) return abu_result_tuple, metrics """ 买入策略使用AbuDownUpTrend: 短线基数xd=30: 30个交易日整体趋势为上涨趋势, 长线下跌乘数基数, 海龟突破的30日突破 长线乘数past_factor=4: xd * 4 = 30 * 4 = 120 过去120个交易日整体趋势为下跌趋势 趋势角度阀值down_deg_threshold: 判定趋势是否为上涨下跌的拟合角度值为+-4 """ buy_factors = [{'class': AbuDownUpTrend, 'xd': 30, 'past_factor': 4, 'down_deg_threshold': -4}] sell_factors = [{'stop_loss_n': 1.0, 'stop_win_n': 3.0, 'class': AbuFactorAtrNStop}, {'class': AbuFactorPreAtrNStop, 'pre_atr_n': 1.5}, {'class': AbuFactorCloseAtrNStop, 'close_atr_n': 1.5}] # 开始回测 _, _ = run_loo_back(us_choice_symbols, only_info=True) ``` -------------------------------- ### Defining Factors and Initial Cash - abupy Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/9-港股市场的回测(ABU量化使用文档).ipynb Imports necessary modules from `abupy` for defining trading factors and utilities. It sets the initial trading capital (`read_cash`) and defines lists of dictionaries specifying the buy and sell factors to be used in the backtest, including break-through and ATR-based stop factors. ```python from abupy import AbuFactorAtrNStop, AbuFactorPreAtrNStop, AbuFactorCloseAtrNStop, AbuFactorBuyBreak, ABuProgress from abupy import abu, tl, get_price, ABuSymbolPd, EMarketTargetType, AbuMetricsBase, AbuHkUnit, six # 设置初始资金数 read_cash = 1000000 # 买入因子依然延用向上突破因子 buy_factors = [{'xd': 60, 'class': AbuFactorBuyBreak}, {'xd': 42, 'class': AbuFactorBuyBreak}] # 卖出因子继续使用上一节使用的因子 sell_factors = [ {'stop_loss_n': 1.0, 'stop_win_n': 3.0, 'class': AbuFactorAtrNStop}, {'class': AbuFactorPreAtrNStop, 'pre_atr_n': 1.5}, {'class': AbuFactorCloseAtrNStop, 'close_atr_n': 1.5} ] ``` -------------------------------- ### Splitting Symbols into Training and Testing Sets (Python) Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/15-量化交易和搜索引擎(ABU量化使用文档).ipynb Divides the previously defined lists of symbols into two sets: `train_choice_symbols` and `test_choice_symbols`. The training set is composed of US, CN, and HK stocks plus Bitcoin, while the testing set includes all futures and Litecoin. This manual split prepares the data universe for backtesting specifically the training portion first. ```python # 训练集:沙盒中所有美股 + 沙盒中所有A股 + 沙盒中所有港股 + 比特币 train_choice_symbols = us_choice_symbols + cn_choice_symbols + hk_choice_symbols + tc_choice_symbols[:1] # 测试集:沙盒中所有期货 + 莱特币 test_choice_symbols = ft_choice_symbols + tc_choice_symbols[1:] ``` -------------------------------- ### Executing Backtest with Custom Position Sizing - Python Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/4-多支股票择时回测与仓位管理(ABU量化使用文档).ipynb Sets up an alternative set of buy factors (`buy_factors2`) where the 42-day break factor is configured to use the custom `AbuKellyPosition` class for position sizing. It passes metrics (win rate, mean gains/losses) from the previous backtest as parameters to the custom position manager and then runs the backtest with these modified factors. ```python from abupy import AbuKellyPosition # 42d使用刚刚编写的AbuKellyPosition,60d仍然使用默认仓位管理类,即abupy中内置的AbuAtrPosition类 buy_factors2 = [{'xd': 60, 'class': AbuFactorBuyBreak}, {'xd': 42, 'position': {'class': AbuKellyPosition, 'win_rate': metrics.win_rate, 'gains_mean': metrics.gains_mean, 'losses_mean': -metrics.losses_mean}, 'class': AbuFactorBuyBreak}] capital = AbuCapital(1000000, benchmark) orders_pd, action_pd, all_fit_symbols_cnt = ABuPickTimeExecute.do_symbols_with_same_factors(choice_symbols, benchmark, buy_factors2, sell_factors, capital, show=False) ``` -------------------------------- ### Launching abupy Grid Search UI Widget (Python) Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/32-策略有效性的验证.ipynb Initializes and calls the WidgetGridSearch class, which launches a graphical user interface for interactively performing Grid Search to find optimal strategy parameters. This provides a visual alternative to the code-based Grid Search approach. ```python # 直接启动grid search界面 WidgetGridSearch()() ``` -------------------------------- ### Displaying First 10 Backtest Orders - Python Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/4-多支股票择时回测与仓位管理(ABU量化使用文档).ipynb Shows the initial entries from the `orders_pd` DataFrame generated by the multi-stock backtest. This DataFrame contains detailed information about each trading order, such as the symbol, the number of units traded (`buy_cnt`), and other order parameters. ```python orders_pd[:10] ``` -------------------------------- ### Importing ABU Trading and Umpire Modules (Python) Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/15-量化交易和搜索引擎(ABU量化使用文档).ipynb Imports various specific modules and classes from the abupy library required for defining trading strategies, running backtests, analyzing results, handling market data, and utilizing the machine learning-based 'umpire' (ump) modules. Includes factor classes, core backtesting functions, metrics, drawing tools, symbol handlers, and umpire model classes. ```python from abupy import AbuFactorAtrNStop, AbuFactorPreAtrNStop, AbuFactorCloseAtrNStop, AbuFactorBuyBreak, ABuProgress from abupy import abu, EMarketTargetType, AbuMetricsBase, ABuMarketDrawing, AbuFuturesCn, ABuSymbolPd, ABuMarket from abupy import AbuUmpMainDeg, AbuUmpMainJump, AbuUmpMainPrice, AbuUmpMainWave, AbuFuturesCn, EStoreAbu ``` -------------------------------- ### Loading US Stock Train and Test Backtest Data - Python Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/23-美股UMP决策(ABU量化使用文档).ipynb This snippet configures the environment for the US market and forces local data fetching. It then loads pre-saved backtest results (orders, etc.) for both the training and testing datasets for US stocks, identified by the custom names 'train_us' and 'test_us' and n_folds=5. Finally, it clears the progress bar output and displays the general performance metrics for both datasets. ```python abupy.env.g_market_target = EMarketTargetType.E_MARKET_TARGET_US abupy.env.g_data_fetch_mode = EMarketDataFetchMode.E_DATA_FETCH_FORCE_LOCAL abu_result_tuple = abu.load_abu_result_tuple(n_folds=5, store_type=EStoreAbu.E_STORE_CUSTOM_NAME, custom_name='train_us') abu_result_tuple_test = abu.load_abu_result_tuple(n_folds=5, store_type=EStoreAbu.E_STORE_CUSTOM_NAME, custom_name='test_us') ABuProgress.clear_output() print('训练集结果:') metrics_train = AbuMetricsBase.show_general(*abu_result_tuple, returns_cmp=True ,only_info=True) print('测试集结果:') metrics_test = AbuMetricsBase.show_general(*abu_result_tuple_test, returns_cmp=True, only_info=True) ``` -------------------------------- ### Executing Backtest with Different Factors Per Symbol - Python Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/4-多支股票择时回测与仓位管理(ABU量化使用文档).ipynb Configures unique buy and sell factors for specific target symbols (`usSFUN` and `usNOAH`). It creates a dictionary mapping each symbol to its specific factor configuration and then runs a backtest using `ABuPickTimeExecute.do_symbols_with_diff_factors`, applying the designated strategy to each symbol individually. ```python # 选定noah和sfun target_symbols = ['usSFUN', 'usNOAH'] # 针对sfun只使用42d向上突破作为买入因子 buy_factors_sfun = [{'xd': 42, 'class': AbuFactorBuyBreak}] # 针对sfun只使用60d向下突破作为卖出因子 sell_factors_sfun = [{'xd': 60, 'class': AbuFactorSellBreak}] # 针对noah只使用21d向上突破作为买入因子 buy_factors_noah = [{'xd': 21, 'class': AbuFactorBuyBreak}] # 针对noah只使用42d向下突破作为卖出因子 sell_factors_noah = [{'xd': 42, 'class': AbuFactorSellBreak}] factor_dict = dict() # 构建SFUN独立的buy_factors,sell_factors的dict factor_dict['usSFUN'] = {'buy_factors': buy_factors_sfun, 'sell_factors': sell_factors_sfun} # 构建NOAH独立的buy_factors,sell_factors的dict factor_dict['usNOAH'] = {'buy_factors': buy_factors_noah, 'sell_factors': sell_factors_noah} # 初始化资金 capital = AbuCapital(1000000, benchmark) # 使用do_symbols_with_diff_factors执行 orders_pd, action_pd, all_fit_symbols = ABuPickTimeExecute.do_symbols_with_diff_factors(target_symbols, benchmark, factor_dict, capital) ``` -------------------------------- ### Executing Parallel Multi-Stock Backtest - Python Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/4-多支股票择时回测与仓位管理(ABU量化使用文档).ipynb Runs the multi-stock backtest again, but this time utilizing `AbuPickTimeMaster.do_symbols_with_same_factors_process` to leverage parallel processing. It specifies the number of processes for data fetching (`n_process_kl`) and pick time execution (`n_process_pick_time`) to potentially reduce the overall execution time, demonstrated using the `%%time` magic command. ```python %%time from abupy import AbuPickTimeMaster capital = AbuCapital(1000000, benchmark) orders_pd, action_pd, _ = AbuPickTimeMaster.do_symbols_with_same_factors_process( choice_symbols, benchmark, buy_factors, sell_factors, capital, n_process_kl=4, n_process_pick_time=4) ``` -------------------------------- ### Importing Specific ABU Quant System Modules Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/31-资金仓位管理与买入策略的搭配.ipynb This snippet imports key classes and modules from the abupy library required for defining strategies, position management, drawing tools, factors, utilities, metrics calculation, and market type enumeration. These imports are necessary building blocks for constructing and evaluating trading strategies within the ABU framework. ```python from abupy import AbuDownUpTrend, AbuPtPosition, ABuMarketDrawing from abupy import AbuFactorCloseAtrNStop, AbuFactorAtrNStop, AbuFactorPreAtrNStop, tl from abupy import abu, ABuProgress, AbuMetricsBase, EMarketTargetType ``` -------------------------------- ### Executing Backtest Simulation - abupy Source: https://github.com/bbfamily/abu/blob/master/abupy_lecture/9-港股市场的回测(ABU量化使用文档).ipynb Initiates the backtesting process using the `abu.run_loop_back` function. It takes the initial cash, defined buy/sell factors, number of folds for cross-validation, and the list of chosen symbols as input. It then clears any output related to progress indication. ```python abu_result_tuple, kl_pd_manger = abu.run_loop_back(read_cash, buy_factors, sell_factors, n_folds=6, choice_symbols=choice_symbols) ABuProgress.clear_output() ```