请 [注册] 或 [登录]  | 返回主站

量化交易吧 /  数理科学 帖子:3353243 新帖:52

各板块pe和roe情况

我就是英雄发表于:8 月 24 日 18:00回复(1)
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import bisect
from jqdata import *
import math
import datetime
from sklearn import linear_model        #表示,可以调用sklearn中的linear_model模块进行线性回归。
#指定日期的板块PE(等权重)
def get_industry_pe_date(industry,date):
    stocks = get_industry_stocks(industry, date=date)
    q = query(valuation).filter(valuation.code.in_(stocks))
    df = get_fundamentals(q, date)
    if len(df)>0:
        pe = len(df)/sum([1/p if p>0 else 0 for p in df.pe_ratio])
        return pe
    else:
        return float('NaN')
    
#板块历史PE
def get_industry_pe(index_code):
    start='2005-1-1'
    end = pd.datetime.today();
    dates=[]
    pes=[]
    for d in pd.date_range(start,end,freq='M'): #频率为月
        dates.append(d)
        pes.append(get_industry_pe_date(index_code,d))
    return pd.Series(pes, index=dates)


def count_industry():
    #"sw_l1": 申万一级行业,"sw_l2": 申万二级行业,"sw_l3": 申万三级行业
    all_industry = get_industries(name='sw_l1')
    print all_industry
    industry_choose =['801170',
                   '801030',
                    '801150',
                      '801740',
                      '801110',
                      '801710',
                      '801720',
                      '801180',
                      '801890',
                      '801880',
                      '801080',
                      '801730',
                      '801750',
                      '801790',
                      '801120'
                  ]
    df_pe = pd.DataFrame()
    #分板块计算pe值
    for code in industry_choose:
        print u'正在处理: ',code
        #获取历史时间code下的所用pe
        df_pe[code]=get_industry_pe(code)

    today= pd.datetime.today()
    results=[]
    #进行分位数计算
    for code in industry_choose:
        #获取今天的板块pe值
        pe = get_industry_pe_date(code,today)
        
        #计算分位数,也就是今天的pe值在历史值上的分位数
        q_pes = [df_pe.quantile(i/10.0)[code]  for i in range(11)]
        
        #bisect其目的在于查找该数值将会插入的位置并返回,而不会插入
        #找到本code位于整体分位的次序,比如1,就是历史上的10%(因为总共切了10个分位)
        idx = bisect.bisect(q_pes,pe)
        #计算同一分位段内本code,quantile*10为当前的分位点,处于历史的哪个位置
        quantile = idx-(q_pes[idx]-pe)/(q_pes[idx]-q_pes[idx-1])
        index_name = all_industry.loc[code,"name"]
        index_roe = calculate_roe_ttm(code, today,type='industry')
        results.append([index_name,index_roe,'%.2f'% pe,'%.2f'% (quantile*10)]\
                       +['%.2f'%q  for q in q_pes]\
                       +[df_pe[code].count()])

    df_pe.columns=np.array(results)[:,0]
    df_pe.plot(figsize=(12,10))
    columns=[u'名称',u'当前roe',u'当前PE',u'分位点%',u'最小PE']\
    +['%d%%'% (i*10) for i in range(1,10)]\
    +[u'最大PE' , u"数据个数"]
    df = pd.DataFrame(data=results,index=industry_choose,columns=columns)
    return df
    

##粗略计算过去一年板块的roe情况 industry为板块代码
def calculate_roe_ttm(industry, date,type='industry'):
    #date=xxxx-03-31/.../xxxx-12-31,不支持个性化日期,例如xxxx-01-23
    industry_stock = []
    if(type == "industry"):
        industry_stock = get_industry_stocks(industry, date=date)
    else:
        industry_stock.append(industry)
    qt_str = [str(qt) for qt in pd.period_range(end=date, periods=4, freq='Q')]
    #此处与研究模块的区别 jq.+
    q = query(
        income.statDate,
        income.code,
        indicator.adjusted_profit,
        balance.equities_parent_company_owners
    ).filter(
        income.code.in_(industry_stock)
        #历史统计分析,不考虑未来函数问题
    )
    ##df为四个季度的数据df的数组  单元素:203*4
    df = [get_fundamentals(q, statDate=qt) for qt in qt_str]
    ##四个季度数据组合 812*4
    df = pd.concat(df)
    ##相当于group by,statDate第一列,code第二列 812*2
    df.set_index(['statDate', 'code'], inplace=True)
    ##按code展开 4*406
    df = df.unstack('code')
    ##过滤缺失数据 4 * 405
    df = df.dropna(axis=1)

    #按code合计四个季度的adjusted_profit的值 ----扣除非经常损益后的净利润(元)
    adj_net_profit = df['adjusted_profit'].sum()
    #按code合计四个季度的equities_parent_company_owners的均值 ----归属于母公司股东权益合计(元)
    ##所有者权益合计=母公司股东权益合计母+少数股东权益合计。
    equity_avg= df['equities_parent_company_owners'].mean()
    data = pd.concat([adj_net_profit, equity_avg], axis=1, join='inner')
    
    data.columns = ['adj_net_profit', 'equity_avg']

    ##归属于母公司股东的净利润*2/(期初归属于母公司股东的净资产+期末归属于母公司股东的净资产)
    roe_ttm = data['adj_net_profit'].sum()/data['equity_avg'].sum() * 100
    return round(roe_ttm, 4)

