In [1]:
import tushare as ts
import pandas as pd
stock_selected='300159'
df = ts.get_realtime_quotes(stock_selected) 
df[['code','name','price','bid','ask','volume','amount','time']]


Out[1]:
code name price bid ask volume amount time
0 300159 新研股份 12.000 12.000 12.010 2661673 31933936.590 13:40:57

In [ ]:
cf=ts.get_concept_classified()
print(cf)

In [ ]:

1、top 10 share holder


In [1]:
import tushare as ts
import pandas as pd
stock_selected='600699'

df1, data1 = ts.top10_holders(code=stock_selected, gdtype='1') 
df1 = df1.sort_values('quarter', ascending=True)
df1.tail(10)

#qts = list(df1['quarter'])
#data = list(df1['props'])
#name = ts.get_realtime_quotes(stock_selected)['name'][0]


Out[1]:
quarter amount changed props
9 2015-03-31 26381.82 20203.57 58.75
8 2015-06-30 20772.26 -5609.56 46.25
7 2015-09-30 22702.83 1930.57 50.54
6 2015-12-31 41063.10 18360.27 64.55
5 2016-03-31 40620.09 -443.01 63.86
4 2016-06-30 39450.39 -1169.70 62.03
3 2016-09-30 41732.32 2281.93 60.53
2 2016-12-31 42186.90 454.58 61.18
1 2017-03-31 41636.51 -550.39 60.40
0 2017-06-30 40932.18 -704.33 59.38

2、Top 10 share holder


In [3]:
import tushare as ts
import pandas as pd
from IPython.display import HTML
#浦发银行2016三季度前十大流通股东情况
df2, data2 = ts.top10_holders(code=stock_selected, year=2016, quarter=3, gdtype='1')

#取前十大流通股东名称
top10name = str(list(data2['name']))
top10name


Out[3]:
"['宁波均胜投资集团有限公司', '乌鲁木齐喜尔盈股权投资有限合伙企业', '王剑峰', '香港中央结算有限公司', '中国长城资产管理公司', '中国证券金融股份有限公司', '平安大华基金-平安银行-建信资本管理有限责任公司', '重庆高新创投两江品牌汽车产业投资中心(有限合伙)', '中国银行股份有限公司-华夏新经济灵活配置混合型发起式证券投资基金', '全国社保基金一零九组合']"

获取沪深上市公司基本情况。属性包括:

code,代码 name,名称 industry,所属行业 area,地区 pe,市盈率 outstanding,流通股本(亿) totals,总股本(亿) totalAssets,总资产(万) liquidAssets,流动资产 fixedAssets,固定资产 reserved,公积金 reservedPerShare,每股公积金 esp,每股收益 bvps,每股净资 pb,市净率 timeToMarket,上市日期 undp,未分利润 perundp, 每股未分配 rev,收入同比(%) profit,利润同比(%) gpr,毛利率(%) npr,净利润率(%) holders,股东人数 调用方法:


In [ ]:
import tushare as ts
df=ts.get_stock_basics()
#data=df.loc('002281')
#print(data['gpr'])
#data=df.loc('002281')
#df.ix['002281']

In [ ]:
#df.ix['002281']
#df.ix['002281']
#df.info()
df[df.name == u'四维图新']

In [ ]:
df_out=df[(df.profit>20) & 
          (df.gpr > 25) &
          (df.pe <120) &
          (df.pe >0) &
          (df.rev >0)][['name','industry','pe','profit','esp','rev','holders','gpr','npr']]
df_out.sort_values(by='npr',ascending=False, inplace = True)
df_out.rename(columns={'name':u'股票','industry':u'行业','pe':u'市盈率', 
                       'profit':u'利润同比','esp':u'每股收益','rev':u'收入同比',
                       'holders':u'股东人数','gpr':u'毛利率','npr':u'净利率'})[:50]

业绩报告(主表) 按年度、季度获取业绩报表数据。数据获取需要一定的时间,网速取决于您的网速,请耐心等待。结果返回的数据属性说明如下:

code,代码 name,名称 esp,每股收益 eps_yoy,每股收益同比(%) bvps,每股净资产 roe,净资产收益率(%) epcf,每股现金流量(元) net_profits,净利润(万元) profits_yoy,净利润同比(%) distrib,分配方案 report_date,发布日期 调用方法:

获取2014年第3季度的业绩报表数据

