Download backtest_framework(4)/backtest_framework/data_api_module.py from 2090741942justin/quant: direct link, hf CLI and curl.
- Browser
- Download file 52 kB
-
https://huggingface.co/datasets/2090741942justin/quant/resolve/main/backtest_framework(4)/backtest_framework/data_api_module.py
- Command line
-
hf download 'hf://datasets/2090741942justin/quant/backtest_framework(4)/backtest_framework/data_api_module.py'
-
curl -L -o data_api_module.py 'https://huggingface.co/datasets/2090741942justin/quant/resolve/main/backtest_framework(4)/backtest_framework/data_api_module.py'
52 kB
| # coding: UTF-8 | |
| import configparser | |
| import os | |
| import psutil | |
| import scipy.io as scio | |
| import numpy as np | |
| import pandas as pd | |
| import sys | |
| from backtest_framework.print_type import PrintType as p | |
| import copy | |
| import warnings | |
| from sklearn.linear_model import LinearRegression | |
| import scipy.stats as st | |
| from wby_utils.path.Path import get_all_dirs | |
| warnings.filterwarnings("ignore") | |
| class DataApi: | |
| def getConfig(self): | |
| """ | |
| 赋值路径用函数 | |
| :param: | |
| :return: | |
| """ | |
| try: | |
| self.config = configparser.ConfigParser() | |
| self.config.read(self.configPath, encoding="utf-8") | |
| except Exception as e: | |
| p.error_print(sys._getframe().f_code.co_filename, sys._getframe().f_code.co_name, "配置文件读取失败!") | |
| else: | |
| self.local_db_path = self.config['data_path']['local_db'] | |
| self.dataPathList.append(self.config['data_path']['base_data_path']) | |
| self.factorNpzPath = self.config['data_path']['derivative_factor_npz_path'] # 因子路径 | |
| self.dataPathList.append(self.factorNpzPath) | |
| self.result_path = self.config['data_path']['result_path'] # 结果路径 | |
| self.dataPathList.append(self.result_path) | |
| def getLpp(self): | |
| """ | |
| 获取回测下标用函数 | |
| :return: int,回测下标 | |
| """ | |
| return self.lpp | |
| def setLpp(self, lpp): | |
| """ | |
| 设置回测下标用函数 | |
| :return: | |
| """ | |
| self.lpp = lpp | |
| def version(process_name): | |
| """ | |
| 展示版本用函数 | |
| :param process_name: 运行程序类名,char类型 | |
| :return: | |
| """ | |
| crossbar = "===============================================" | |
| version = "==" + process_name + " for Python3, Version: 0.0.1==" | |
| p.version_print(sys._getframe().f_code.co_filename, sys._getframe().f_code.co_name, crossbar) | |
| p.version_print(sys._getframe().f_code.co_filename, sys._getframe().f_code.co_name, version) | |
| p.version_print(sys._getframe().f_code.co_filename, sys._getframe().f_code.co_name, crossbar) | |
| def loadDerivativeFactorToGlobal(self, factorName, shapeType, typeLen): | |
| """ | |
| 从指定目录读取因子数据用函数 | |
| :param factorName:因子名 | |
| :param shapeType:char类型,‘tensor’表示三维矩阵型因子,’matrix‘表示矩阵型因子,’vector‘表示列表型因子 | |
| :param typeLen:typeLen在当type为’vector‘的时候的列数,‘tensor’二维和三维的长度 | |
| :return: | |
| """ | |
| if factorName in self.globalSave.keys(): | |
| p.disp_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, "请求的因子已被导入!") | |
| return | |
| tradeDate = self.getAllData("trade_date_int") | |
| filePath_npz = self.factorNpzPath + factorName + ".npz" | |
| filePath_mat = self.factorNpzPath + factorName + ".mat" | |
| try: | |
| try: | |
| data = np.load(filePath_npz) | |
| single_key = data.files[0] | |
| factorData = data[single_key] | |
| except: | |
| factorData = scio.loadmat(filePath_mat)[factorName] | |
| site = np.max([1, np.shape(factorData)[0] - self.factorGeneratorTradeDateCount - 1]) | |
| self.startDate = str(tradeDate[site][0]) | |
| self.endDate = str(tradeDate[-1][0]) | |
| if shapeType == "matrix": | |
| factorData = self.myFactorReshape(factorData) | |
| elif shapeType == 'vector': | |
| factor = np.nan * np.zeros((len(tradeDate), factorData.shape[1])) | |
| factor[:factorData.shape[0], :factorData.shape[1]] = factorData | |
| factorData = factor | |
| elif shapeType == 'tensor': | |
| factor = np.nan * np.zeros((len(tradeDate), factorData.shape[1], factorData.shape[2])) | |
| factor[:factorData.shape[0], :factorData.shape[1], :factorData.shape[2]] = factorData | |
| factorData = factor | |
| except: | |
| self.startDate = str(tradeDate[0][0]) | |
| self.endDate = str(tradeDate[-1][0]) | |
| if shapeType == 'matrix': | |
| factorData = self.myFactorReshape() | |
| elif shapeType == 'vector': | |
| factorData = np.nan * np.zeros((len(tradeDate), typeLen)) | |
| elif shapeType == 'tensor': | |
| if len(typeLen) == 1: | |
| p.error_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, "typeLen参数不能为标量!") | |
| factorData = np.nan * np.zeros((len(tradeDate), typeLen[0], typeLen[1])) | |
| self.globalSave[factorName] = factorData | |
| p.disp_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, "导入" + factorName + "文件!") | |
| def setGlobal(self, globalName, globalValue): | |
| """ | |
| 存储全局变量用函数 | |
| :param globalName: char类型,全局变量名 | |
| :param globalValue: 任意类型,全局变量值 | |
| :return: | |
| """ | |
| self.globalSave[globalName] = globalValue | |
| def getGlobal(self, globalName): | |
| """ | |
| 获取全局变量用函数 | |
| :param globalName: char类型,全局变量名 | |
| :return: 任意类型, 全局变量值 | |
| """ | |
| try: | |
| return self.globalSave[globalName] | |
| except: | |
| p.warning_print(sys._getframe().f_code.co_filename, sys._getframe().f_code.co_name, | |
| f"请求的全局变量不存在!{globalName}") | |
| return None | |
| def getAllData(self, key): | |
| """ | |
| 获取数据文件用函数 | |
| :param key: char类型,数据名称 | |
| :return: 数据文件,np.array格式 | |
| """ | |
| if key not in self.allData: | |
| npzFile = key + '.npz' | |
| matFile = key + '.mat' | |
| for dataPath in self.dataPathList: | |
| if npzFile in os.listdir(dataPath): | |
| data = np.load(dataPath + "\\\\" + npzFile, allow_pickle=True) | |
| single_key = data.files[0] | |
| value = data[single_key] | |
| self.allData[key] = value | |
| p.disp_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "因子文件" + key + "成功导入!") | |
| return self.allData[key] | |
| elif matFile in os.listdir(dataPath): | |
| value = scio.loadmat(dataPath + matFile)[key] | |
| self.allData[key] = value | |
| p.disp_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "因子文件" + key + "成功导入!") | |
| return self.allData[key] | |
| p.error_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "因子文件导入失败!找不到因子文件" + key + ",请更新因子!" + dataPath) | |
| return self.allData[key] | |
| def getDataPackage(self, key): | |
| """ | |
| 获取数据文件用函数 | |
| :param key: char类型,数据名称 | |
| :return: 数据文件,np.array格式 | |
| """ | |
| if key not in self.allData: | |
| npzFile = key + '.npz' | |
| matFile = key + '.mat' | |
| for dataPath in self.dataPathList: | |
| if npzFile in os.listdir(dataPath): | |
| data = np.load(dataPath + "\\\\" + npzFile, allow_pickle=True) | |
| self.allData[key] = data | |
| p.disp_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "数据包" + key + "成功导入!") | |
| return self.allData[key] | |
| elif matFile in os.listdir(dataPath): | |
| value = scio.loadmat(dataPath + matFile)[key] | |
| self.allData[key] = value | |
| p.disp_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "数据包" + key + "成功导入!") | |
| return self.allData[key] | |
| p.error_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "数据包导入失败!找不到数据包" + key + ",请更新数据包!") | |
| return self.allData[key] | |
| def getFieldTickData(self, code, tradeDate): | |
| """ | |
| 获取tick交易数据用函数 | |
| :param code: char类型,股票代码 | |
| :param tradeDate:int类型,交易日期 | |
| :return: np.array类型,tick交易数据 | |
| """ | |
| trade_date = self.getAllData('trade_date_int') | |
| tradeDateSite = np.where(trade_date == int(tradeDate))[0][0] | |
| if not tradeDateSite: | |
| p.error_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, "请求的日期为非交易日!") | |
| elif tradeDateSite > self.getLpp(): | |
| p.error_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, "禁止提取未来数据!") | |
| else: | |
| quotePath = self.local_db_path + 'quote_data\\stock\\xt_tick_data\\' + str(tradeDate) + '\\' | |
| dataFile = f"{quotePath}{code}.npz" | |
| ret = np.load(dataFile, allow_pickle=True) | |
| return ret | |
| def getFieldMinuteData(self, fieldName, tradeDate): | |
| """ | |
| 获取日内交易数据用函数 | |
| :param fieldName: char类型,日内交易数据名称 | |
| :param tradeDate: int类型,交易日期 | |
| :return: np.array类型,日内交易数据 | |
| """ | |
| trade_date = self.getAllData('trade_date_int') | |
| tradeDateSite = np.where(trade_date == int(tradeDate))[0][0] | |
| if not tradeDateSite: | |
| p.error_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, "请求的日期为非交易日!") | |
| elif tradeDateSite > self.getLpp(): | |
| p.error_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, "禁止提取未来数据!") | |
| else: | |
| if fieldName[-2:] == '1m': | |
| quotePath = self.local_db_path + 'quote_data\\stock\\minute_data\\1m\\' | |
| elif fieldName[-2:] == '5m' and not fieldName[-3:] == '15m': | |
| quotePath = self.local_db_path + 'quote_data\\stock\\minute_data\\5m\\' | |
| elif fieldName[-3:] == '10m': | |
| quotePath = self.local_db_path + 'quote_data\\stock\\minute_data\\10m\\' | |
| elif fieldName[-3:] == '15m': | |
| quotePath = self.local_db_path + 'quote_data\\stock\\minute_data\\15m\\' | |
| elif fieldName[-3:] == '30m': | |
| quotePath = self.local_db_path + 'quote_data\\stock\\minute_data\\30m\\' | |
| elif fieldName[-3:] == '60m': | |
| quotePath = self.local_db_path + 'quote_data\\stock\\minute_data\\60m\\' | |
| else: | |
| p.error_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "请求的因子文件为非日内行情数据!") | |
| dataFile = f"{quotePath}{fieldName}_{tradeDate}.npz" | |
| data = np.load(dataFile, allow_pickle=True) | |
| single_key = data.files[0] | |
| value = data[single_key] | |
| ret = self.quoteCorrection(value) | |
| return ret | |
| def getStartTradeDate(self, startTradeDate, change): | |
| """ | |
| 设置开始交易日期标签用函数 | |
| :param startTradeDate: int类型,开始交易日期 | |
| :return: startDateFlag数值,int类型 | |
| """ | |
| tradeDate = self.getAllData('trade_date_int') | |
| if startTradeDate and startTradeDate != np.inf: | |
| date = int(startTradeDate) | |
| ret = 0 | |
| minDistant = np.inf | |
| for i in list(range(0, len(tradeDate))): | |
| if tradeDate[i] - date < minDistant and tradeDate[i] - date >= 0: | |
| minDistant = tradeDate[i] - date | |
| ret = i | |
| else: | |
| ret = 0 | |
| if change == True: | |
| self.startDateFlag = ret | |
| return ret | |
| def getEndTradeDate(self, endTradeDate=""): | |
| """ | |
| 设置结束交易日期标签用函数 | |
| :param endTradeDate: int类型,结束交易日期 | |
| :return: endDateFlag数值,int类型 | |
| """ | |
| tradeDate = self.getAllData('trade_date_int') | |
| if endTradeDate and endTradeDate != np.inf: | |
| date = int(endTradeDate) | |
| ret = 0 | |
| minDistant = np.inf | |
| for i in list(range(0, len(tradeDate))): | |
| if date - tradeDate[i] < minDistant and date - tradeDate[ | |
| i] >= 0: | |
| minDistant = date - tradeDate[i] | |
| ret = i | |
| else: | |
| ret = len(tradeDate) | |
| self.endDateFlag = ret | |
| return ret | |
| def myFactorReshape(self, inputData): | |
| """ | |
| 规范数据形状用函数 | |
| :param inputData: np.array类型,输入的数据 | |
| :return: np.array类型,重塑形状之后的数据 | |
| """ | |
| tradeDate = self.getAllData("trade_date_int") | |
| stock_list = self.getAllData("stock_code") | |
| if not inputData is None: | |
| if inputData.shape[1] < len(stock_list): | |
| ret = np.hstack((inputData, np.nan * np.zeros( | |
| (inputData.shape[0], | |
| len(stock_list) - inputData.shape[1])))) | |
| else: | |
| ret = inputData | |
| if inputData.shape[0] < len(tradeDate): | |
| ret = np.vstack((ret, np.nan * np.zeros( | |
| (len(tradeDate) - ret.shape[0], ret.shape[1])))) | |
| else: | |
| ret = np.nan * np.zeros([len(tradeDate), len(stock_list)]) | |
| return ret | |
| def myWinsorizeCalc(self, inputValue, sigma, calcType): | |
| """ | |
| 去极值用函数 | |
| :param inputValue: np.array类型,输入的数据 | |
| :param sigma: int类型,控制宽度参数 | |
| :param calcType: char类型,“std”、“median”、“Briner”,代表去极值方法 | |
| :return: np.array类型,去极值后的数据 | |
| """ | |
| inputValue_ = copy.deepcopy(inputValue) | |
| if calcType == 'std' or calcType == 'median': | |
| if calcType == 'std': | |
| meanValue = np.nanmean(inputValue_) | |
| stdValue = np.nanstd(inputValue_) | |
| elif calcType == 'median': | |
| meanValue = np.nanmedian(inputValue_) | |
| stdValue = np.nanmedian(np.abs(inputValue_ - meanValue)) | |
| upperThreshold = meanValue + stdValue * sigma | |
| lowerThreshold = meanValue - stdValue * sigma | |
| while len(np.where(inputValue_ > upperThreshold)[1]) > 0 or len( | |
| np.where(inputValue_ < lowerThreshold)[1]) > 0: | |
| inputValue_[0, np.where( | |
| inputValue_ > upperThreshold)[1]] = upperThreshold | |
| inputValue_[0, np.where( | |
| inputValue_ < lowerThreshold)[1]] = lowerThreshold | |
| if calcType == 'std': | |
| meanValue = np.nanmean(inputValue_) | |
| stdValue = np.nanstd(inputValue_) | |
| elif calcType == 'median': | |
| meanValue = np.nanmedian(inputValue_) | |
| stdValue = np.nanmedian(np.abs(inputValue_ - meanValue)) | |
| upperThreshold = meanValue + stdValue * sigma | |
| lowerThreshold = meanValue - stdValue * sigma | |
| elif calcType == 'Briner': | |
| inputValue_ = self.myStandardizeCalc(inputValue_) | |
| s_plus = max(0, min(1, 0.5 / np.nanmax(inputValue_ - sigma))) | |
| s_minus = max(0, min(1, -0.5 / np.nanmin(inputValue_ + sigma))) | |
| inputValue_[0, np.where( | |
| inputValue_ > sigma)[1]] = sigma * (1 - s_plus) + inputValue_[ | |
| 0, np.where(inputValue_ > sigma)[1]] * s_plus | |
| inputValue_[0, np.where( | |
| inputValue_ < -sigma)[1]] = -sigma * (1 - s_minus) + inputValue_[ | |
| 0, np.where(inputValue_ < -sigma)[1]] * s_minus | |
| else: | |
| meanValue = np.nan | |
| stdValue = np.nan | |
| p.warning_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, "标准化类型的入参有误!") | |
| return inputValue_ | |
| def myStandardizeCalc(self, inputValue, calcType, filter): | |
| """ | |
| 标准化用函数 | |
| :param inputValue: np.array类型,输入的数据 | |
| :param calcType: char类型,“zscore”或“0-1”,代表标准化方法 | |
| :return: np.array类型,标准化后的数据 | |
| """ | |
| if calcType == 'zscore': | |
| return (inputValue - | |
| np.nanmean(inputValue)) / np.nanstd(inputValue) | |
| elif calcType == '0-1': | |
| return (inputValue - np.nanmin(inputValue)) / ( | |
| np.nanmax(inputValue) - np.nanmin(inputValue)) | |
| elif calcType == 'ppf': | |
| ppf = st.norm.ppf(1 - np.sum(~np.isnan(inputValue)) / np.sum(~np.isnan(filter))) | |
| return ppf + (np.nanmax(inputValue) - ppf) / (np.nanmax(inputValue) - np.nanmin(inputValue)) * ( | |
| inputValue - np.nanmin(inputValue)) | |
| def myNanFillAsData(self, inputValue, data): | |
| """ | |
| 缺失值填充用函数 | |
| :param inputValue: np.array类型,输入的数据 | |
| :param data: float类型,填充缺失值用参数 | |
| :return: np.array类型,填充缺失值后的数据 | |
| """ | |
| stockTradeDayCount = self.getFieldData('stockTradeDayCount', 1) | |
| inTheMarket = np.nan * np.zeros([1, np.shape(stockTradeDayCount)[1]]) | |
| inTheMarket[0, np.where(stockTradeDayCount > 0)[1]] = 1 | |
| for i in range(np.shape(inTheMarket)[1]): | |
| if np.isnan(inTheMarket[0, i]) == False and np.isnan( | |
| inputValue[0, i]): | |
| inputValue[0, i] = data | |
| return inputValue * inTheMarket | |
| def myIndustryFlag(zx): | |
| """ | |
| 生成各股行业one-hot矩阵用函数 | |
| :param zx: np.array类型,中信行业数据 | |
| :return: np.array类型,各股行业one-hot矩阵 | |
| """ | |
| ret = np.zeros([int(np.nanmax(zx)), int(np.shape(zx)[1])]) | |
| for i in list(range(int(np.nanmax(zx)))): | |
| ret[i, np.where(zx == i + 1)[1]] = 1 | |
| return ret | |
| def removeAllData(self, key, usedMemoProcess, usedMemoPercent): | |
| """ | |
| 从内存移除数据用函数 | |
| :param key: list类型,包含数据名称的列表 | |
| :param usedMemoProcess: float类型,python进程占用内存GB上限 | |
| :param usedMemoPercent: float类型,计算机内存占用百分比上限 | |
| :return: | |
| """ | |
| if not usedMemoProcess and not usedMemoPercent: | |
| for i in range(len(key)): | |
| self.allData.pop(key[i]) | |
| p.disp_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "请求的因子/数据包" + key[i] + "删除完毕!") | |
| else: | |
| mem_Process = round( | |
| psutil.Process(os.getpid()).memory_info().rss / 1024 / 1024 / | |
| 1024, 2) | |
| memPercent = round(psutil.virtual_memory().percent / 100, 2) | |
| if (usedMemoProcess and mem_Process > usedMemoProcess) or ( | |
| usedMemoPercent and memPercent > usedMemoPercent): | |
| for i in range(len(key)): | |
| self.allData.pop(key[i]) | |
| p.disp_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "请求的因子/数据包" + key[i] + "删除完毕!") | |
| def getStockName(self): | |
| """ | |
| 获取股票名称用函数 | |
| :param | |
| :return: np.array类型,股票名称列表 | |
| """ | |
| return self.getAllData("stockName") | |
| def getStockCode(self): | |
| """ | |
| 获取股票数字代码用函数 | |
| :param | |
| :return: np.array类型,股票数字代码列表 | |
| """ | |
| stock_list = self.getStockList() | |
| return np.array(list(map(lambda x: int(x[:6]), stock_list))) | |
| def getStockList(self): | |
| """ | |
| 获取股票代码用函数 | |
| :param | |
| :return: np.array类型,股票代码列表 | |
| """ | |
| return self.getAllData("stock_code") | |
| def getTradeDateList(self, varargin): | |
| """ | |
| 返回交易日历,不传入参数返回历史所有的交易日历,传入参数返回固定交易日数的交易日历 | |
| :param days: 返回固定交易日期数 | |
| :return: List | |
| """ | |
| ret = self.getAllData("trade_date_int") | |
| if varargin: | |
| return ret[self.getLpp() - varargin + 1:self.getLpp() + 1, :] | |
| else: | |
| return ret[:self.getLpp() + 1, :] | |
| def isLastDate(self): | |
| """ | |
| 判断是否为最后一个回测截面,如果是,返回True,否则返回False | |
| :return: bool | |
| """ | |
| return self.lpp == self.endDateFlag | |
| def getStockIndexQuotes(self, indexCode, varargin): # TODO | |
| """ | |
| 获取股票指数行情数据 | |
| :param indexCode:指数代码 | |
| :param varargin:可选参数,截取的日期行数 | |
| :return: | |
| """ | |
| lpp = self.lpp | |
| nowDate = self.getNowDate() | |
| indexQuotes = self.getAllData("stockIndexQuotes")[()][indexCode] | |
| site = np.where(indexQuotes[:, 0] == nowDate)[0][0] | |
| if varargin: | |
| return indexQuotes[lpp - varargin + 1:lpp + 1] | |
| else: | |
| return indexQuotes[:lpp + 1] | |
| def getStockIndexDailyQuotes(self, indexCode, tradeDate): | |
| """ | |
| 获取股票指数日内行情数据 | |
| :param indexCode:指数代码 | |
| :param tradeDate:行情日期 | |
| :return: | |
| """ | |
| return self.getAllData("stockIndexDailyQuotes")[()][indexCode][tradeDate] | |
| def getFieldData(self, fieldName, varargin): | |
| """ | |
| 获取因子矩阵用函数 | |
| :param fieldName:因子名 | |
| :param varargin: 返回的因子行数 | |
| :return: | |
| """ | |
| lpp = self.lpp | |
| if varargin: | |
| return self.getAllData(fieldName)[lpp - varargin + 1:lpp + 1] | |
| else: | |
| return self.getAllData(fieldName)[:lpp + 1] | |
| def getFieldDataByIndex(self, fieldName, index): | |
| """ | |
| 获取因子矩阵用函数 | |
| :param fieldName:因子名 | |
| :param index: 回测下标 | |
| :return: | |
| """ | |
| return self.getAllData(fieldName)[index].reshape(1, -1) | |
| def saveGlobal(self, globalName): | |
| """ | |
| 存储因子到指定文件夹目录 | |
| :param globalName:请求存储的因子名 | |
| :return: | |
| """ | |
| factorData = self.getGlobal(globalName) | |
| if sum(factorData[-1] == 0) + sum(np.isnan( | |
| factorData[-1])) == factorData.shape[1]: | |
| p.warning_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "衍生因子 " + globalName + " 异常,结果未保存!") | |
| else: | |
| np.savez_compressed(self.factorNpzPath + globalName + '.npz', factorData) | |
| if self.saveFactorResultAsMat == True: | |
| scio.savemat(self.factorNpzPath + globalName + '.mat', {globalName: factorData}) | |
| p.disp_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "衍生因子 " + globalName + " 保存完成!") | |
| def saveGlobalUnconditionally(self, globalName): | |
| """ | |
| 无条件存储因子到指定文件夹目录 | |
| :param globalName:请求存储的因子名 | |
| :return: | |
| """ | |
| factorData = self.getGlobal(globalName) | |
| np.savez_compressed(self.factorNpzPath + globalName + '.npz', factorData) | |
| if self.saveFactorResultAsMat == True: | |
| scio.savemat(self.factorNpzPath + globalName + '.mat', {globalName: factorData}) | |
| p.disp_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "衍生因子 " + globalName + " 保存完成!") | |
| def getBarCount(self): | |
| """ | |
| 返回bar计数 | |
| :return: | |
| """ | |
| return self.barCount | |
| def getNowDate(self, type): | |
| """ | |
| 返回回测当日下标的日期 | |
| :return: | |
| """ | |
| if type == 'int': | |
| return self.getAllData("trade_date_int")[self.lpp][0] | |
| elif type == 'datetime': | |
| return self.getAllData("trade_date_datetime")[self.lpp][0] | |
| else: | |
| p.error_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "type类型有误!") | |
| def getYesterdayDate(self, type): | |
| """ | |
| 返回回测前一日下标的日期 | |
| :return: | |
| """ | |
| if type == 'int': | |
| return self.getAllData("trade_date_int")[self.lpp - 1][0] | |
| elif type == 'datetime': | |
| return self.getAllData("trade_date_datetime")[self.lpp - 1][0] | |
| else: | |
| p.error_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "type类型有误!") | |
| def getNextDate(self, type): | |
| """ | |
| 返回回测下一日下标的日期 | |
| :return: | |
| """ | |
| if type == 'int': | |
| tradeDate = self.getAllData("trade_date_int") | |
| tradeDateHistory = self.getAllData("calendar_date_int") | |
| elif type == 'datetime': | |
| tradeDate = self.getAllData("trade_date_datetime") | |
| tradeDateHistory = self.getAllData("calendar_date_datetime") | |
| else: | |
| p.error_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "type类型有误!") | |
| index = np.where(tradeDateHistory == tradeDate[self.lpp])[0][0] | |
| return tradeDateHistory[index + 1][0] | |
| def getHalfTimeWeight(halflife, window): | |
| ''' | |
| 得到半衰期权重,WLS回归用 | |
| :param halflife: 半衰期时长,int类型 | |
| :param window: 观察期窗口,int类型 | |
| :return: 半衰期标准化后的权重,np.array类型,一行 | |
| ''' | |
| sigma = 0.5 ** (1 / halflife) | |
| weight = np.empty([1, window]) | |
| for i in range(window): | |
| weight[0, i] = sigma ** (window - i) | |
| weight = weight / np.sum(weight) | |
| return weight.reshape(1, -1) # 转化为1Darray 方便 | |
| def myFiltering(self, inputValue): | |
| """ | |
| 将非交易日的因子值设置为np.nan用函数,同时将inf转化为nan | |
| :param inputValue: np.array类型,输入的数据 | |
| :param data: float类型,填充缺失值用参数 | |
| :return: np.array类型,填充缺失值后的数据 | |
| """ | |
| stockTradeDayCount = self.getFieldData('stock_on_list_duration', 1) | |
| stockTradeDayCount = stockTradeDayCount.astype(np.float32) | |
| stockTradeDayCount[stockTradeDayCount > 0] = 1 | |
| stockTradeDayCount[stockTradeDayCount == 0] = np.nan | |
| ret = inputValue * stockTradeDayCount | |
| ret[np.isinf(ret)] = np.nan | |
| return ret | |
| def myRank(self, data, type): | |
| """ | |
| 将因子截面数据做排名返回 | |
| :param data: np.array类型,因子截面数据的输入值 | |
| :param type: char类型,降序(descend)、升序(ascend) | |
| :return: np.array类型,data的排名返回值 | |
| """ | |
| if type == '降序' or type == 'descend': | |
| rev = -1 | |
| elif type == '升序' or type == 'ascend': | |
| rev = 1 | |
| data_ = copy.deepcopy(data) | |
| data_ = np.array(data_) | |
| Site = np.where(~np.isnan(data_)) | |
| data_[Site] = np.argsort(data_[Site] * rev) | |
| data_[Site] = np.argsort(data_[Site]) | |
| return data_.reshape(1, -1) | |
| def mySort(self, data, type): | |
| """ | |
| 将因子排序下标返回 | |
| :param data: np.array类型,因子截面数据的输入值 | |
| :param type: char类型,降序(descend)、升序(ascend) | |
| :return: np.array类型,data的排名下标返回值 | |
| """ | |
| if type == '降序' or type == 'descend': | |
| rev = -1 | |
| elif type == '升序' or type == 'ascend': | |
| rev = 1 | |
| data_ = copy.deepcopy(data) | |
| Site = np.where(~np.isnan(data_)) | |
| data_ = np.array(data_) | |
| data_[Site] = np.argsort(data_[Site] * rev) | |
| return data_.reshape(1, -1) | |
| def quoteCorrection(self, inputvalue): | |
| ''' | |
| 纠正getFieldDailyData获得数据列数错误用函数 | |
| :param inputValue: np.array类型,输入的数据 | |
| :return: np.array类型,列数正确的函数 | |
| ''' | |
| column_num = len(self.getAllData('stock_code')) | |
| value_num = inputvalue.shape[1] | |
| if column_num > value_num: | |
| ret = np.hstack( | |
| (inputvalue, np.nan * | |
| np.zeros([inputvalue.shape[0], column_num - value_num]))) | |
| elif column_num <= value_num: | |
| ret = inputvalue[:, :column_num] | |
| return ret | |
| def regForNeutralizeFactor(self, factor, list1): | |
| ''' | |
| 中性化因子用函数 | |
| :param factor: 被中性化的因子,二维数组(1,) | |
| :param list: 包含中性化因子数组的列表,列表内部数据格式:二维数组(1,) | |
| :return: ndarray类型,回归后的残差,二维数组(1,) | |
| ''' | |
| factor = factor.T | |
| neutralizeList = np.zeros((factor.shape[0], len(list1))) * np.nan | |
| result = np.zeros((1, factor.shape[0])) * np.nan | |
| for i in range(len(list1)): | |
| neutralizeList[:, i] = list1[i][0, :] | |
| y = factor | |
| x = neutralizeList | |
| for i in range(x.shape[1]): | |
| if i == 0: | |
| y_not_empty = np.where(~np.isnan(y))[0].tolist() | |
| x_not_empty = np.where(~np.isnan(x[:, i]))[0].tolist() | |
| not_empty = list(set(x_not_empty).intersection(set(y_not_empty))) | |
| else: | |
| y_not_empty = not_empty | |
| x_not_empty = np.where(~np.isnan(x[:, i]))[0].tolist() | |
| not_empty = list(set(x_not_empty).intersection(set(y_not_empty))) | |
| y = y[not_empty] | |
| x = x[not_empty] | |
| m = LinearRegression() | |
| m.fit(x, y) | |
| residual = y - m.predict(x) | |
| for i in range(len(not_empty)): | |
| result[0, not_empty[i]] = residual[i, 0] | |
| return result | |
| def myNeutralizeCalc(self, y, x): | |
| ''' | |
| :param x: | |
| :param y: | |
| :return: | |
| ''' | |
| fit_data = np.vstack((x, y)) | |
| site = np.where(~np.isnan(np.sum(fit_data, axis=0)))[0] | |
| x_ = x[:, site] | |
| y_ = y[:, site] | |
| resid = np.nan * np.zeros(y.shape).reshape(1, -1) | |
| if x_.size and y_.size: | |
| m = LinearRegression() | |
| m.fit(x_.T, y_.T) | |
| resid[0, site] = (y_.T - m.predict(x_.T)).reshape(1, -1) | |
| return resid | |
| def getReportPeriodsList(self, modified): | |
| ''' | |
| 获取最新报告期列表用函数 | |
| :param modified: bool类型,确定是否需要扩展 | |
| :return: np.array类型,报告期数组 | |
| ''' | |
| report_periods_list = self.getFieldData('reportPeriodsList') | |
| report_periods_list = report_periods_list[~np.isnan(report_periods_list | |
| )] | |
| report_periods_list = np.array(list(set(report_periods_list.tolist()))) | |
| report_periods_list = np.flipud(np.sort(report_periods_list)) | |
| if modified == False: | |
| return report_periods_list | |
| else: | |
| if report_periods_list[0] % 10000 == 1231: | |
| report_periods_list = np.insert(report_periods_list, 0, | |
| report_periods_list[0] + 9100) | |
| elif report_periods_list[0] % 10000 == 930: | |
| report_periods_list = np.insert(report_periods_list, 0, | |
| report_periods_list[0] + 301) | |
| elif report_periods_list[0] % 10000 == 630: | |
| report_periods_list = np.insert(report_periods_list, 0, | |
| report_periods_list[0] + 300) | |
| elif report_periods_list[0] % 10000 == 331: | |
| report_periods_list = np.insert(report_periods_list, 0, | |
| report_periods_list[0] + 299) | |
| return report_periods_list | |
| def getFinancialAllData(self, key): | |
| """ | |
| 导入数据包用函数 | |
| :param key: char类型,数据包名 | |
| :return: tuple类型,包含数据包数据值和数据名称的元组 | |
| """ | |
| if key in self.allData: | |
| return self.allData[key] | |
| npzFile = key + '.npz' | |
| for dataPath in self.dataPathList: | |
| if npzFile in os.listdir(dataPath): | |
| dataFile = dataPath + "\\\\" + npzFile | |
| break | |
| try: | |
| data = np.load(dataFile, allow_pickle=True) | |
| except: | |
| p.error_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "数据包导入失败!找不到数据包" + key + ",请更新数据包!") | |
| else: | |
| value = data['value'] | |
| fieldName = data['fieldname'] | |
| v = (value, fieldName) | |
| self.allData[key] = v | |
| return self.allData[key] | |
| def getFinancialFieldData(self, tableName, fieldName, reportDate): | |
| """ | |
| 获取金融数据 | |
| :param tableName: char类型,数据包名称 | |
| :param fieldName: char/list/tuple类型,数据包中具体数据名称 | |
| :param reportDate: int类型,报告期 | |
| :return: np.array类型,具体的金融数据 | |
| """ | |
| nextDate = self.getNextDate() | |
| tableData = self.getFinancialAllData(tableName) | |
| fieldData = tableData[0] | |
| fieldNameList = tableData[1] | |
| if isinstance(fieldName, str): | |
| try: | |
| site = np.where(fieldNameList == fieldName)[0][0] | |
| except: | |
| p.error_print( | |
| sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "在" + tableName + "数据包里找不到对应的" + fieldName + "字段!") | |
| else: | |
| fieldData = fieldData[:, [0, 1, 2, site]] | |
| stockCode = self.getStockCode() | |
| IA_ret = np.ones([1, len(stockCode)]) | |
| fieldData = fieldData[np.where( | |
| fieldData[:, 1] <= nextDate)[0], :] | |
| ret = np.nan * np.zeros([1, len(stockCode)]) | |
| fieldData = fieldData[np.where( | |
| fieldData[:, 2] == reportDate)[0], :] | |
| if fieldData.size == 0: | |
| return ret | |
| else: | |
| for i in range(len(stockCode)): | |
| dataTemp = fieldData[np.where( | |
| fieldData[:, 0] == stockCode[i])[0]] | |
| if dataTemp.size == 0: | |
| IA_ret[0, i] = np.nan | |
| continue | |
| if np.shape(dataTemp)[0] > 1: | |
| dataTemp = dataTemp[np.argsort(dataTemp[:, 1])] | |
| ret[0, i] = dataTemp[-1, -1] | |
| if tableName != 'ASHARE_PROFITNOTICE': | |
| ret[np.where(np.isnan(ret))] = 0 | |
| ret = ret * IA_ret | |
| elif isinstance(fieldName, (np.ndarray, list, tuple)): | |
| try: | |
| site = list( | |
| map(lambda x: np.where(fieldNameList == x)[0][0], | |
| fieldName)) | |
| except: | |
| var_str = fieldName[0] | |
| for i in list(range(1, len(fieldName))): | |
| var_str += ',' + fieldName[i] | |
| p.error_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "在" + tableName + "数据包里找不到对应的" + var_str + "字段!") | |
| else: | |
| tmp = [0, 1, 2] | |
| tmp.extend(site) | |
| fieldData = fieldData[:, tmp] | |
| stockCode = self.getStockCode() | |
| IA_ret = np.ones([1, len(stockCode)]) | |
| fieldData = fieldData[np.where( | |
| fieldData[:, 1] <= nextDate)[0], :] | |
| ret = np.nan * np.zeros([len(site), len(stockCode)]) | |
| fieldData = fieldData[np.where( | |
| fieldData[:, 2] == reportDate)[0], :] | |
| if fieldData.size == 0: | |
| return ret | |
| else: | |
| for i in list(range(len(stockCode))): | |
| dataTemp = fieldData[np.where( | |
| fieldData[:, 0] == stockCode[i])[0]] | |
| if dataTemp.size == 0: | |
| IA_ret[0, i] = np.nan | |
| continue | |
| if np.shape(dataTemp)[0] > 1: | |
| dataTemp = dataTemp[np.argsort(dataTemp[:, 1])] | |
| for j in list(range(3, np.shape(dataTemp)[1])): | |
| ret[j - 3, i] = dataTemp[-1, j] | |
| if tableName != 'ASHARE_PROFITNOTICE': | |
| ret[np.where(np.isnan(ret))] = 0 | |
| ret = ret * IA_ret | |
| return ret | |
| def getFinancialFieldDataMatrix(self, tablename, fieldname, | |
| report_periods_list, datalen): | |
| ''' | |
| 获取财务数据矩阵用函数 | |
| :param tablename: char类型,表名 | |
| :param fieldname: char类型,字段名 | |
| :param report_periods_list: 1darray数组,报告期列表 | |
| :param datalen: int类型,数据行数 | |
| :return: np.array类型,财务数据矩阵 | |
| ''' | |
| ret = np.nan * np.zeros((int(datalen), len(self.getStockList()))) | |
| for i in range(datalen): | |
| try: | |
| ret[i] = self.getFinancialFieldData(tablename, fieldname, | |
| report_periods_list[i]) | |
| except: | |
| p.error_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "数据包导入失败!找不到数据包" + tablename + ",请更新数据包!") | |
| return ret | |
| def getFinancialFieldDataMatrixModified(self, value, tablename, fieldname, | |
| report_periods_list): | |
| ''' | |
| 注意:此函数对value进行操作,返回的是value的修正值,内存占用不变 | |
| 获取财务数据修正矩阵用函数 | |
| :param tablename: char类型,修正表名 | |
| :param fieldname: char类型,具体修正字段名 | |
| :param report_periods_list: 1darray数组,报告期列表 | |
| :return: np.array类型,财务数据矩阵 | |
| ''' | |
| datalen = min(3, value.shape[0]) | |
| if fieldname != 'NET_PROFIT_EXCL_MIN_INT_INC': | |
| ret = np.nan * np.zeros((datalen, len(self.getStockList()))) | |
| for i in range(datalen): | |
| try: | |
| ret[i] = self.getFinancialFieldData(tablename, fieldname, | |
| report_periods_list[i]) | |
| except: | |
| p.error_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "逐行报告期数据提取失败!") | |
| value[:datalen][np.where(np.isnan( | |
| value[:datalen]))] = ret[np.where(np.isnan(value[:datalen]))] | |
| return value | |
| else: | |
| ret_1 = np.nan * np.zeros((datalen, len(self.getStockList()))) | |
| for i in range(datalen): | |
| try: | |
| ret_1[i] = self.getFinancialFieldData(tablename, fieldname, | |
| report_periods_list[i]) | |
| except: | |
| p.error_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "逐行报告期数据提取失败!") | |
| ret_2 = np.nan * np.zeros((datalen, len(self.getStockList()))) | |
| for i in range(datalen): | |
| try: | |
| upDown = self.getFinancialFieldData('ASHARE_PROFITNOTICE', [ | |
| 'S_PROFITNOTICE_NETPROFITMIN', | |
| 'S_PROFITNOTICE_NETPROFITMAX' | |
| ], report_periods_list[i]) * 10000 | |
| ret_2[i] = np.nanmean(upDown, axis=0) | |
| except: | |
| p.error_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "字段为净利润,业绩预告逐行报告期数据提取失败!") | |
| value[:datalen][np.where(np.isnan( | |
| value[:datalen]))] = ret_1[np.where(np.isnan(value[:datalen]))] | |
| value[:datalen][np.where(np.isnan( | |
| value[:datalen]))] = ret_2[np.where(np.isnan(value[:datalen]))] | |
| return value | |
| def getFinancialFieldDataMatrixModified_gta(self, value, tablename, fieldname, | |
| report_periods_list): | |
| ''' | |
| 函数 | |
| 注意:此函数对value进行操作,返回的是value的修正值,内存占用不变 | |
| 获取财务数据修正矩阵用函数 | |
| :param tablename: char类型,修正表名 | |
| :param fieldname: char类型,具体修正字段名 | |
| :param report_periods_list: 1darray数组,报告期列表 | |
| :return: np.array类型,财务数据矩阵 | |
| ''' | |
| dic_fieldname = {'B0011': 'GROSSREVENUE', 'B0013': 'OPERATEPROFIT', 'B001': 'TOTALPROFIT', 'A001': 'ASSET' | |
| , 'A0031': 'EQUITYPARENT', 'A003': 'EQUITY', 'B0024': 'PROFITPARENT', 'B001101': 'GROSSREVENUE', | |
| 'B002': 'PROFIT'} | |
| fieldname = dic_fieldname[fieldname] | |
| datalen = min(3, value.shape[0]) | |
| if fieldname != 'PROFITPARENT' and 'PROFIT': | |
| ret = np.nan * np.zeros((datalen, len(self.getStockList()))) | |
| for i in range(datalen): | |
| try: | |
| ret[i] = self.getFinancialFieldData(tablename, fieldname, | |
| report_periods_list[i]) | |
| except: | |
| p.error_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "逐行报告期数据提取失败!") | |
| value[:datalen][np.where(np.isnan( | |
| value[:datalen]))] = ret[np.where(np.isnan(value[:datalen]))] | |
| return value | |
| elif fieldname == 'PROFITPARENT': # 归母净利润 | |
| ret_1 = np.nan * np.zeros((datalen, len(self.getStockList()))) | |
| for i in range(datalen): | |
| try: | |
| ret_1[i] = self.getFinancialFieldData(tablename, fieldname, | |
| report_periods_list[i]) | |
| except: | |
| p.error_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "逐行报告期数据提取失败!") | |
| ret_2 = np.nan * np.zeros((datalen, len(self.getStockList()))) | |
| for i in range(datalen): | |
| try: | |
| upDown = self.getFinancialFieldData('STK_FIN_FORECFIN', [ | |
| 'PROFITPARENTFLOOR', | |
| 'PROFITPARENTCEILING' | |
| ], report_periods_list[i]) | |
| ret_2[i] = np.nanmean(upDown, axis=0) | |
| except: | |
| p.error_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "字段为归母净利润,业绩预告逐行报告期数据提取失败!") | |
| value[:datalen][np.where(np.isnan( | |
| value[:datalen]))] = ret_1[np.where(np.isnan(value[:datalen]))] | |
| value[:datalen][np.where(np.isnan( | |
| value[:datalen]))] = ret_2[np.where(np.isnan(value[:datalen]))] | |
| return value | |
| elif fieldname == 'PROFIT': # 净利润 | |
| ret_1 = np.nan * np.zeros((datalen, len(self.getStockList()))) | |
| for i in range(datalen): | |
| try: | |
| ret_1[i] = self.getFinancialFieldData(tablename, fieldname, | |
| report_periods_list[i]) | |
| except: | |
| p.error_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "逐行报告期数据提取失败!") | |
| ret_2 = np.nan * np.zeros((datalen, len(self.getStockList()))) | |
| for i in range(datalen): | |
| try: | |
| upDown = self.getFinancialFieldData('STK_FIN_FORECFIN', [ | |
| 'PROFITFLOOR', | |
| 'PROFITCEILING' | |
| ], report_periods_list[i]) | |
| ret_2[i] = np.nanmean(upDown, axis=0) | |
| except: | |
| p.error_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "字段为净利润,业绩预告逐行报告期数据提取失败!") | |
| value[:datalen][np.where(np.isnan( | |
| value[:datalen]))] = ret_1[np.where(np.isnan(value[:datalen]))] | |
| value[:datalen][np.where(np.isnan( | |
| value[:datalen]))] = ret_2[np.where(np.isnan(value[:datalen]))] | |
| return value | |
| def getFinancialFieldDataMatrix_Q(self, value, report_periods_list): | |
| ''' | |
| 获取财务单季度数据矩阵用函数 | |
| :param value: ndarray类型,getFieldDataMatrix获得的财务数据矩阵 | |
| :param report_periods_list: 1darray数组,报告期列表 | |
| :return: np.array类型,财务单季度数据矩阵 | |
| ''' | |
| datalen = value.shape[0] | |
| ret = np.nan * np.zeros((datalen - 1, len(self.getStockList()))) | |
| for i in range(datalen - 1): | |
| try: | |
| if report_periods_list[i] % 10000 == 331: | |
| ret[i] = value[i] | |
| else: | |
| ret[i] = value[i] - value[i + 1] | |
| except: | |
| p.error_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "财务数据单季度计算失败!") | |
| return ret | |
| def getFinancialFieldDataMatrix_TTM(self, value, n): | |
| ''' | |
| 获取财务TTM数据矩阵用函数 | |
| :param value: ndarray类型,getFieldDataMatrix_Q获得的财务单季度数据矩阵 | |
| :param n: int类型,期数,默认为4 | |
| :return: np.array类型,财务TTM数据矩阵 | |
| ''' | |
| datalen = value.shape[0] | |
| ret = np.nan * np.zeros((datalen - (n - 1), len(self.getStockList()))) | |
| for i in range(datalen - (n - 1)): | |
| try: | |
| ret[i] = np.sum(value[i:(i + n), :], axis=0) | |
| except: | |
| p.error_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, | |
| "财务数据TTM计算失败!") | |
| return ret | |
| def getFirstNonnan(arr, axis, invalid_val): | |
| ''' | |
| 获得矩阵每行或者每列第一个非空值所在位置用函数 | |
| :param arr: ndarray类型 | |
| :param axis: 0/1 0为每列提取,1为每行提取 | |
| :param invalid_val: int/float,若行/列全空返回的数字 | |
| :return: 1darray数组 | |
| ''' | |
| mask = ~np.isnan(arr) | |
| return np.where(mask.any(axis=axis), mask.argmax(axis=axis), invalid_val) | |
| def getNewestData(arr): | |
| ''' | |
| 获取矩阵每一列第一个非空值用函数 | |
| :param arr: ndarray类型 | |
| :return: ndarray类型,一行矩阵 | |
| ''' | |
| ret = np.nan * np.zeros((1, arr.shape[1])) | |
| for i in range(arr.shape[0]): | |
| ret[0, np.where(np.isnan(ret[0]))[0]] = arr[i][np.where(np.isnan(ret[0]))[0]] | |
| return ret | |
| def getGrowthData(self, factor_list, dataLen, type): | |
| ''' | |
| 计算growth因子用函数 | |
| :param factor_list: ndarray类型,growth因子基础值矩阵 | |
| :param dataLen: int类型,默认为1,前后两期的间隔 | |
| :param type: char类型,默认为rate,计算的growth因子种类 | |
| :return: ndarray类型,一行矩阵 | |
| ''' | |
| factor_list = np.flipud(factor_list) | |
| if type == 'rate': | |
| growth = (factor_list[dataLen:] - factor_list[:-dataLen]) / np.abs(factor_list[:-dataLen]) | |
| elif type == 'value': | |
| growth = factor_list[dataLen:] - factor_list[:-dataLen] | |
| growth = growth.astype('float') | |
| else: | |
| p.warning_print(sys._getframe().f_code.co_filename, | |
| sys._getframe().f_code.co_name, "传入的type类型有误") | |
| return None | |
| growth[np.where(growth == np.inf)] = np.nan | |
| growth[np.where(growth == -np.inf)] = np.nan | |
| growth = np.flipud(growth) | |
| growth = self.getNewestData(growth) | |
| return growth | |