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]:
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]:
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,发布日期 调用方法:
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
In [13]:
import tushare as ts
df_profit = ts.get_profit_data(2017,1)
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]
Out[12]:
In [ ]:
营运能力 按年度、季度获取营运能力数据,结果返回的数据属性说明如下:
code,代码 name,名称 arturnover,应收账款周转率(次) arturndays,应收账款周转天数(天) inventory_turnover,存货周转率(次) inventory_days,存货周转天数(天) currentasset_turnover,流动资产周转率(次) currentasset_days,流动资产周转天数(天) 调用方法:
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]
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]
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()