Package: pyquantfin
nav_calcIt is a lib for backtesting.multi_assetsThis function is used to test strategies involving mutliple assets, like multi-factors model.params:prz: dataframe, index = dates, columns = stocksw_tar: dataframe, target weight, index = dates, columns = stocksIt is worthwhile to note that the dates in w_tar does not need to be the same as the dates in prz, it can be a subset of the dates in prz.dates_reb: array, rebalance datesIf you want to balance at every w_tar's dates, set dates_reb to w_tar.indexfee: fee rate, default = 0return a dataframeIt has the following columns:reb: 1 indicate it is a rebalance date, 0 for not a rebalance dateret_gross: return before feefee: fees to substract from ret_grossret_net: return after feenav: net asset value of the strategytime_seriesThis function is used to test timing strategies, like CTA strategies.params:prz: arraypos: array, indicate the strategy's positionIt must be the same size with przfee: fee rate, default 0ret_ext: whether to return the extended information; if False(default), return an array which represents the nav of the strategy; if True, return a DataFrame(see below)return a dataframe(ret_ext = True)It has the following columns:price: the price of the underlying assetposition: the strategy's positionreturn: pct_change of the pricevalue: position * pricefee: trading feesstrategy_return_before_fee:strategy_return: post-fee returnnav: nav of the strategy (post_fee)nav_before_fee:nav_price: the normalized pricenav_analysisIt is a lib for analysis nav (which maybe from nav_calc).calc_mddFunction to calculate max drawdownparamsarr: an array that represents nav or pricereturn a dictThe dict has the following keys:mdd_value: the max drawdown in valuemdd_pct: the max drawdown in percentagecalc_ann_retFunction to calculate the annualized return, assuming daily data.parmasarr: an array that represents nav or pricereturn a valueannualized returnstatsFunction to return both ret and mddparamsarr: an array that represents nav or pricereturn a dict which has the following keysret: the total return (not annualized return)mdd: the max drawdown in percentagestats_yearlyparamss: a series that represents nav or priceThe index of s should be date and must be in the form like "20181010".return a dataframe which has the following columns:ret: the total return (not annualized return)mdd: the max drawdown in percentageThe index of the dataframe is 'year'.stats_yearly_multi_assetsparamsdf: a dataframe whose each column represents a nav of an asset or strategy.return a dataframe which has two-level columnsLevel I: the asset or strategyLevel II: ret and mdd, the same meaning as in stats_yearlygeneralto_db_codeparamsts_code: security code like '600000.SH'returndb_code: code format in database like 'SH_600000'exampleto_db_code('600000.SH') returns 'SH_600000'to_ts_codeparams:db_code: code format in database like 'SH_600000'return:ts_code: security code like '600000.SH'example:to_ts_code('SH_600000') returns '600000.SH'real_round_2precise round to 0.01  (用于计算涨跌停价)parama numberreturnnumber roundedexample-read_round_2(5.347) returns 5.35check_df_structcheck if two dataframe have identical struct: same shape, same index and same columnsparamsdf1, df2returnTrue if the two dataframe have the same shape, same index and same columns, else Falseexamplecheck_df_struct(df1, df2)utilsgrouping1dassign groupid to an array, used to group stocks according a factorparamsarr: the factor arraynog: number of groupST = 999: the number need to be specially treatedreturnan array that contained groupid, nan will be assigned to the 0 group, ST will be assigned to the -1 groupexamplegrouping1d(np.arange(100),5)get_clean_factor_and_forward_returnsparamfactor: a mult-index series with index = ['date', 'asset'], value = factor valueprices: a dataframe with index = daily dates and columns = the universe of stocks interestedbins = 5: number of group (use bins as the variable name in order to be consistence with alphalens)periods = (20,60): the holding periods to be testedreturna multi-index dataframe with index = ['date', 'asset'] and columns:XD(i.e. 20D, 60D,...): the forward returnfactor: the factor valuefactor_quantile: the group id (also, to be consistence with alphalens)examplefactor_data = get_clean_factor_and_forward_returns(factor, prices)referencealphalens:http://quantopian.github.io/alphalens/index.htmlconvert_date_in_factor_dataconvert the type of index 'date' in factor_data to datetimeparamfactor_data: with be changed inplacereturnNoneexampleconvert_date_in_factor_data(factor_data)SAArisk_budgetparamsdata: the DataFrame consists of asset price datab: the risk budget (list or array)returna Series representing the weightsrisk_budget_weight_resampleparamsdata: the DataFrame consists of asset price datab: the risk budget (list or array)lb: the lookback periodfreq: the rebalace frequency (str or int)returna DataFrame representing the weights at each rebalance daterisk_parityparamsdata: the DataFrame consists of asset price datareturna Series representing the weightsrp_weight_resampleparamsdata: the DataFrame consists of asset price datalb: the lookback periodfreq: the rebalace frequency (str or int)returna DataFrame representing the weights at each rebalance dateequalweight_resampleparamsdata: the DataFrame consists of asset price datafreq: the rebalace frequency (str or int)returna DataFrame representing the weights at each rebalance datecalc_navparamsdata: the DataFrame consists of asset price datawegiths: the DataFrame representing the weights at each rebalance datefee: fee ratereturndf_nav: a DataFrame the contains the backtested nav of the strategydf: a muli_level DataFrame that contains the raw data, the weights and the period return of that assets, at each rebalace datacta有关 CTA 研究的方法get_pos_1l当价格位于指标线上方时，做多；当价格位于指标线下方时，做空。params:prz: arrayline: array，指标线。也可以为标量，表示水平线。return an array仓位get_pos_2l当价格位于  upper 上方时，做多；当价格位于  lower 下方时，做空。params:prz: arrayupper / lower: array，指标线。也可以为标量，表示水平线。return an array仓位get_pos_3l当价格位于  upper 上方时，做多；下穿 mid 时平仓。当价格位于  lower 下方时，做空；上穿 mid 时平仓。注意，做多时有可能直接下穿 lower，此时应平多做空，反之亦然。params:prz: arrayupper / lower / mid: array，指标线。也可以为标量，表示水平线。return an array仓位