ts.get_report_data(2014,3)

结果返回:

    code   name      esp   eps_yoy  bvps     roe   epcf net_profits  

In [ ]:
import tushare as ts
df=ts.get_report_data(2016,4)

In [ ]:
#df[df.code=='002405']
df

盈利能力 按年度、季度获取盈利能力数据,结果返回的数据属性说明如下:

code,代码 name,名称 roe,净资产收益率(%) net_profit_ratio,净利率(%) gross_profit_rate,毛利率(%) net_profits,净利润(万元) esp,每股收益 business_income,营业收入(百万元) bips,每股主营业务收入(元) 调用方法:

获取2014年第3季度的盈利能力数据

ts.get_profit_data(2014,3) 结果返回:


In [13]:
import tushare as ts
df_profit = ts.get_profit_data(2017,1)


[Getting data:]#######################################################

In [12]:
#df_profit.info()
#df_profit[df_profit.code == '002405']
df_out=df_profit[(df_profit.roe>10) & (df_profit.gross_profit_rate > 25) & (df_profit.net_profits >0)]
df_out.sort_values(by='roe',ascending=False, inplace = True)
df_out[:50]


c:\anaconda2\envs\python35\lib\site-packages\ipykernel_launcher.py:4: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  after removing the cwd from sys.path.
Out[12]:
code name roe net_profit_ratio gross_profit_rate net_profits eps business_income bips
4 600354 敦煌种业 23.40 302.21 25.0654 273.7035 0.5185 90.5655 0.1715
6 600230 沧州大化 21.94 39.66 55.6318 424.8125 1.4440 1070.9230 3.6402
7 600338 西藏珠峰 20.28 53.09 70.4140 305.8753 0.4684 576.0689 0.8821
8 000036 华联控股 18.32 42.51 71.4131 758.4114 0.6643 1783.7509 1.5625
9 300288 朗玛信息 18.30 85.96 26.9264 240.8041 0.7125 280.1342 0.8289
10 600291 西水股份 17.53 22.32 26.3018 2117.8868 1.9375 9488.7197 8.6808
11 000505 珠江控股 17.44 5.48 26.3391 13.7571 0.0322 250.7017 0.5874
12 000526 *ST紫学 16.87 1.29 28.5887 9.1549 0.0951 708.2125 7.3622
13 600633 浙数文化 16.31 192.98 43.5107 1259.7513 0.9676 652.7781 0.5013
14 600167 联美控股 15.40 43.16 60.2320 451.5746 0.6639 1046.1494 1.5381
17 600393 粤泰股份 13.13 28.34 44.0938 725.1229 0.5718 2558.6270 2.0176
18 002027 分众传媒 12.20 45.72 67.5988 1106.7614 0.1266 2420.4147 0.2770
19 603165 荣晟环保 12.03 19.96 28.6107 95.2930 0.7522 477.2464 3.7673
20 000822 山东海化 11.38 24.99 32.6209 275.6988 0.3080 1103.2008 1.2324
21 600309 万华化学 11.26 19.94 39.2307 2195.0598 0.9634 11007.0486 4.8311
22 000011 深物业A 11.11 29.03 74.7318 301.5978 0.5060 1038.6835 1.7428
24 603387 基蛋生物 10.73 44.22 82.0964 40.8975 0.4131 92.4743 0.9340
25 002714 牧原股份 10.72 34.55 40.4656 680.0364 0.6578 1967.8447 1.9036

In [ ]:

营运能力 按年度、季度获取营运能力数据,结果返回的数据属性说明如下:

code,代码 name,名称 arturnover,应收账款周转率(次) arturndays,应收账款周转天数(天) inventory_turnover,存货周转率(次) inventory_days,存货周转天数(天) currentasset_turnover,流动资产周转率(次) currentasset_days,流动资产周转天数(天) 调用方法:

获取2014年第3季度的营运能力数据

ts.get_operation_data(2014,3) 结果返回:

  code     name   arturnover arturndays  inventory_turnover  inventory_days  \

In [ ]:
import tushare as ts
df_operation = ts.get_operation_data(2017,1)

In [ ]:
df_out=df_operation[df_operation.currentasset_days<120]
df_out.sort_values(by='currentasset_days',ascending=False, inplace = True)
df_out[:50]

成长能力

按年度、季度获取成长能力数据,结果返回的数据属性说明如下:

