最近在学习基于python的股票数据分析,其中主要用到了tushare和seaborn。tushare是一款财经类数据接口包,国内的股票数据还是比较全的

官网地址:http://tushare.waditu.com/index.html#id5。seaborn则是一款绘图库,通过seaborn可以轻松地画出简洁漂亮的图表,而且库本身具有一定的统计功能。

  导入的模块:

import matplotlib.pyplot as plt

  import seaborn as sns

  import seaborn.linearmodels as snsl

from datetime import datetime

  import tushare as ts

代码部分:

  股票收盘价走势曲线

  sns.set_style("whitegrid")

  end = datetime.today() #开始时间结束时间,选取最近一年的数据

  start = datetime(end.year-1,end.month,end.day)

  end = str(end)[0:10]

  start = str(start)[0:10]

stock = ts.get_hist_data('300104',start,end)#选取一支股票

  stock['close'].plot(legend=True ,figsize=(10,4))

  plt.show()

Python金融量化

股票日线

同理,可以做出5日均线、10日均线以及20日均线

  stock[['close','ma5','ma10','ma20']].plot(legend=True ,figsize=(10,4))

Python金融量化

日线、5日均线、10日均线、20日均线

股票每日涨跌幅度

  stock['Daily Return'] = stock['close'].pct_change()

  stock['Daily Return'].plot(legend=True,figsize=(10,4))

Python金融量化

每日涨跌幅

核密度估计

  sns.kdeplot(stock['Daily Return'].dropna())

Python金融量化

核密度估计

核密度估计+统计柱状图

  sns.distplot(stock['Daily Return'].dropna(),bins=100)

Python金融量化

核密度+柱状图

两支股票的皮尔森相关系数

  sns.jointplot(stock['Daily Return'],stock['Daily Return'],alpha=0.2)

Python金融量化

皮尔森相关系数

