import tushare as ts
import pandas as pd
from IPython.display import HTML
stock_selected='000413'
#历年前十大股东持股情况
#df1为季度统计摘要，data1为前十大持股明细统计
df1, data1 = ts.top10_holders(code=stock_selected, gdtype='0') #gdtype等于1时表示流通股，默认为0 
#df1, data1 = ts.top10_holders(code='002281', year=2015, quarter=1, 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]

"""
Explanation: 1、top 10 share holder
End of explanation
"""


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']))

"""
Explanation: 2、Top 10 share holder
End of explanation
"""


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


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


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]

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


import tushare as ts
df=ts.get_report_data(2016,4)

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

"""
Explanation: 业绩报告（主表）
按年度、季度获取业绩报表数据。数据获取需要一定的时间，网速取决于您的网速，请耐心等待。结果返回的数据属性说明如下：
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
End of explanation
"""


import tushare as ts
df_profit = ts.get_profit_data(2017,1)

#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]

"""
Explanation: 盈利能力
按年度、季度获取盈利能力数据，结果返回的数据属性说明如下：
code,代码
name,名称
roe,净资产收益率(%)
net_profit_ratio,净利率(%)
gross_profit_rate,毛利率(%)
net_profits,净利润(万元)
esp,每股收益
business_income,营业收入(百万元)
bips,每股主营业务收入(元)
调用方法：
获取2014年第3季度的盈利能力数据
ts.get_profit_data(2014,3)
结果返回：
End of explanation
"""


import tushare as ts
df_operation = ts.get_operation_data(2017,1)

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

"""
Explanation: 营运能力
按年度、季度获取营运能力数据，结果返回的数据属性说明如下：
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  \
End of explanation
"""


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

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

"""
Explanation: 成长能力
按年度、季度获取成长能力数据，结果返回的数据属性说明如下：
code,代码
name,名称
mbrg,主营业务收入增长率(%)
nprg,净利润增长率(%)
nav,净资产增长率
targ,总资产增长率
epsg,每股收益增长率
seg,股东权益增长率
调用方法：
获取2014年第3季度的成长能力数据
ts.get_growth_data(2014,3)
结果返回：
End of explanation
"""


import tushare as ts
df_cash = ts.get_cashflow_data(2016,4)

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

"""
Explanation: 偿债能力
按年度、季度获取偿债能力数据，结果返回的数据属性说明如下：
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  \

'''
End of explanation
"""


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')


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>
"""

HTML(datahead + datavar + funcstr + namestr + functail)

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()

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

#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)

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

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

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

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)

df['regime'].tail(10)

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

plt.show()

"""
Explanation: 3、CandleStick
End of explanation
"""