df = count_industry()
df
         name start_date
801740  国防军工I 2014-02-21
801020    采掘I 2004-02-10
801110  家用电器I 2004-02-10
801160  公用事业I 2004-02-10
801060  建筑建材I 2004-02-10
801770    通信I 2014-02-21
801010  农林牧渔I 2004-02-09
801120  食品饮料I 2004-02-10
801750   计算机I 2014-02-21
801050  有色金属I 2004-02-10
801890  机械设备I 2014-02-21
801170  交通运输I 2004-02-10
801090  交运设备I 2004-02-10
801710  建筑材料I 2014-02-21
801780    银行I 2014-02-21
801040    钢铁I 2004-02-10
801130  纺织服装I 2004-02-10
801880    汽车I 2014-02-21
801180   房地产I 2004-02-10
801230    综合I 2004-02-10
801220  信息服务I 2004-02-10
801760    传媒I 2014-02-21
801200  商业贸易I 2004-02-10
801140  轻工制造I 2004-02-10
801720  建筑装饰I 2014-02-21
801080    电子I 2004-02-10
801790  非银金融I 2014-02-21
801030    化工I 2004-02-10
801100  信息设备I 2004-02-10
801190  金融服务I 2004-02-10
801210  休闲服务I 2004-02-10
801730  电气设备I 2014-02-21
801070  机械设备I 2004-02-10
801150  医药生物I 2004-02-10
正在处理:  801170
正在处理:  801030
正在处理:  801150
正在处理:  801740
正在处理:  801110
正在处理:  801710
正在处理:  801720
正在处理:  801180
正在处理:  801890
正在处理:  801880
正在处理:  801080
正在处理:  801730
正在处理:  801750
正在处理:  801790
正在处理:  801120
名称 当前roe 当前PE 分位点% 最小PE 10% 20% 30% 40% 50% 60% 70% 80% 90% 最大PE 数据个数
801170 交通运输I 6.1195 18.60 19.74 13.54 17.20 18.63 19.60 22.45 25.26 27.66 29.73 31.69 40.66 51.40 175
801030 化工I 5.6901 24.66 9.80 12.21 24.91 27.58 30.71 35.62 38.36 43.78 47.84 57.75 64.94 92.54 175
801150 医药生物I 7.3236 31.25 8.66 23.69 32.42 34.93 38.42 41.56 44.30 46.36 48.67 53.35 63.70 97.74 175
801740 国防军工I 2.0306 58.93 6.05 54.36 61.92 68.69 79.13 94.65 105.65 121.34 134.20 144.56 180.08 237.90 66
801110 家用电器I -2.8325 30.07 33.97 17.95 22.17 25.06 28.44 32.54 35.34 37.89 40.32 42.84 48.18 90.72 175
801710 建筑材料I 15.1220 18.73 1.14 18.30 22.06 25.03 29.54 34.23 43.21 48.27 54.34 58.35 61.97 71.65 66
801720 建筑装饰I 4.1679 18.16 10.84 16.95 18.07 19.13 21.68 27.47 31.55 34.51 36.58 39.99 42.18 53.87 66
801180 房地产I 14.2486 12.65 1.94 11.60 16.99 18.90 21.49 24.04 27.50 30.85 34.15 38.45 45.25 94.33 175
801890 机械设备I 2.8974 38.69 8.16 31.45 40.32 41.68 46.03 55.32 60.45 66.22 78.48 84.78 93.42 108.94 66
801880 汽车I 0.8342 26.75 21.20 20.29 22.87 26.47 28.81 29.66 33.15 36.20 40.25 41.93 43.68 57.02 66
801080 电子I 4.7942 43.82 27.49 19.96 34.21 40.16 45.04 49.61 57.28 63.39 67.92 73.29 82.85 120.84 175
801730 电气设备I 2.0559 39.49 18.09 28.16 33.76 40.85 44.42 50.41 53.30 57.16 58.38 60.25 72.16 107.83 66
801750 计算机I 1.8492 54.46 17.94 37.94 49.38 55.77 58.80 63.30 66.94 73.15 82.76 88.60 110.76 169.69 66
801790 非银金融I 10.1891 30.65 75.87 13.90 18.00 22.70 24.65 26.15 27.06 28.05 29.03 31.79 37.99 45.21 66
801120 食品饮料I 17.4810 36.76 18.05 26.00 33.15 37.63 40.64 44.32 47.90 50.97 54.15 58.84 71.92 103.94 175
 

全部回复

0/140

达人推荐

量化课程

    移动端课程