Beispiel #1
0
 def _output(self):
     Output = {}
     for i, iAccount in enumerate(self.Accounts):
         iOutput = iAccount.output()
         if iOutput: Output[str(i)+"-"+iAccount.Name] = iOutput
     AccountValueSeries, CashSeries, DebtSeries, InitCash, DebtRecord, CashRecord = 0, 0, 0, 0, None, None
     for iAccount in self.Accounts:
         AccountValueSeries += iAccount.getAccountValueSeries()
         CashSeries += iAccount.getCashSeries()
         DebtSeries += iAccount.getDebtSeries()
         InitCash += iAccount.InitCash
         DebtRecord = iAccount.DebtRecord.append(DebtRecord)
         CashRecord = iAccount.CashRecord.append(CashRecord)
     DebtRecord = DebtRecord[DebtRecord["融资"]!=0]
     StrategyOutput = genAccountOutput(InitCash, CashSeries, DebtSeries, AccountValueSeries, CashRecord, DebtRecord, self._Model.DateIndexSeries)
     StrategyOutput["统计数据"] = StrategyOutput["统计数据"].rename(columns={"账户价值": "策略表现", "无杠杆价值": "无杠杆表现"})
     if self.Benchmark.FactorTable is not None:# 设置了基准
         BenchmarkPrice = self.Benchmark.FactorTable.readData(factor_names=[self.Benchmark.PriceFactor], dts=AccountValueSeries.index.tolist(), ids=[self.Benchmark.BenchmarkID]).iloc[0,:,0]
         BenchmarkOutput = pd.DataFrame(calcYieldSeq(wealth_seq=BenchmarkPrice.values), index=BenchmarkPrice.index, columns=["基准收益率"])
         BenchmarkOutput["基准累计收益率"] = BenchmarkOutput["基准收益率"].cumsum()
         BenchmarkOutput["基准净值"] = BenchmarkPrice / BenchmarkPrice.iloc[0]
         if DebtRecord.shape[0]>0:
             LYield = (StrategyOutput["日期序列"]["无杠杆收益率"].values if "时间序列" not in StrategyOutput else StrategyOutput["时间序列"]["无杠杆收益率"].values)
         else:
             LYield = (StrategyOutput["日期序列"]["收益率"].values if "时间序列" not in StrategyOutput else StrategyOutput["时间序列"]["收益率"].values)
         if not self.Benchmark.RebalanceDTs: RebalanceIndex = None
         else:
             RebalanceIndex = pd.Series(np.arange(BenchmarkOutput["基准收益率"].shape[0]), index=BenchmarkOutput["基准收益率"].index, dtype=int)
             RebalanceIndex = RebalanceIndex.loc[RebalanceIndex.index.intersection(self.Benchmark.RebalanceDTs)].values.tolist()
         BenchmarkOutput["相对收益率"] = calcLSYield(long_yield=LYield, short_yield=BenchmarkOutput["基准收益率"].values, rebalance_index=RebalanceIndex)
         BenchmarkOutput["相对累计收益率"] = BenchmarkOutput["相对收益率"].cumsum()
         BenchmarkOutput["相对净值"] = (1 + BenchmarkOutput["相对收益率"]).cumprod()
         if "时间序列" in StrategyOutput:
             StrategyOutput["时间序列"] = pd.merge(StrategyOutput["时间序列"], BenchmarkOutput, left_index=True, right_index=True)
             BenchmarkOutput = BenchmarkOutput.iloc[self._Model.DateIndexSeries.values]
             BenchmarkOutput["基准收益率"] = BenchmarkOutput["基准净值"].values / np.r_[1, BenchmarkOutput["基准净值"].iloc[:-1].values] - 1
             BenchmarkOutput["基准累计收益率"] = BenchmarkOutput["基准收益率"].cumsum()
             BenchmarkOutput["相对收益率"] = BenchmarkOutput["相对净值"].values / np.r_[1, BenchmarkOutput["相对净值"].iloc[:-1].values] - 1
             BenchmarkOutput["相对累计收益率"] = BenchmarkOutput["相对收益率"].cumsum()
         BenchmarkOutput.index = StrategyOutput["日期序列"].index
         StrategyOutput["日期序列"] = pd.merge(StrategyOutput["日期序列"], BenchmarkOutput, left_index=True, right_index=True)
         BenchmarkStatistics = summaryStrategy(BenchmarkOutput[["基准净值", "相对净值"]].values, list(BenchmarkOutput.index), init_wealth=[1, 1])
         BenchmarkStatistics.columns = ["基准", "相对表现"]
         StrategyOutput["统计数据"] = pd.merge(StrategyOutput["统计数据"], BenchmarkStatistics, left_index=True, right_index=True)
     Output["Strategy"] = StrategyOutput
     return Output
