Skip to content

Commit

Permalink
Merge pull request #799 from ricequant/dev-rqsdk-661
Browse files Browse the repository at this point in the history
summary新增个股权重分析
  • Loading branch information
Cuizi7 committed Jun 9, 2023
2 parents a4ebaea + ba49a61 commit cdfeb8d
Show file tree
Hide file tree
Showing 5 changed files with 32 additions and 4 deletions.
2 changes: 1 addition & 1 deletion rqalpha/apis/api_rqdatac.py
Original file line number Diff line number Diff line change
Expand Up @@ -1039,7 +1039,7 @@ def _futures_get_dominant_price(
""" 获取主力合约行情数据
:param underlying_symbols: 期货合约品种,可传入 underlying_symbol, underlying_symbol list
:param start_date: 开始日期, 最小日期为 20210104
:param start_date: 开始日期, 最小日期为 20100104
:param end_date: 结束日期
:param frequency: 历史数据的频率。 支持/日/分钟/tick 级别的历史数据,默认为'1d'。
1m- 分钟线,1d-日线,分钟可选取不同频率,例如'5m'代表 5 分钟线
Expand Down
21 changes: 21 additions & 0 deletions rqalpha/mod/rqalpha_mod_sys_analyser/mod.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,7 @@ def _to_position_record(self, date, order_book_id, long, short):
for direction_prefix, pos in direction_pos_iter:
data[direction_prefix + "_pnl"] = self._safe_convert(getattr(pos, "pnl", None))
data[direction_prefix + "_margin"] = self._safe_convert(pos.margin)
data[direction_prefix + "_market_value"] = self._safe_convert(pos.market_value)
data[direction_prefix + "_quantity"] = self._safe_convert(pos.quantity)
data[direction_prefix + "_avg_open_price"] = self._safe_convert(getattr(pos, "avg_price", None))
return data
Expand Down Expand Up @@ -489,6 +490,26 @@ def tear_down(self, code, exception=None):
df = df.set_index("date").sort_index()
result_dict["{}_positions".format(account_name)] = df

# 个股权重
df_list = []
need_cols = ["order_book_id", "market_value"]
for table_name in ["stock_positions", "future_positions"]:
if table_name not in result_dict:
continue
table = result_dict[table_name]
for field in ["market_value", "LONG_market_value", "SHORT_market_value"]:
if field not in table.columns:
continue
df_list.append(table.rename(columns={field: "market_value"})[need_cols])
if len(df_list) > 0:
positions_weight_df = pd.concat(df_list).dropna()
positions_weight_df["total_value"] = positions_weight_df.groupby(by="date")["market_value"].sum()
positions_weight_df["weight"] = positions_weight_df["market_value"] / positions_weight_df["total_value"]
positions_weight_df = positions_weight_df.groupby(by="date")["weight"].describe()
else:
positions_weight_df = pd.DataFrame(columns=["count", "mean", "std", "min", "25%", "50%", "75%", "max"])
positions_weight_df = positions_weight_df.reindex(total_portfolios.index).fillna(value=0)
result_dict["positions_weight"] = positions_weight_df
result_dict["yearly_risk_free_rates"] = dict(_get_yearly_risk_free_rates(data_proxy, start_date, end_date))

if self._mod_config.output_file:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,8 @@ class SummaryTemplate(ExcelTemplate):
"概览": SingleCellSchema,
"年度指标": VerticalSeriesSchema,
"月度收益": VerticalSeriesSchema,
"月度超额收益(几何)": VerticalSeriesSchema
"月度超额收益(几何)": VerticalSeriesSchema,
"个股权重": VerticalSeriesSchema,
}


Expand Down
10 changes: 8 additions & 2 deletions rqalpha/mod/rqalpha_mod_sys_analyser/report/report.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,11 @@ def _monthly_geometric_excess_returns(p_returns: Series, b_returns: Optional[Ser
return ChainMap({str(c): data[c] for c in data.columns}, {"year": data.index})


def _gen_positions_weight(df):
rename = {"{}%".format(i): "percent_{}".format(i) for i in [25, 50, 75]}
return df.reset_index().rename(columns=rename).to_dict(orient="list")


def generate_report(result_dict, output_path):
from six import StringIO

Expand All @@ -128,11 +133,12 @@ def generate_report(result_dict, output_path):
"概览": summary,
"年度指标": _yearly_indicators(p_nav, p_returns, b_nav, b_returns, result_dict["yearly_risk_free_rates"]),
"月度收益": _monthly_returns(p_returns),
"月度超额收益(几何)": _monthly_geometric_excess_returns(p_returns, b_returns)
"月度超额收益(几何)": _monthly_geometric_excess_returns(p_returns, b_returns),
"个股权重": _gen_positions_weight(result_dict["positions_weight"]),
}, output_path)

for name in ["portfolio", "stock_account", "future_account",
"stock_positions", "future_positions", "trades"]:
"stock_positions", "future_positions", "trades", "positions_weight"]:
try:
df = result_dict[name]
except KeyError:
Expand Down
Binary file not shown.

0 comments on commit cdfeb8d

Please sign in to comment.