分享

streamlit量化选择etf:可视化界面实现

 AI量化实验室 2023-10-12 发布于北京

原创文章第132篇,专注“个人成长与财富自由、世界运作的逻辑,AI量化投资”。

本以为本周的早高峰人会变多,因为有大量的公司要开始复工,结果似乎没有发生。所以,“大家做自己健康的第一责任人”是没有问题的,而且很多店铺自己就把店关了,多数人都自觉戴上了N95,自觉保持社交距离。——也许这就是“市场经济”的力量吧,你越不管,“自觉”的力量就觉醒了。

今天把etf的列表可视化出来,人是视觉动物,可视化非常重要。

看下效果:

01 从tushare下载场内基金基本信息

A股场内基金一共1700多支(比场外基金少多了),退市的500多支,可交易的1205支

# ================ basic =========================
def download_etfs_basic():
# 拉取数据
df = pro.fund_basic(**{
"ts_code": "",
"market": "E",
"update_flag": "",
"offset": "",
"limit": "",
"status": "L",
"name": ""
}, fields=[
"ts_code",
"name",
"management",
"custodian",
"fund_type",
"found_date",
"due_date",
"list_date",
"issue_date",
"delist_date",
"issue_amount",
"m_fee",
"c_fee",
"duration_year",
"p_value",
"min_amount",
"exp_return",
"benchmark",
"status",
"invest_type",
"type",
"trustee",
"purc_startdate",
"redm_startdate",
"market"
])
df.rename(columns={'ts_code': 'code'}, inplace=True)
df.sort_values(by='list_date', inplace=True)
df.set_index('code', inplace=True)
return df

调用的代码,写入hdf5:

from engine.config import DATA_DIR_HDF5_ALL, DATA_DIR_HDF5_BASIC
basic = download_etfs_basic()
print(basic)

with pd.HDFStore(DATA_DIR_HDF5_BASIC.resolve()) as store:
store['etfs'] = download_etfs_basic()

结果显示:(最早的etf,上市时间是2004年底)

02 streamlit读出并查询etfs

@staticmethod
def load_etfs_basic():
with pd.HDFStore(DATA_DIR_HDF5_BASIC.resolve()) as store:
return store['etfs']

03 界面布局

col_indicators, col_corr = st.columns(2)
col_indicators.subheader('风险收益指标')
col_indicators.table(DataUtils.calc_indicators(df_returns))

col_corr.subheader('相关系数')
col_corr.table(df_returns.corr())

核心代码就是st.columns(N),即可以横向布局:

04 etf筛选

这里使用了streamlit的多页面:

只需要在main.py的同级目录下,创建一个pages,然后里面的xx.py都会自动生成一个页面:

多级联动也非常简单,主要使用pandas的query查询语法:

import streamlit as st
from engine.data_utils import DataUtils
from engine.logic import Logic

st.header('etf分析')


@st.cache
def load_etfs():
return Logic.load_etfs_basic()


col_fund, col2_invest = st.columns(2)
# 基金类型
df = load_etfs()
total = len(df)
fund_type = col_fund.selectbox('基金类型:', options=df['fund_type'].unique())

df = df.query("fund_type == '{}'".format(fund_type))
invest_type = col2_invest.selectbox('投资类型:', options=df['invest_type'].unique())
df = df.query("invest_type == '{}'".format(invest_type, fund_type))

col1, col2 = st.columns(2)
col1.metric("场内基金总数", total)
col2.metric("当前数量", len(df))
st.table(df)

streamlit特别适合数据驱动型,机器学习型的项目,尤其是用于演示类的需求。后续可以把etf的一些指标计算比如,比如20日动量等,即可以支持指标选基金。

代码和数据已经上传至星球-量化专栏。

近期文章:

多策略风险收益对比——风险平价,动量以及RSRS

wxpython+streamlit:AI量化平台更新gui

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约