Beispiel #2
0
def genAccountOutput(init_cash, cash_series, debt_series, account_value_series,
                     debt_record, date_index):
    Output = {}
    # 以时间点为索引的序列
    Output["时间序列"] = pd.DataFrame(cash_series, columns=["现金"])
    Output["时间序列"]["负债"] = debt_series
    Output["时间序列"]["证券"] = account_value_series - (cash_series - debt_series)
    Output["时间序列"]["账户价值"] = account_value_series
    AccountEarnings = account_value_series.diff()
    AccountEarnings.iloc[0] = account_value_series.iloc[0] - init_cash
    Output["时间序列"]["收益"] = AccountEarnings
    PreAccountValue = np.r_[init_cash, account_value_series.values[:-1]]
    AccountReturn = AccountEarnings / np.abs(PreAccountValue)
    AccountReturn[AccountEarnings == 0] = 0.0
    Output["时间序列"]["收益率"] = AccountReturn
    AccountReturn[np.isinf(AccountReturn)] = np.nan
    Output["时间序列"]["累计收益率"] = AccountReturn.cumsum()
    Output["时间序列"]["净值"] = (AccountReturn + 1).cumprod()
    DebtDelta = debt_record.groupby(by=["时间点"]).sum()["融资"]
    PreUnleveredValue = pd.Series(np.r_[init_cash,
                                        (account_value_series.values +
                                         debt_series.values)[:-1]],
                                  index=AccountEarnings.index)
    PreUnleveredValue[DebtDelta.index] += DebtDelta.clip(0, np.inf)
    UnleveredReturn = AccountEarnings / np.abs(PreUnleveredValue)
    UnleveredReturn[AccountEarnings == 0] = 0.0
    Output["时间序列"]["无杠杆收益率"] = UnleveredReturn
    UnleveredReturn[np.isinf(UnleveredReturn)] = np.nan
    Output["时间序列"]["无杠杆累计收益率"] = UnleveredReturn.cumsum()
    Output["时间序列"]["无杠杆净值"] = (1 + UnleveredReturn).cumprod()
    # 以日期为索引的序列
    if date_index.shape[0] == Output["时间序列"].shape[
            0]:  # 判断回测序列为日级别, 直接将时间点索引更改为日期索引
        Output["日期序列"] = Output.pop("时间序列")
        Output["日期序列"].index = date_index.index
    else:
        Output["日期序列"] = Output["时间序列"].iloc[date_index.values].copy()
        Output["日期序列"].index = date_index.index
        AccountValueSeries = Output["日期序列"]["账户价值"]
        DebtSeries = Output["日期序列"]["负债"]
        AccountEarnings = AccountValueSeries.diff()
        AccountEarnings.iloc[0] = AccountValueSeries.iloc[0] - init_cash
        Output["日期序列"]["收益"] = AccountEarnings
        PreAccountValue = np.append(np.array(init_cash),
                                    AccountValueSeries.values[:-1])
        AccountReturn = AccountEarnings / np.abs(PreAccountValue)
        AccountReturn[AccountEarnings == 0] = 0.0
        Output["日期序列"]["收益率"] = AccountReturn
        AccountReturn[np.isinf(AccountReturn)] = np.nan
        Output["日期序列"]["累计收益率"] = AccountReturn.cumsum()
        Output["日期序列"]["净值"] = (AccountReturn + 1).cumprod()
        debt_record = debt_record.copy()
        debt_record["时间点"] = [
            iDateTime.date() for iDateTime in debt_record["时间点"]
        ]
        DebtDelta = debt_record.groupby(by=["时间点"]).sum()["融资"]
        PreUnleveredValue = pd.Series(np.append(np.array(init_cash),
                                                (AccountValueSeries.values +
                                                 DebtSeries.values)[:-1]),
                                      index=AccountEarnings.index)
        PreUnleveredValue[DebtDelta.index] += DebtDelta.clip(0, np.inf)
        UnleveredReturn = AccountEarnings / np.abs(PreUnleveredValue)
        UnleveredReturn[AccountEarnings == 0] = 0.0
        Output["日期序列"]["无杠杆收益率"] = UnleveredReturn
        UnleveredReturn[np.isinf(UnleveredReturn)] = np.nan
        Output["日期序列"]["无杠杆累计收益率"] = UnleveredReturn.cumsum()
        Output["日期序列"]["无杠杆净值"] = (1 + UnleveredReturn).cumprod()
    # 统计数据
    Output["统计数据"] = summaryStrategy(Output["日期序列"][["净值", "无杠杆净值"]].values,
                                     list(Output["日期序列"].index),
                                     init_wealth=[1, 1])
    Output["统计数据"].columns = ["账户价值", "无杠杆价值"]
    return Output