code,代码 name,名称 mbrg,主营业务收入增长率(%) nprg,净利润增长率(%) nav,净资产增长率 targ,总资产增长率 epsg,每股收益增长率 seg,股东权益增长率 调用方法:

获取2014年第3季度的成长能力数据

ts.get_growth_data(2014,3) 结果返回:


In [ ]:
# -*- coding: UTF-8 -*-
import tushare as ts
df_growth = ts.get_growth_data(2017,1)

In [ ]:
import numpy as np
import pandas as pd
df_out = df_growth[(df_growth.nprg >20) &
                  (df_growth.mbrg >20)]
df_out.sort_values(by= 'nprg', ascending = True, inplace=True)
writer = pd.ExcelWriter('growth.xlsx')
df_out.to_excel(writer,'growth')
writer.save()
#df_out.to_csv(".\growth.csv",encoding="utf_8_sig",dtype={'code':np.string})
df_out[:50]

偿债能力 按年度、季度获取偿债能力数据,结果返回的数据属性说明如下:

code,代码 name,名称 currentratio,流动比率 quickratio,速动比率 cashratio,现金比率 icratio,利息支付倍数 sheqratio,股东权益比率 adratio,股东权益增长率 调用方法:

获取2014年第3季度的偿债能力数据

ts.get_debtpaying_data(2014,3) 结果返回:

  code     name     currentratio quickratio    cashratio      icratio  \

现金流量 按年度、季度获取现金流量数据,结果返回的数据属性说明如下:

code,代码 name,名称 cf_sales,经营现金净流量对销售收入比率 rateofreturn,资产的经营现金流量回报率 cf_nm,经营现金净流量与净利润的比率 cf_liabilities,经营现金净流量对负债比率 cashflowratio,现金流量比率 调用方法:

获取2014年第3季度的现金流量数据

ts.get_cashflow_data(2014,3) 结果返回:

  code    name    cf_sales   rateofreturn  cf_nm     cf_liabilities  \

