1.购买服务器阿里云:服务器购买地址https://t.aliyun.com/U/Bg6shY若失效,可用地址
阿里云:
服务器购买地址
https://t.aliyun.com/U/Bg6shY若失效,可用地址
https://www.aliyun.com/daily-act/ecs/activity_selection?source=5176.29345612&userCode=49hts92d腾讯云:
https://curl.qcloud.com/wJpWmSfU若失效,可用地址
https://cloud.tencent.com/act/cps/redirect?redirect=2446&cps_key=ad201ee2ef3b771157f72ee5464b1fea&from=console华为云
https://activity.huaweicloud.com/cps.html?fromacct=64b5cf7cc11b4840bb4ed2ea0b2f4468&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=2019052.部署教程
3.代码如下
import datetimeimport akshare as akimport baostock as bsimport pandas as pd# 判断当前日期属于哪个季度def last_quarter():today = datetime.date.today()month = today.monthif 1 <= month <= 3:quarter = 4year = today.year - 1else:quarter = (month - 1) // 3year = today.yearreturn quarter, yeardef hk_index_pe_pb_div(index_code = "159699"):hk_consumer = ak.fund_portfolio_hold_em(symbol=index_code, date="202511")quarter,year = last_quarter()quarterStr = f"{year}年{quarter}季度"# 获取当前季度数据,保存为df1df1 = hk_consumer[hk_consumer['季度'].astype(str).str.contains(quarterStr)]# 获取当前季度前10名持仓top10_current_quarter = df1.sort_values(by='占净值比例', ascending=False).head(10)print(top10_current_quarter)# 获取第二季度数据quarterStr2 = f"{year}年2季度"df2 = hk_consumer[hk_consumer['季度'].astype(str).str.contains(quarterStr2)]# 获取第二季度后40名持仓tail40_q2 = df2.sort_values(by='占净值比例', ascending=True).head(40)# 合并第二季度后40名和当前季度前10名持仓merged_df = pd.concat([top10_current_quarter, tail40_q2], ignore_index=True)#print(merged_df)pe_list = []pb_list = []div_list = []weight_list = []for idx, row in merged_df.iterrows():stock_code = row["股票代码"]weight = row["占净值比例"]stock_info = ak.stock_hk_financial_indicator_em(stock_code)pe = stock_info["市盈率"]pb = stock_info["市净率"]stock_info["股息率TTM(%)"].iloc[0]val = stock_info["股息率TTM(%)"].iloc[0]if val is None or pd.isna(val):div = 0else:div = float(val)#print(stock_code, " 股息率: ", stock_code, div)pe_list.append(pe * weight)pb_list.append(pb * weight)div_list.append(div * weight)weight_list.append(weight)total_weight = sum(weight_list)print(total_weight)weight_pe = sum(pe_list)/total_weightweight_pb = sum(pb_list)/total_weightweight_div = sum(div_list)/total_weightprint("指数加权市盈率: ", weight_pe)print("指数加权市净率: ", weight_pb)print("指数加权股息率: ", weight_div)hk_index_pe_pb_div("159699")index_stock_info_df = ak.index_stock_info()hl = ak.stock_zh_index_value_csindex(symbol="000922")#print(hl.iloc[0])a_drink = ak.stock_zh_index_value_csindex(symbol="930653")#print(a_drink.iloc[0])bank = ak.stock_zh_index_value_csindex(symbol="399986")#print(bank.iloc[0])#result = index_stock_info_df[index_stock_info_df['index_code'] == '000922']#print(result)#查询指数的成份股信息#index_stock_cons_csindex_df = ak.index_stock_cons_csindex(symbol="000922")#print(index_stock_cons_csindex_df.iloc[0])# 查询指数成份股的权重信息index_stock_cons_weight_csindex_df = ak.index_stock_cons_weight_csindex(symbol="000922")'''# 获取每只成分股的市盈率、市净率、股息率pe_list = []pb_list = []div_list = []weight_list = []for idx, row in index_stock_cons_weight_csindex_df.iterrows():stock_code = row["成分券代码"]weight = float(row["权重"])/ 100try:stock_info = ak.stock_market_pb_lg(symbol=stock_code)pe = float(stock_info["市盈率TTM"][0]) if not index_stock_cons_weight_csindex_df.isna(stock_info["市盈率TTM"][0]) else 0pb = float(stock_info["市净率"][0]) if not index_stock_cons_weight_csindex_df.isna(stock_info["市净率"][0]) else 0div = float(stock_info["股息率"][0]) if not index_stock_cons_weight_csindex_df.isna(stock_info["股息率"][0]) else 0except Exception as e:pe, pb, div = 0, 0, 0pe_list.append(pe * weight)pb_list.append(pb * weight)div_list.append(div * weight)weight_list.append(weight)# 计算加权平均total_weight = sum(weight_list)weighted_pe = sum(pe_list) / total_weight if total_weight > 0 else 0weighted_pb = sum(pb_list) / total_weight if total_weight > 0 else 0weighted_div = sum(div_list) / total_weight if total_weight > 0 else 0print(f"000922红利指数加权市盈率: {weighted_pe:.2f}")print(f"000922红利指数加权市净率: {weighted_pb:.2f}")print(f"000922红利指数加权股息率: {weighted_div:.2f}")'''
脚本的作用
对指定基金/指数(默认 159699)计算加权估值指标
加权市盈率(PE)
加权市净率(PB)
加权股息率
当前季度的前 10 大重仓股;
第二季度的权重最小的 40 只股票;
将这两部分合并为一篮子股票。
从 akshare 获取该基金的持仓结构(按季度披露的持仓)。
取:
对这篮子股票,分别计算按持仓权重加权后的:
查询几个指数的基础信息/成分信息
获取全市场指数基本信息表。
分别查询红利相关指数、银行等指数的估值数据。
获取红利指数(000922)的成分股及权重(后面有一段注释掉的示例,演示如何对 000922 再做一遍"加权 PE/PB/股息率"的计算)。
整体上,这是一个用 akshare 做指数/基金持仓 + 估值因子分析的小工具。
主要函数
1. last_quarter()
根据当前日期判断"上一报告期所在的季度及年份"。
规则大致是:
如果当前是 1–3 月,则上一季度视为去年四季度;
否则认为上一季度是"当前年份中,当前月份所属前一个完整季度"。
返回值是
(季度号, 年份),比如(3, 2025)表示 2025 年三季度。
2. hk_index_pe_pb_div(index_code="159699")脚本的核心函数:
获取持仓数据
调用 akshare 接口,按
index_code(默认 159699)和指定月份(例:202511)获取该基金的持仓披露数据,其中包含"季度""股票代码""占净值比例"等字段。筛选两批股票构成分析篮子
按"占净值比例"从小到大排序的 40 名(尾部 40 名)。
按"占净值比例"从大到小排序的前 10 名。
根据
last_quarter()计算出的季度/年份,拼出"某年某季度"的字符串,在持仓数据中筛出当前季度的持仓记录,再从中选出:同时构造一个固定的"2 季度"字符串,在持仓数据中筛出"第二季度"的持仓记录,从中取:
将当前季度前 10 + 第二季度尾部 40 合并成一个 DataFrame,作为后续估值计算的样本集。
逐只股票获取估值数据
提取股票代码和对应权重(占净值比例)。
用 akshare 查询该港股的财务指标(市盈率、市净率、股息率 TTM 等)。
处理股息率缺失的情况(为空则按 0 处理)。
分别计算:
pe × 权重、pb × 权重、股息率 × 权重,并存入列表。对样本集中每一只股票:
计算加权平均
将所有权重求和得到
total_weight。加权市盈率 = 所有
pe × 权重之和 /total_weight。加权市净率 = 所有
pb × 权重之和 /total_weight。加权股息率 = 所有
股息率 × 权重之和 /total_weight。最后打印这三个加权指标。
注意:
本文部分变量已做脱敏处理,仅用于测试和学习研究,禁止用于商业用途,不能保证其合法性,准确性,完整性和有效性,请根据情况自行判断。技术层面需要提供帮助,可以通过打赏的方式进行探讨。
没有评论:
发表评论