Beispiel #3
0
def genAccountOutput(init_cash,
                     cash_series,
                     debt_series,
                     account_value_series,
                     cash_record,
                     debt_record,
                     date_index,
                     risk_free_rate=0.0):
    Output = {}
    # 以时间点为索引的序列
    Output["时间序列"] = pd.DataFrame(cash_series, columns=["现金"])
    Output["时间序列"]["负债"] = debt_series
    Output["时间序列"]["证券"] = account_value_series - (cash_series - debt_series)
    Output["时间序列"]["账户价值"] = account_value_series
    AccountEarnings = account_value_series.diff()
    AccountEarnings.iloc[0] = account_value_series.iloc[0] - init_cash
    # 现金流调整
    CashDelta = cash_record.loc[:, ["时间点", "现金流"]].groupby(
        by=["时间点"]).sum()["现金流"]
    CashDelta = CashDelta[CashDelta != 0]
    if CashDelta.shape[0] > 0:
        Output["时间序列"]["累计资金投入"] = init_cash + CashDelta.loc[
            Output["时间序列"].index].fillna(0).cumsum()
    else:
        Output["时间序列"]["累计资金投入"] = init_cash
    AccountEarnings[CashDelta.index] -= CashDelta
    Output["时间序列"]["收益"] = AccountEarnings
    PreAccountValue = np.r_[init_cash, account_value_series.values[:-1]]
    AccountReturn = AccountEarnings / np.abs(PreAccountValue)
    AccountReturn[AccountEarnings == 0] = 0.0
    Output["时间序列"]["收益率"] = AccountReturn
    AccountReturn[np.isinf(AccountReturn)] = np.nan
    Output["时间序列"]["累计收益率"] = AccountReturn.cumsum()
    Output["时间序列"]["净值"] = (AccountReturn + 1).cumprod()
    if CashDelta.shape[0] > 0:
        Output["时间序列"]["考虑资金投入的累计收益率"] = Output["时间序列"]["账户价值"] / Output[
            "时间序列"]["累计资金投入"] - 1
        Output["时间序列"]["考虑资金投入的净值"] = Output["时间序列"]["考虑资金投入的累计收益率"] + 1
    # 负债调整
    debt_record = debt_record[debt_record["融资"] != 0]
    if debt_record.shape[0] > 0:
        DebtDelta = debt_record.loc[:, ["时间点", "融资"]].groupby(
            by=["时间点"]).sum()["融资"]
        PreUnleveredValue = pd.Series(np.r_[init_cash,
                                            (account_value_series.values +
                                             debt_series.values)[:-1]],
                                      index=AccountEarnings.index)
        PreUnleveredValue[DebtDelta.index] += DebtDelta.clip(0, np.inf)
        UnleveredReturn = AccountEarnings / np.abs(PreUnleveredValue)
        UnleveredReturn[AccountEarnings == 0] = 0.0
        Output["时间序列"]["无杠杆收益率"] = UnleveredReturn
        UnleveredReturn[np.isinf(UnleveredReturn)] = np.nan
        Output["时间序列"]["无杠杆累计收益率"] = UnleveredReturn.cumsum()
        Output["时间序列"]["无杠杆净值"] = (1 + UnleveredReturn).cumprod()
    # 以日期为索引的序列
    if date_index.shape[0] == Output["时间序列"].shape[
            0]:  # 判断回测序列为日级别, 直接将时间点索引更改为日期索引
        Output["日期序列"] = Output.pop("时间序列")
        Output["日期序列"].index = date_index.index
    else:
        Output["日期序列"] = Output["时间序列"].iloc[date_index.values].copy()
        Output["日期序列"].index = date_index.index
        AccountValueSeries = Output["日期序列"]["账户价值"]
        DebtSeries = Output["日期序列"]["负债"]
        AccountEarnings = AccountValueSeries.diff()
        AccountEarnings.iloc[0] = AccountValueSeries.iloc[0] - init_cash
        # 现金流调整
        cash_record = cash_record.copy()
        cash_record["时间点"] = [
            iDateTime.date() for iDateTime in cash_record["时间点"]
        ]
        CashDelta = cash_record.loc[:, ["时间点", "现金流"]].groupby(
            by=["时间点"]).sum()["现金流"]
        CashDelta = CashDelta[CashDelta != 0]
        if CashDelta.shape[0] > 0:
            Output["日期序列"]["累计资金投入"] = init_cash + CashDelta.loc[
                Output["日期序列"].index].fillna(0).cumsum()
        else:
            Output["日期序列"]["累计资金投入"] = init_cash
        AccountEarnings[CashDelta.index] -= CashDelta
        Output["日期序列"]["收益"] = AccountEarnings
        PreAccountValue = np.append(np.array(init_cash),
                                    AccountValueSeries.values[:-1])
        AccountReturn = AccountEarnings / np.abs(PreAccountValue)
        AccountReturn[AccountEarnings == 0] = 0.0
        Output["日期序列"]["收益率"] = AccountReturn
        AccountReturn[np.isinf(AccountReturn)] = np.nan
        Output["日期序列"]["累计收益率"] = AccountReturn.cumsum()
        Output["日期序列"]["净值"] = (AccountReturn + 1).cumprod()
        if CashDelta.shape[0] > 0:
            Output["日期序列"]["考虑资金投入的累计收益率"] = Output["日期序列"]["账户价值"] / Output[
                "日期序列"]["累计资金投入"] - 1
            Output["日期序列"]["考虑资金投入的净值"] = Output["日期序列"]["考虑资金投入的累计收益率"] + 1
        # 负债调整
        if debt_record.shape[0] > 0:
            debt_record = debt_record.copy()
            debt_record["时间点"] = [
                iDateTime.date() for iDateTime in debt_record["时间点"]
            ]
            DebtDelta = debt_record.loc[:, ["时间点", "融资"]].groupby(
                by=["时间点"]).sum()["融资"]
            PreUnleveredValue = pd.Series(np.append(
                np.array(init_cash),
                (AccountValueSeries.values + DebtSeries.values)[:-1]),
                                          index=AccountEarnings.index)
            PreUnleveredValue[DebtDelta.index] += DebtDelta.clip(0, np.inf)
            UnleveredReturn = AccountEarnings / np.abs(PreUnleveredValue)
            UnleveredReturn[AccountEarnings == 0] = 0.0
            Output["日期序列"]["无杠杆收益率"] = UnleveredReturn
            UnleveredReturn[np.isinf(UnleveredReturn)] = np.nan
            Output["日期序列"]["无杠杆累计收益率"] = UnleveredReturn.cumsum()
            Output["日期序列"]["无杠杆净值"] = (1 + UnleveredReturn).cumprod()
    # 统计数据
    TargetCols = ["净值"] + ["考虑资金投入的净值"] * (
        CashDelta.shape[0] > 0) + ["无杠杆净值"] * (debt_record.shape[0] > 0)
    Output["统计数据"] = summaryStrategy(Output["日期序列"][TargetCols].values,
                                     list(Output["日期序列"].index),
                                     init_wealth=[1] * len(TargetCols),
                                     risk_free_rate=risk_free_rate)
    Output["统计数据"].columns = ["绝对表现"] + ["考虑资金投入的表现"] * (
        CashDelta.shape[0] > 0) + ["无杠杆表现"] * (debt_record.shape[0] > 0)
    return Output