'''


In [ ]:
import tushare as ts
df_cash = ts.get_cashflow_data(2016,4)

In [ ]:
df_out = df_cash[(df_cash.cf_sales > 0)]
df_out.sort_values(by = 'cf_sales', ascending = True, inplace = True)
df_out[:50]

3、CandleStick


In [ ]:
import tushare as ts
import pandas as pd
from IPython.display import HTML
#中国联通前复权数据
#df = ts.get_k_data(stock_selected, start='2016-01-01', end='2016-12-02')
df = ts.get_k_data(stock_selected, start='2016-01-01')

In [ ]:
datastr = ''
for idx in df.index:
    rowstr = '[\'%s\',%s,%s,%s,%s]' % (df.ix[idx]['date'], df.ix[idx]['open'], 
                                           df.ix[idx]['close'], df.ix[idx]['low'], 
                                           df.ix[idx]['high'])
    datastr += rowstr + ','
datastr = datastr[:-1]
#取股票名称
name = ts.get_realtime_quotes(stock_selected)['name'][0]

datahead = """
<div id="chart" style="width:800px; height:600px;"></div> 
<script> 
require.config({ paths:{ echarts: '//cdn.bootcss.com/echarts/3.2.3/echarts.min', } });
require(['echarts'],function(ec){
var myChart = ec.init(document.getElementById('chart'));
"""
datavar = 'var data0 = splitData([%s]);' % datastr
funcstr = """
function splitData(rawData) {
    var categoryData = [];
    var values = []
    for (var i = 0; i < rawData.length; i++) {
        categoryData.push(rawData[i].splice(0, 1)[0]);
        values.push(rawData[i])
    }
    return {
        categoryData: categoryData,
        values: values
    };
}

function calculateMA(dayCount) {
    var result = [];
    for (var i = 0, len = data0.values.length; i < len; i++) {
        if (i < dayCount) {
            result.push('-');
            continue;
        }
        var sum = 0;
        for (var j = 0; j < dayCount; j++) {
            sum += data0.values[i - j][1];
        }
        result.push((sum / dayCount).toFixed(2));
    }
    return result;
}

option = {
    title: {
"""

namestr = 'text: \'%s\',' %name

functail = """
        left: 0
    },
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'line'
        }
    },
    legend: {
        data: ['日K', 'MA5', 'MA10', 'MA20', 'MA30']
    },
    grid: {
        left: '10%',
        right: '10%',
        bottom: '15%'
    },
    xAxis: {
        type: 'category',
        data: data0.categoryData,
        scale: true,
        boundaryGap : false,
        axisLine: {onZero: false},
        splitLine: {show: false},
        splitNumber: 20,
        min: 'dataMin',
        max: 'dataMax'
    },
    yAxis: {
        scale: true,
        splitArea: {
            show: true
        }
    },
    dataZoom: [
        {
            type: 'inside',
            start: 50,
            end: 100
        },
        {
            show: true,
            type: 'slider',
            y: '90%',
            start: 50,
            end: 100
        }
    ],
    series: [
        {
            name: '日K',
            type: 'candlestick',
            data: data0.values,
            markPoint: {
                label: {
                    normal: {
                        formatter: function (param) {
                            return param != null ? Math.round(param.value) : '';
                        }
                    }
                },
                data: [
                    {
                        name: '标点',
                        coord: ['2013/5/31', 2300],
                        value: 2300,
                        itemStyle: {
                            normal: {color: 'rgb(41,60,85)'}
                        }
                    },
                    {
                        name: 'highest value',
                        type: 'max',
                        valueDim: 'highest'
                    },
                    {
                        name: 'lowest value',
                        type: 'min',
                        valueDim: 'lowest'
                    },
                    {
                        name: 'average value on close',
                        type: 'average',
                        valueDim: 'close'
                    }
                ],
                tooltip: {
                    formatter: function (param) {
                        return param.name + '<br>' + (param.data.coord || '');
                    }
                }
            },
            markLine: {
                symbol: ['none', 'none'],
                data: [
                    [
                        {
                            name: 'from lowest to highest',
                            type: 'min',
                            valueDim: 'lowest',
                            symbol: 'circle',
                            symbolSize: 10,
                            label: {
                                normal: {show: false},
                                emphasis: {show: false}
                            }
                        },
                        {
                            type: 'max',
                            valueDim: 'highest',
                            symbol: 'circle',
                            symbolSize: 10,
                            label: {
                                normal: {show: false},
                                emphasis: {show: false}
                            }
                        }
                    ],
                    {
                        name: 'min line on close',
                        type: 'min',
                        valueDim: 'close'
                    },
                    {
                        name: 'max line on close',
                        type: 'max',
                        valueDim: 'close'
                    }
                ]
            }
        },
        {
            name: 'MA5',
            type: 'line',
            data: calculateMA(5),
            smooth: true,
            lineStyle: {
                normal: {opacity: 0.5}
            }
        },
        {
            name: 'MA10',
            type: 'line',
            data: calculateMA(10),
            smooth: true,
            lineStyle: {
                normal: {opacity: 0.5}
            }
        },
        {
            name: 'MA20',
            type: 'line',
            data: calculateMA(20),
            smooth: true,
            lineStyle: {
                normal: {opacity: 0.5}
            }
        },
        {
            name: 'MA30',
            type: 'line',
            data: calculateMA(30),
            smooth: true,
            lineStyle: {
                normal: {opacity: 0.5}
            }
        },

    ]
};
myChart.setOption(option);
    });
</script>
"""

In [ ]:
HTML(datahead + datavar + funcstr + namestr + functail)

In [ ]:
import tushare as ts
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
stock_selected='002281'
df = ts.get_k_data(stock_selected, start='2016-01-01')
df.info()

In [ ]:
#df['close'].plot(grid=True)

In [ ]:
#df['42d']= np.round(pd.rolling_mean(df['close'],window=42),2)
#df['252d']= np.round(pd.rolling_mean(df['close'],window=252),2)
df['42d']= np.round(pd.Series.rolling(df['close'],window=42).mean(),2)
df['252d']= np.round(pd.Series.rolling(df['close'],window=252).mean(),2)

In [ ]:
#df[['close','42d','252d']].tail(10)

In [ ]:
df[['close','42d','252d']].plot(grid=True)

In [ ]:
df['42-252']=df['42d']-df['252d']
#df['42-252'].tail(10)

In [ ]:
SD=1
df['regime'] = np.where(df['42-252']>SD,1,0)
df['regime'] = np.where(df['42-252'] < -SD,-1,df['regime'])
#df['regime'].head(10)

In [ ]:
df['regime'].tail(10)

In [ ]:
#df['regime'].plot(lw=1.5)
#plt.ylim(-1.1, 1.1)

In [ ]:
plt.show()