Skip to content

Commit

Permalink
0.9.53 优化 streamlit 组件
Browse files Browse the repository at this point in the history
  • Loading branch information
zengbin93 committed Jun 8, 2024
1 parent 7f8c970 commit 9d5b140
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
14 changes: 11 additions & 3 deletions czsc/utils/st_components.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ def show_monthly_return(df, ret_col="total", sub_title="月度累计收益", **k
:param df: pd.DataFrame,数据源
:param ret_col: str,收益列名
:param title: str,标题
:param sub_title: str,标题
:param kwargs:
"""
assert isinstance(df, pd.DataFrame), "df 必须是 pd.DataFrame 类型"
Expand All @@ -137,11 +137,19 @@ def show_monthly_return(df, ret_col="total", sub_title="月度累计收益", **k
monthly.columns = month_cols
monthly["年收益"] = monthly.sum(axis=1)

# 计算月度胜率和月度盈亏比
win_rate = monthly.apply(lambda x: (x > 0).sum() / len(x), axis=0)
ykb = monthly.apply(lambda x: x[x > 0].sum() / -x[x < 0].sum() if min(x) < 0 else 10, axis=0)
mean_ret = monthly.mean(axis=0)
dfy = pd.DataFrame([win_rate, ykb, mean_ret], index=["胜率", "盈亏比", "平均收益"])

monthly = monthly.style.background_gradient(cmap="RdYlGn_r", axis=None, subset=month_cols)
monthly = monthly.background_gradient(cmap="RdYlGn_r", axis=None, subset=["年收益"])
monthly = monthly.format("{:.2%}", na_rep="-")

st.dataframe(monthly, use_container_width=True)
dfy = dfy.style.background_gradient(cmap="RdYlGn_r", axis=1).format("{:.2%}", na_rep="-")
st.dataframe(dfy, use_container_width=True)
st.caption("注:月度收益为累计收益,胜率为月度收益大于0的占比,盈亏比为月度盈利总额与月度亏损总额的比值,如果月度亏损总额为0,则盈亏比为10")


def show_correlation(df, cols=None, method="pearson", **kwargs):
Expand Down Expand Up @@ -211,7 +219,7 @@ def show_sectional_ic(df, x_col, y_col, method="pearson", **kwargs):
if kwargs.get("show_cumsum_ic", True):
dfc["ic_cumsum"] = dfc["ic"].cumsum()
fig = go.Figure()
fig.add_trace(go.Scatter(x=dfc["dt"], y=dfc["ic"], mode="lines", name="IC", yaxis="y"))
fig.add_trace(go.Bar(x=dfc["dt"], y=dfc["ic"], name="IC", yaxis="y"))
fig.add_trace(
go.Scatter(x=dfc["dt"], y=dfc["ic_cumsum"], mode="lines", name="累计IC", yaxis="y2", line=dict(color="red"))
)
Expand Down
17 changes: 17 additions & 0 deletions examples/streamlit日收益分析组件使用案例.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import sys
sys.path.insert(0, r"A:\ZB\git_repo\waditu\czsc")
import czsc
import streamlit as st
import pandas as pd
import numpy as np

st.set_page_config(layout="wide")

df = pd.DataFrame({
"dt": pd.date_range("20210101", periods=1000),
"ret": np.random.randn(1000)
})

czsc.show_daily_return(df)

czsc.show_monthly_return(df, ret_col="ret")

0 comments on commit 9d5b140

Please sign in to comment.