多只股票相关性计算

  stock_lis=['300113','300343','300295','300315`] #随便选取了四支互联网相关的股票

  df=pd.DataFrame()

  for stock in stock_lis: closing_df = ts.get_hist_data(stock,start,end)['close'] df = df.join(pd.DataFrame({stock:closing_df}),how='outer')

  tech_rets = df.pct_change()

  snsl.corrplot(tech_rets.dropna())

Python金融量化

  相关性

简单地计算股票的收益与风险,衡量股票收益与风险的数值分别为股票涨跌的平均值以及标准差,平均值为正则说明收益是正的,标准差越大则说明股票波动大,风险也大。

  rets = tech_rets.dropna()

  plt.scatter(rets.mean(),rets.std())

  plt.xlabel('Excepted Return')

  plt.ylabel('Risk')

  for label,x,y in zip(rets.columns,rets.mean(),rets.std()):#添加标注 plt.annotate( label, xy =(x,y),xytext=(15,15), textcoords = 'offset points', arrowprops = dict(arrowstyle = '-',connectionstyle = 'arc3,rad=-0.3'))

Python金融量化

声明:本文由入驻搜狐公众平台的作者撰写,除搜狐官方账号外,观点仅代表作者本人,不代表搜狐立场。

 

 

用Python分析公开数据选出高送转预期股票

根据以往的经验,每年年底都会有一波高送转预期行情。今天,米哥就带大家实践一下如何利用tushare实现高送转预期选股。

本文主要是讲述选股的思路方法,选股条件和参数大家可以根据米哥提供的代码自行修改。

1. 选股原理

一般来说,具备高送转预期的个股,都具有总市值低、每股公积金高、每股收益大,流通股本少的特点。当然,也还有其它的因素,比如当前股价、经营收益变动情况、以及以往分红送股习惯等等。

这里我们暂时只考虑每股公积金、每股收益、流通股本和总市值四个因素,将公积金大于等于5元,每股收益大于等于5毛,流通股本在3亿以下,总市值在100亿以内作为高送转预期目标(这些参数大家可根据自己的经验随意调整)。

2. 数据准备

首先要导入tushare:

import tushare as ts

调取股票基本面数据和行情数据

# 基本面数据
basic = ts.get_stock_basics()

# 行情和市值数据
hq = ts.get_today_all()

3. 数据清洗整理

对获取到的数据进行清洗和整理,只保留需要的字段。(其它字段及含义,请参考 http:// tushare.org 文档)

#当前股价,如果停牌则设置当前价格为上一个交易日股价
hq['trade'] = hq.apply(lambda x:x.settlement if x.trade==0 else x.trade, axis=1)

#分别选取流通股本,总股本,每股公积金,每股收益
basedata = basic[['outstanding', 'totals', 'reservedPerShare', 'esp']]

#选取股票代码,名称,当前价格,总市值,流通市值
hqdata = hq[['code', 'name', 'trade', 'mktcap', 'nmc']]

#设置行情数据code为index列
hqdata = hqdata.set_index('code')

#合并两个数据表
data = basedata.merge(hqdata, left_index=True, right_index=True)

Python金融量化

4. 选股条件

根据上文提到的选股参数和条件,我们对数据进一步处理。

将总市值和流通市值换成亿元单位
data['mktcap'] = data['mktcap'] / 10000
data['nmc'] = data['nmc'] / 10000

设置参数和过滤值(此次各自调整)

#每股公积金>=5
res = data.reservedPerShare >= 5
#流通股本<=3亿
out = data.outstanding <= 30000
#每股收益>=5毛
eps = data.esp >= 0.5
#总市值<100亿
mktcap = data.mktcap <= 100

取并集结果:

allcrit = res & out & eps & mktcap
selected = data[allcrit]

具有高送转预期股票的结果呈现:

Python金融量化

以上字段的含义分别为:股票名称、收盘价格、每股公积金、流通股本、每股收益(应该为eps,之前发布笔误)、总市值和流通市值。

https://zhuanlan.zhihu.com/p/23829205

 

 

 

Python 金叉判定

Python金融量化
def jincha(context, bar_dict, his):

    #站上5日线

    def zs5(context, bar_dict, his):

        ma_n = pd.rolling_mean(his, 5)

        temp = his - ma_n

​       #temp_s包含了前一天站上五日线得股票代码

        temp_s = list(temp[temp>0].iloc[-1,:].dropna().index)

        return temp_s

    #站上10日线

    def zs10(context, bar_dict, his):

        ma_n = pd.rolling_mean(his, 10)

        temp = his - ma_n

        temp_s = list(temp[temp>0].iloc[-1,:].dropna().index)

        return temp_s

    

    #金叉突破

    def jc(context, bar_dict, his):

        mas = pd.rolling_mean(his,5)

        mal = pd.rolling_mean(his, 10)

        temp = mas - mal

        #temp_jc昨天大于0股票代码

        #temp_r前天大于0股票代码​

        temp_jc = list(temp[temp>0].iloc[-1,:].dropna().index)

        temp_r = list(temp[temp>0].iloc[-2,:].dropna().index)

        temp = []

        for stock in temp_jc:

            if stock not in temp_r:

                temp.append(stock)

        return temp

    

    #求三种条件下的股票代码交集

    con1 = zs5(context, bar_dict, his)

    con2 = zs10(context, bar_dict, his)

    con3 = jc(context, bar_dict, his)

    tar_list=[con1,con2,con3]​

    tarstock = tar_list[0]

    for i in tar_list:

        tarstock = list(set(tarstock).intersection(set(i)))

    return tarstock
Python金融量化
View Code

 

Python 过滤次新股、停牌、涨跌停

#过滤次新股、是否涨跌停、是否停牌等条件

def filcon(context,bar_dict,tar_list):

    def zdt_trade(stock, context, bar_dict):

        yesterday = history(2,'1d', 'close')[stock].values[-1]

        zt = round(1.10 * yesterday,2)

        dt = round(0.99 * yesterday,2)

        #last最后交易价

        return dt < bar_dict[stock].last < zt

    filstock = []

    for stock in tar_list:

        con1 = ipo_days(stock,context.now) > 60

        con2 = bar_dict[stock].is_trading

        con3 = zdt_trade(stock,context,bar_dict)

        if con1 & con2 & con3:

                filstock.append(stock)

    return filstock
View Code

相关文章:

  • 2022-12-23
  • 2021-09-02
  • 2021-12-09
  • 2021-06-14
  • 2022-12-23
  • 2021-12-24
  • 2022-12-23
  • 2021-12-09
猜你喜欢
  • 2022-01-31
  • 2021-06-19
  • 2022-01-11
  • 2021-11-20
  • 2022-12-23
  • 2021-12-26
  • 2022-02-20
相关资源
相似解决方案