发现numpy一个很坑的问题,要一定级别的高手才能发现问题

李魔佛 发表了文章 • 0 个评论 • 4285 次浏览 • 2019-04-30 00:04 • 来自相关话题

一个二元一次方程:
y=X0**2+X1**2   # **2 是平方def function_2(x):
return x[0]**2+x[1]**2

 
下面是计算y的偏导数,分布计算X0和X1的偏导def numerical_gradient(f,x):
grad = np.zeros_like(x)
h=1e-4
for idx in range(x.size):
temp_v = x[idx]
x[idx]=temp_v+h
f1=f(x)
print(x,f1)
x[idx]=temp_v-h
f2=f(x)
print(x,f2)
ret = (f1-f2)/(2*h)
print(ret)
x[idx]=temp_v
grad[idx]=ret

return grad
然后调用numerical_gradient(function_2,np.array([3,4]))
计算的是二元一次方程 y=X0**2+X1**2  在点(3,4)的偏导的值
得到的是什么结果?
为什么会得到这样的结果? 
小白一般要花点时间才能找到原因。
  查看全部
一个二元一次方程:
y=X0**2+X1**2   # **2 是平方
def function_2(x):
return x[0]**2+x[1]**2

 
下面是计算y的偏导数,分布计算X0和X1的偏导
def numerical_gradient(f,x):
grad = np.zeros_like(x)
h=1e-4
for idx in range(x.size):
temp_v = x[idx]
x[idx]=temp_v+h
f1=f(x)
print(x,f1)
x[idx]=temp_v-h
f2=f(x)
print(x,f2)
ret = (f1-f2)/(2*h)
print(ret)
x[idx]=temp_v
grad[idx]=ret

return grad

然后调用
numerical_gradient(function_2,np.array([3,4]))

计算的是二元一次方程 y=X0**2+X1**2  在点(3,4)的偏导的值
得到的是什么结果?
为什么会得到这样的结果? 
小白一般要花点时间才能找到原因。
 

numpy和dataframe轴的含义,axis为负数的含义

李魔佛 发表了文章 • 0 个评论 • 5113 次浏览 • 2019-04-28 14:22 • 来自相关话题

比如有数组:
a=np.array([[[1,2],[3,4]],[[11,12],[13,14]]])
a
array([[[ 1, 2],
[ 3, 4]],

[[11, 12],
[13, 14]]])
 a有3个中括号,那么就有3条轴,从0开始到2,分别是axis=0,1,2
那么我要对a进行求和,分别用axis=0,1,2进行运行。
 
a.sum(axis=0)得到:
array([[12, 14],
[16, 18]])意思是去掉一个中括号,然后运行。
 
同理:
a.sum(axis=1)对a去掉2个中括号,然后运行。
得到:
array([[ 4, 6],
[24, 26]])那么对a.sum(axis=2)的结果呢?读者可以自己上机去尝试吧。
 
而轴的负数,axis=-3和axis=0的意思是一样的,对于有3层轴的数组来说的话。
 
a.sum(axis=-3)
array([[12, 14],
[16, 18]])
  查看全部
比如有数组:
a=np.array([[[1,2],[3,4]],[[11,12],[13,14]]])

a
array([[[ 1,  2],
[ 3, 4]],

[[11, 12],
[13, 14]]])

 a有3个中括号,那么就有3条轴,从0开始到2,分别是axis=0,1,2
那么我要对a进行求和,分别用axis=0,1,2进行运行。
 
a.sum(axis=0)
得到:
array([[12, 14],
[16, 18]])
意思是去掉一个中括号,然后运行。
 
同理:
a.sum(axis=1)
对a去掉2个中括号,然后运行。
得到:
array([[ 4,  6],
[24, 26]])
那么对a.sum(axis=2)的结果呢?读者可以自己上机去尝试吧。
 
而轴的负数,axis=-3和axis=0的意思是一样的,对于有3层轴的数组来说的话。
 
a.sum(axis=-3)

array([[12, 14],
[16, 18]])

 

np.nonzero()的用法【numpy小白】

李魔佛 发表了文章 • 0 个评论 • 5597 次浏览 • 2019-04-28 10:16 • 来自相关话题

numpy函数返回非零元素的位置。

返回值为元组, 两个值分别为两个维度, 包含了相应维度上非零元素的目录值。
 
比如:
n1=np.array([0,1,0,0,0,0,1,0,0,0,0,0,0,1])
n1.nonzero()
返回的是:
(array([ 1, 6, 13], dtype=int64),)注意上面是一个yu元组
要获取里面的值,需要用 n1.nonzero()[0] 来获取。
 
原创文章
转载请注明出处:
http://30daydo.com/article/466
  查看全部
numpy函数返回非零元素的位置。

返回值为元组, 两个值分别为两个维度, 包含了相应维度上非零元素的目录值。
 
比如:
n1=np.array([0,1,0,0,0,0,1,0,0,0,0,0,0,1])
n1.nonzero()

返回的是:
(array([ 1,  6, 13], dtype=int64),)
注意上面是一个yu元组
要获取里面的值,需要用 n1.nonzero()[0] 来获取。
 
原创文章
转载请注明出处:
http://30daydo.com/article/466
 

ndarray和array的区别【numpy小白】

李魔佛 发表了文章 • 0 个评论 • 12188 次浏览 • 2019-04-28 10:11 • 来自相关话题

在numpy中,np.array()是一个函数,用法: np.array([1,2,3,4])上面代码创建了一个对象,这个对象就是ndarray。 所以ndarray是一个类对象象,而array是一个方法。
 
原创文章
转载请注明出处:
http://30daydo.com/article/465
  查看全部
在numpy中,np.array()是一个函数,用法: 
np.array([1,2,3,4])
上面代码创建了一个对象,这个对象就是ndarray。 所以ndarray是一个类对象象,而array是一个方法。
 
原创文章
转载请注明出处:
http://30daydo.com/article/465
 

可转债价格分布堆叠图 绘制 可视化 python+pyecharts

李魔佛 发表了文章 • 0 个评论 • 7158 次浏览 • 2019-01-30 10:59 • 来自相关话题

这一节课带大家学习如何利用可视化,更好的呈现数据。
即使你有很多数据,可是,你无法直观地看到数据的总体趋势。使用可视化的绘图,可以帮助我们看到数据背后看不到的数据。 比如我已经有每一个可转债的价格,评级。数据如下:





 点击查看大图

如果我用下面的图形就可以看出规律:




 点击查看大图

横坐标是价格,纵坐标是落在该价格的可转债数量,不同颜色代表不同评级的可转债。
 
可以看到大部分AA-评级(浅橙色)的可转债价格都在100元以下,而AA(浅蓝色)的可转债价格分布较为平均,从90到110都有。而AA+和AAA的一般都在100以上。
 
那么如何使用代码实现呢?from setting import get_mysql_conn,get_engine
import pandas as pd
import pymongo
from pyecharts import Geo,Style,Map
engine = get_engine('db_stock',local='local')
# 堆叠图
from pyecharts import Bar
df = pd.read_sql('tb_bond_jisilu',con=engine)

result ={}
for name,grades in df.groupby('评级'):
# print(name,grades[['可转债名称','可转债价格']])
for each in grades['可转债价格']:
result.setdefault(name,)
result[name].append(each)


# 确定价格的范围

value = [str(i) for i in range(85,140)]
ret = [0]*len(value)
ret1 = dict(zip(value,ret))

ret_A_add = ret1.copy()
for item in result['A+']:
for k in ret1:
if float(k)+0.5>item and float(k)-0.5<=item:
ret_A_add[k]+=1

retAA_ = ret1.copy()
for item in result['']:
for k in ret1:
if float(k)+0.5>item and float(k)-0.5<=item:
retAA_[k]+=1

retAA = ret1.copy()
for item in result['AA']:
for k in ret1:
if float(k)+0.5>item and float(k)-0.5<=item:
retAA[k]+=1

retAA_add = ret1.copy()
for item in result['AA+']:
for k in ret1:
if float(k)+0.5>item and float(k)-0.5<=item:
retAA_add[k]+=1

retAAA = ret1.copy()
for item in result['AAA']:
for k in ret1:
if float(k)+0.5>item and float(k)-0.5<=item:
retAAA[k]+=1

bar = Bar('可转债价格分布')
bar.add('A+',value,list(ret_A_add.values()),is_stack=True,yaxis_max=11)
bar.add('',value,list(retAA_.values()),is_stack=True,yaxis_max=11)
bar.add('AA',value,list(retAA.values()),is_stack=True,yaxis_max=11)
bar.add('AA+',value,list(retAA_add.values()),is_stack=True,yaxis_max=11)
bar.add('AAA',value,list(retAAA.values()),is_stack=True,yaxis_max=11)
如果没有安装pyecharts,需要用pip安装即可。
 

 

原创文章
转载请注明出处:
 http://30daydo.com/article/400 

  查看全部
这一节课带大家学习如何利用可视化,更好的呈现数据。
即使你有很多数据,可是,你无法直观地看到数据的总体趋势。使用可视化的绘图,可以帮助我们看到数据背后看不到的数据。 比如我已经有每一个可转债的价格,评级。数据如下:

可转债数据.JPG

 点击查看大图

如果我用下面的图形就可以看出规律:
可转债价格分布.JPG

 点击查看大图

横坐标是价格,纵坐标是落在该价格的可转债数量,不同颜色代表不同评级的可转债。
 
可以看到大部分AA-评级(浅橙色)的可转债价格都在100元以下,而AA(浅蓝色)的可转债价格分布较为平均,从90到110都有。而AA+和AAA的一般都在100以上。
 
那么如何使用代码实现呢?
from  setting import get_mysql_conn,get_engine
import pandas as pd
import pymongo
from pyecharts import Geo,Style,Map
engine = get_engine('db_stock',local='local')
# 堆叠图
from pyecharts import Bar
df = pd.read_sql('tb_bond_jisilu',con=engine)

result ={}
for name,grades in df.groupby('评级'):
# print(name,grades[['可转债名称','可转债价格']])
for each in grades['可转债价格']:
result.setdefault(name,)
result[name].append(each)


# 确定价格的范围

value = [str(i) for i in range(85,140)]
ret = [0]*len(value)
ret1 = dict(zip(value,ret))

ret_A_add = ret1.copy()
for item in result['A+']:
for k in ret1:
if float(k)+0.5>item and float(k)-0.5<=item:
ret_A_add[k]+=1

retAA_ = ret1.copy()
for item in result['']:
for k in ret1:
if float(k)+0.5>item and float(k)-0.5<=item:
retAA_[k]+=1

retAA = ret1.copy()
for item in result['AA']:
for k in ret1:
if float(k)+0.5>item and float(k)-0.5<=item:
retAA[k]+=1

retAA_add = ret1.copy()
for item in result['AA+']:
for k in ret1:
if float(k)+0.5>item and float(k)-0.5<=item:
retAA_add[k]+=1

retAAA = ret1.copy()
for item in result['AAA']:
for k in ret1:
if float(k)+0.5>item and float(k)-0.5<=item:
retAAA[k]+=1

bar = Bar('可转债价格分布')
bar.add('A+',value,list(ret_A_add.values()),is_stack=True,yaxis_max=11)
bar.add('',value,list(retAA_.values()),is_stack=True,yaxis_max=11)
bar.add('AA',value,list(retAA.values()),is_stack=True,yaxis_max=11)
bar.add('AA+',value,list(retAA_add.values()),is_stack=True,yaxis_max=11)
bar.add('AAA',value,list(retAAA.values()),is_stack=True,yaxis_max=11)

如果没有安装pyecharts,需要用pip安装即可。
 

 

原创文章
转载请注明出处:
 http://30daydo.com/article/400 

 

python数据分析之 A股上市公司按地区分布与可视化 地图显示

李魔佛 发表了文章 • 0 个评论 • 8359 次浏览 • 2018-12-19 14:07 • 来自相关话题

首先传统方法是使用数据库:SELECT area `地区`,count(*) as `数目` FROM `tb_basic_info` GROUP BY area order by 数目 desc;得到下面的结果: 接着我们使用pandas进行数据可视化。
 地区 数目
浙江 431
江苏 401
北京 316
广东 303
上海 285
深圳 283
山东 196
福建 132
四川 120
湖南 104
安徽 103
湖北 101
河南 79
辽宁 72
河北 56
新疆 54
天津 50
陕西 49
重庆 48
吉林 41
江西 41
山西 38
黑龙江 37
广西 37
云南 33
甘肃 33
海南 31
贵州 29
内蒙 25
西藏 18
宁夏 13
青海 12
看看我们的641主席的功劳,江浙一带的上市公司数量已经超过广东了。
 
接下来我们使用pandas进行数据可视化:
 
首先读入数据:# A股上市公司分布:
df = pd.read_sql('tb_basic_info',con=engine)engine为from sqlalchemy import create_engine 中的连接引擎。
 
然后直接统计:result = df['area'].value_counts()得到的result就是统计结果:





 
看是不是比mysql语句简单多了?
 
得到一样的数据。
 
接下来使用图像来显示我们的数据:





 
什么? 一条命令就可以啦~ 实在太强大了!
从这个柱状图上,可以更加直观地看到A股上市公司的分布情况,东部长三角和珠三角的公司数目最多。而西部只有东部的零头。
 
接着把数据转化为百分比数据:total = result.sum()
ration = result/total*100




可以看到江浙地区占了22%的数量,体量还是很大的。
 
接下来,为了数据更加直观,把数据在地图上显示出来:





            点击查看大图

颜色越红,表明上市公司越多。现在数据够直观了吧。
 
实现代码:# 热力图
def create_heatmap(attr,value,name,maptype):
style = Style(title_color="#fff", title_pos="center",
width=1200, height=600, background_color="#696969")

# 可视化
geo = Geo(name,**style.init_style)
geo.add("", attr, value, visual_range=[min(value), max(value)], symbol_size=8,
visual_text_color="#000",
is_visualmap=True, type='effectScatter',effect_scale=7,is_random=True,is_roam=False,is_piecewise = True,visual_split_number= 10,
)

geo.render('{}.html'.format(name)) create_heatmap(attr,value,'公司分布','china')
 

更多的数据分析,请关注本网站。
不定期更新哦
 
原创文章
转载请注明出处:
http://30daydo.com/article/388
  查看全部
首先传统方法是使用数据库:
SELECT area `地区`,count(*) as `数目` FROM `tb_basic_info` GROUP BY area order by 数目 desc;
得到下面的结果: 接着我们使用pandas进行数据可视化。
 地区 数目
浙江 431
江苏 401
北京 316
广东 303
上海 285
深圳 283
山东 196
福建 132
四川 120
湖南 104
安徽 103
湖北 101
河南 79
辽宁 72
河北 56
新疆 54
天津 50
陕西 49
重庆 48
吉林 41
江西 41
山西 38
黑龙江 37
广西 37
云南 33
甘肃 33
海南 31
贵州 29
内蒙 25
西藏 18
宁夏 13
青海 12
看看我们的641主席的功劳,江浙一带的上市公司数量已经超过广东了。
 
接下来我们使用pandas进行数据可视化:
 
首先读入数据:
# A股上市公司分布:
df = pd.read_sql('tb_basic_info',con=engine)
engine为from sqlalchemy import create_engine 中的连接引擎。
 
然后直接统计:
result = df['area'].value_counts()
得到的result就是统计结果:

地区统计_副本.jpg

 
看是不是比mysql语句简单多了?
 
得到一样的数据。
 
接下来使用图像来显示我们的数据:

地区绘图.JPG

 
什么? 一条命令就可以啦~ 实在太强大了!
从这个柱状图上,可以更加直观地看到A股上市公司的分布情况,东部长三角和珠三角的公司数目最多。而西部只有东部的零头。
 
接着把数据转化为百分比数据:
total = result.sum()
ration = result/total*100

a5.JPG

可以看到江浙地区占了22%的数量,体量还是很大的。
 
接下来,为了数据更加直观,把数据在地图上显示出来:

热力图.JPG

            点击查看大图

颜色越红,表明上市公司越多。现在数据够直观了吧。
 
实现代码:
# 热力图
def create_heatmap(attr,value,name,maptype):
style = Style(title_color="#fff", title_pos="center",
width=1200, height=600, background_color="#696969")

# 可视化
geo = Geo(name,**style.init_style)
geo.add("", attr, value, visual_range=[min(value), max(value)], symbol_size=8,
visual_text_color="#000",
is_visualmap=True, type='effectScatter',effect_scale=7,is_random=True,is_roam=False,is_piecewise = True,visual_split_number= 10,
)

geo.render('{}.html'.format(name))
 
create_heatmap(attr,value,'公司分布','china')

 

更多的数据分析,请关注本网站。
不定期更新哦
 
原创文章
转载请注明出处:
http://30daydo.com/article/388
 

np.empty() 函数的用法 (有坑)

李魔佛 发表了文章 • 0 个评论 • 44691 次浏览 • 2018-11-20 11:36 • 来自相关话题

看名字np.empty(),以为创建一个空的多维数组,如 np.empty((4,4))
但是实际结果返回:array([[4.67296746e-307, 1.69121096e-306, 9.34601642e-307,
1.33511562e-306],
[8.34447260e-308, 6.23043768e-307, 2.22522597e-306,
1.33511969e-306],
[1.37962320e-306, 9.34604358e-307, 9.79101082e-307,
1.78020576e-306],
[1.69119873e-306, 2.22522868e-306, 1.24611809e-306,
8.06632139e-308]])
what ?
 
感觉里面的元素是随机生成的。
查了下官方文档,的确是。np.empty()返回一个随机元素的矩阵,大小按照参数定义。
所以使用的时候要小心。需要手工把每一个值重新定义,否则该值是一个随机数,调试起来会比较麻烦。
 
原创文章
转载请注明出处:
http://www.30daydo.com/article/376
  查看全部
看名字np.empty(),以为创建一个空的多维数组,如 np.empty((4,4))
但是实际结果返回:
array([[4.67296746e-307, 1.69121096e-306, 9.34601642e-307,
1.33511562e-306],
[8.34447260e-308, 6.23043768e-307, 2.22522597e-306,
1.33511969e-306],
[1.37962320e-306, 9.34604358e-307, 9.79101082e-307,
1.78020576e-306],
[1.69119873e-306, 2.22522868e-306, 1.24611809e-306,
8.06632139e-308]])

what ?
 
感觉里面的元素是随机生成的。
查了下官方文档,的确是。np.empty()返回一个随机元素的矩阵,大小按照参数定义。
所以使用的时候要小心。需要手工把每一个值重新定义,否则该值是一个随机数,调试起来会比较麻烦。
 
原创文章
转载请注明出处:
http://www.30daydo.com/article/376
 

numpy logspace的用法

李魔佛 发表了文章 • 0 个评论 • 7164 次浏览 • 2018-10-28 17:54 • 来自相关话题

numpy.logspace

numpy.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)[source]

Return numbers spaced evenly on a log scale.

In linear space, the sequence starts at base ** start (base to the power of start) and ends with base ** stop (see endpoint below).

Parameters:

start : float

base ** start is the starting value of the sequence.

stop : float

base ** stop is the final value of the sequence, unless endpoint is False. In that case, num + 1 values are spaced over the interval in log-space, of which all but the last (a sequence of length num) are returned.

num : integer, optional

Number of samples to generate. Default is 50.

endpoint : boolean, optional

If true, stop is the last sample. Otherwise, it is not included. Default is True.

base : float, optional

The base of the log space. The step size between the elements in ln(samples) / ln(base) (or log_base(samples)) is uniform. Default is 10.0.

dtype : dtype

The type of the output array. If dtype is not given, infer the data type from the other input arguments.

Returns:

samples : ndarray

num samples, equally spaced on a log scale


 

上面是官方的文档,英文说的很明白,但网上尤其是csdn的解释,(其实都是你抄我,我抄你),实在让人看的一头雾水
 
numpy.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)
 
比如 np.logspace(0,10,9)
那么会有结果是:
array([1.00000000e+00, 1.77827941e+01, 3.16227766e+02, 5.62341325e+03,
1.00000000e+05, 1.77827941e+06, 3.16227766e+07, 5.62341325e+08,
1.00000000e+10])
第一位是开始值0,第二位是结束值10,然后在这0-10之间产生9个值,这9个值是均匀分布的,默认包括最后一个结束点,就是0到10的9个等产数列,那么根据等差数列的公式,a1+(n-1)*d=an,算出,d=1.25,那么a1=0,接着a2=1.25,a3=2.5,。。。。。a9=10,然后再对这9个值做已10为底的指数运算,也就是10^0, 10^1.25 , 10^2.5 这样的结果 查看全部


numpy.logspace

numpy.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)[source]

Return numbers spaced evenly on a log scale.

In linear space, the sequence starts at base ** start (base to the power of start) and ends with base ** stop (see endpoint below).

Parameters:

start : float

base ** start is the starting value of the sequence.

stop : float

base ** stop is the final value of the sequence, unless endpoint is False. In that case, num + 1 values are spaced over the interval in log-space, of which all but the last (a sequence of length num) are returned.

num : integer, optional

Number of samples to generate. Default is 50.

endpoint : boolean, optional

If true, stop is the last sample. Otherwise, it is not included. Default is True.

base : float, optional

The base of the log space. The step size between the elements in ln(samples) / ln(base) (or log_base(samples)) is uniform. Default is 10.0.

dtype : dtype

The type of the output array. If dtype is not given, infer the data type from the other input arguments.

Returns:

samples : ndarray

num samples, equally spaced on a log scale



 


上面是官方的文档,英文说的很明白,但网上尤其是csdn的解释,(其实都是你抄我,我抄你),实在让人看的一头雾水
 
numpy.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)
 
比如 np.logspace(0,10,9)
那么会有结果是:
array([1.00000000e+00, 1.77827941e+01, 3.16227766e+02, 5.62341325e+03,
1.00000000e+05, 1.77827941e+06, 3.16227766e+07, 5.62341325e+08,
1.00000000e+10])

第一位是开始值0,第二位是结束值10,然后在这0-10之间产生9个值,这9个值是均匀分布的,默认包括最后一个结束点,就是0到10的9个等产数列,那么根据等差数列的公式,a1+(n-1)*d=an,算出,d=1.25,那么a1=0,接着a2=1.25,a3=2.5,。。。。。a9=10,然后再对这9个值做已10为底的指数运算,也就是10^0, 10^1.25 , 10^2.5 这样的结果

np.asfarray的用法

李魔佛 发表了文章 • 0 个评论 • 9374 次浏览 • 2018-09-24 10:52 • 来自相关话题

以前很少用的一个函数,见到别人的代码里面有,所以查了下文档,看看该函数的用法。
numpy.asfarray(a, dtype=<class 'numpy.float64'>)

Return an array converted to a float type.

Parameters:
a : array_like
The input array.

dtype : str or dtype object, optional
Float type code to coerce input array a. If dtype is one of the ‘int’ dtypes, it is replaced with float64.

Returns:
out : ndarray
The input a as a float ndarray.
用法就是把一个普通的数组转为一个浮点类型的数组:
 
Examples

>>>
>>> np.asfarray([2, 3])
array([ 2., 3.])
>>> np.asfarray([2, 3], dtype='float')
array([ 2., 3.])
>>> np.asfarray([2, 3], dtype='int8')
array([ 2., 3.]) 查看全部
以前很少用的一个函数,见到别人的代码里面有,所以查了下文档,看看该函数的用法。
numpy.asfarray(a, dtype=<class 'numpy.float64'>)

Return an array converted to a float type.

Parameters:
a : array_like
The input array.

dtype : str or dtype object, optional
Float type code to coerce input array a. If dtype is one of the ‘int’ dtypes, it is replaced with float64.

Returns:
out : ndarray
The input a as a float ndarray.

用法就是把一个普通的数组转为一个浮点类型的数组:
 
Examples

>>>
>>> np.asfarray([2, 3])
array([ 2., 3.])
>>> np.asfarray([2, 3], dtype='float')
array([ 2., 3.])
>>> np.asfarray([2, 3], dtype='int8')
array([ 2., 3.])

tushare 调用ts.get_apis() 后一直在运行无法退出

李魔佛 发表了文章 • 0 个评论 • 4745 次浏览 • 2018-03-16 00:47 • 来自相关话题

旧版本中运行ts.get_apis()后会一直在后台监听,但是在1.0.5的后续版本中,你可以手工中断这个后台监听,从而让你的程序可以正常退出。
 
conn=ts.get_apis()
......
 
在你的程序退出前,运行
ts.close_apis(conn)
 
这样你的程序就能够正常退出。 查看全部
旧版本中运行ts.get_apis()后会一直在后台监听,但是在1.0.5的后续版本中,你可以手工中断这个后台监听,从而让你的程序可以正常退出。
 
conn=ts.get_apis()
......
 
在你的程序退出前,运行
ts.close_apis(conn)
 
这样你的程序就能够正常退出。

【量化选股】A股上有哪些东北股(排雷)?

李魔佛 发表了文章 • 0 个评论 • 3356 次浏览 • 2018-01-31 01:09 • 来自相关话题

上一篇文章中写道,东北企业由于本地特色,会存在一定的造假风险,所以需要在选股的时候排除东北的A股上市企业。
 
打开jupyter notebook。然后输入下面的代码:





 
上面可以获得A股上市公司所有区域的分布。果然刘士余上台后,浙江地区的企业一下子超越广东,成为A股最多公司的省份(当然,这里的广东是把深圳给单独分离出去了),浙江有418个上市公司。
 
然后根据条件筛选列area,选出辽宁,吉林,黑龙江的企业。





共有152家上市公司。截止2018-01-30日。
列表太长没有显示完整,贴在附件里面供大家参考(排雷)。
 
原文地址:http://30daydo.com/article/271
转载请注明出处 查看全部
上一篇文章中写道,东北企业由于本地特色,会存在一定的造假风险,所以需要在选股的时候排除东北的A股上市企业。
 
打开jupyter notebook。然后输入下面的代码:

area.GIF

 
上面可以获得A股上市公司所有区域的分布。果然刘士余上台后,浙江地区的企业一下子超越广东,成为A股最多公司的省份(当然,这里的广东是把深圳给单独分离出去了),浙江有418个上市公司。
 
然后根据条件筛选列area,选出辽宁,吉林,黑龙江的企业。

area1.GIF

共有152家上市公司。截止2018-01-30日。
列表太长没有显示完整,贴在附件里面供大家参考(排雷)。
 
原文地址:http://30daydo.com/article/271
转载请注明出处

python获取A股上市公司的盈利能力

李魔佛 发表了文章 • 0 个评论 • 6717 次浏览 • 2018-01-04 16:09 • 来自相关话题

利用tushare库,可以很方便的获取A股上市公司的基本面信息。
比如企业的盈利能力。
 import tushare as ts
#获取2017年第3季度的盈利能力数据
ts.get_profit_data(2017,3)返回的结果:
 
按年度、季度获取盈利能力数据,结果返回的数据属性说明如下:
code,代码 
name,名称 
roe,净资产收益率(%)
 net_profit_ratio,净利率(%) 
gross_profit_rate,毛利率(%) 
net_profits,净利润(百万元)  #这里的官网信息有误,单位应该是百万
esp,每股收益 
business_income,营业收入(百万元) 
bips,每股主营业务收入(元)
 
例如返回如下结果:
 
    code   name    roe  net_profit_ratio  gross_profit_rate  net_profits  \
  000717   韶钢松山  79.22              9.44            14.1042    1750.2624
  600793   宜宾纸业  65.40             13.31             7.9084     100.6484
  600306    商业城  63.19             18.55            17.8601     114.9175
  000526  *ST紫学  61.03              2.78            31.1212      63.6477
  600768   宁波富邦  57.83             14.95             2.7349      88.3171
 
原创,转载请注明:
http://30daydo.com/article/260
  查看全部
利用tushare库,可以很方便的获取A股上市公司的基本面信息。
比如企业的盈利能力。
 
import tushare as ts
#获取2017年第3季度的盈利能力数据
ts.get_profit_data(2017,3)
返回的结果:
 
按年度、季度获取盈利能力数据,结果返回的数据属性说明如下:
code,代码 
name,名称 
roe,净资产收益率(%)
 net_profit_ratio,净利率(%) 
gross_profit_rate,毛利率(%) 
net_profits,净利润(百万元)  #这里的官网信息有误,单位应该是百万
esp,每股收益 
business_income,营业收入(百万元) 
bips,每股主营业务收入(元)
 
例如返回如下结果:
 
    code   name    roe  net_profit_ratio  gross_profit_rate  net_profits  \
  000717   韶钢松山  79.22              9.44            14.1042    1750.2624
  600793   宜宾纸业  65.40             13.31             7.9084     100.6484
  600306    商业城  63.19             18.55            17.8601     114.9175
  000526  *ST紫学  61.03              2.78            31.1212      63.6477
  600768   宁波富邦  57.83             14.95             2.7349      88.3171
 
原创,转载请注明:
http://30daydo.com/article/260
 

dataframe reindex和reset_index区别

李魔佛 发表了文章 • 0 个评论 • 83203 次浏览 • 2017-12-30 15:58 • 来自相关话题

reset_index的作用是重新设置dataframe的index,范围为0~len(df)。 df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [10, 20, 30, 40, 50]})
df2 = pd.DataFrame({'A': [6], 'B': [60]})
print('df', df)
print('df2', df2)

df_x = [df, df2]
result = pd.concat(df_x)
print('first result ', result) 
上面代码把df和df2合并为一个result,但是result的index是乱的。





 
那么执行result2= result.reset_index()
得到如下的result2: (默认只是返回一个copy,原来的result没有发生改变,所以需要副本赋值给result2)





可以看到,原来的一列index现在变成了columns之一,新的index为[0,1,2,3,4,5]
如果添加参数 reset_index(drop=True) 那么原index会被丢弃,不会显示为一个新列。result2 = result.reset_index(drop=True)



 
reindex的作用是按照原有的列进行重新生成一个新的df。
 
还是使用上面的代码
result目前是df和df2的合并序列。
如下:




 
可以看到index为[0,1,2,3,4,0]
执行 result3 = result.reindex(columns=['A','C'])




 
可以看到,原index并没有发生改变,而列变成了A和C,因为C是不存在的,所以使用了NaB填充,这个值的内容可以自己填充,可以改为默认填充0或者任意你想要的数据。reindex(columns=..)的作用类似于重新把列的顺序整理一遍, 而使用reindex(index=....) 则按照行重新整理一遍。

原文链接:http://30daydo.com/article/257 
欢迎转载,注明出处
  查看全部
reset_index的作用是重新设置dataframe的index,范围为0~len(df)。
    df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [10, 20, 30, 40, 50]})
df2 = pd.DataFrame({'A': [6], 'B': [60]})
print('df', df)
print('df2', df2)

df_x = [df, df2]
result = pd.concat(df_x)
print('first result ', result)
 
上面代码把df和df2合并为一个result,但是result的index是乱的。

df4.PNG

 
那么执行
result2= result.reset_index()

得到如下的result2: (默认只是返回一个copy,原来的result没有发生改变,所以需要副本赋值给result2)

df5.PNG

可以看到,原来的一列index现在变成了columns之一,新的index为[0,1,2,3,4,5]
如果添加参数 reset_index(drop=True) 那么原index会被丢弃,不会显示为一个新列。
result2 = result.reset_index(drop=True)
df6.PNG

 
reindex的作用是按照原有的列进行重新生成一个新的df。
 
还是使用上面的代码
result目前是df和df2的合并序列。
如下:
df7.PNG

 
可以看到index为[0,1,2,3,4,0]
执行 
result3 = result.reindex(columns=['A','C'])

df8.PNG

 
可以看到,原index并没有发生改变,而列变成了A和C,因为C是不存在的,所以使用了NaB填充,这个值的内容可以自己填充,可以改为默认填充0或者任意你想要的数据。reindex(columns=..)的作用类似于重新把列的顺序整理一遍, 而使用reindex(index=....) 则按照行重新整理一遍。

原文链接:http://30daydo.com/article/257 
欢迎转载,注明出处
 

dataframe的index索引是否可以重复

李魔佛 发表了文章 • 0 个评论 • 11416 次浏览 • 2017-12-30 15:10 • 来自相关话题

答案是肯定的。
  df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [10, 20, 30, 40, 50]})
df2 = pd.DataFrame({'A': [6], 'B': [60]})
print 'df\n', df
print 'df2\n', df2输出如下:
df1





df2




 
然后进行合并: df_x = [df, df2]
result = pd.concat(df_x)
print 'first result\n', result
合并后的结果:





 
合并后的index是[0,1,2,3,4,0] 所以index集合是一个类似list的结构,而非set结构,允许重复数据的存在。
 
原文链接:http://30daydo.com/article/256 
转载请注明
 
  查看全部
答案是肯定的。
 
    df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [10, 20, 30, 40, 50]})
df2 = pd.DataFrame({'A': [6], 'B': [60]})
print 'df\n', df
print 'df2\n', df2
输出如下:
df1
df.PNG


df2
df2.PNG

 
然后进行合并:
    df_x = [df, df2]
result = pd.concat(df_x)
print 'first result\n', result

合并后的结果:

dfx.PNG

 
合并后的index是[0,1,2,3,4,0] 所以index集合是一个类似list的结构,而非set结构,允许重复数据的存在。
 
原文链接:http://30daydo.com/article/256 
转载请注明
 
 

tushare使用get_stock_basic()保存为excel会因为乱码出错而无法保存

李魔佛 发表了文章 • 0 个评论 • 7365 次浏览 • 2017-12-30 13:11 • 来自相关话题

代码如下:
basic=ts.get_stock_basics()

print basic.info()
print basic.head(10)

basic.to_excel('basic2017.xls',encoding='gbk')
运行后会出错:

'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
 
很明显的是编问题。 
 
然后尝试使用解决编码的步骤。
1. reload(sys) 设置default为utf-8: 失败
2. to_excel('stock.xls',encoding='gbk') : 失败,encoding参数换了几个都是失败,utf-8,gb2312,cp1252
 
最后解决的办法是,先把df保存为csv,然后再从csv从读取出来,然后再存储为excel。 整个过程的encoding参数都是用'gbk'.
basic.to_csv('2017_all_price_change.xls',encoding='gbk')
df=pd.read_csv('2017_all_price_change.xls',encoding='gbk')
df.to_excel('2017_all_price_change.xls',encoding='gbk')
  查看全部
代码如下:
    basic=ts.get_stock_basics()

print basic.info()
print basic.head(10)

basic.to_excel('basic2017.xls',encoding='gbk')

运行后会出错:

'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
 
很明显的是编问题。 
 
然后尝试使用解决编码的步骤。
1. reload(sys) 设置default为utf-8: 失败
2. to_excel('stock.xls',encoding='gbk') : 失败,encoding参数换了几个都是失败,utf-8,gb2312,cp1252
 
最后解决的办法是,先把df保存为csv,然后再从csv从读取出来,然后再存储为excel。 整个过程的encoding参数都是用'gbk'.
    basic.to_csv('2017_all_price_change.xls',encoding='gbk')
df=pd.read_csv('2017_all_price_change.xls',encoding='gbk')
df.to_excel('2017_all_price_change.xls',encoding='gbk')

 

pandas to_excel函数参数中的文件名需要为.xls

李魔佛 发表了文章 • 0 个评论 • 11313 次浏览 • 2017-12-29 18:10 • 来自相关话题

例如 df.to_excel('2017-analysis')
会报错。
ValueError: No engine for filetype: ''

需要把文件名也命名为'2017-analysis.xls' 才能过正常运行。
 
不同于其他本文格式,可以随意命名后缀,然后生成文件后再修改后缀。
  查看全部
例如 df.to_excel('2017-analysis')
会报错。
ValueError: No engine for filetype: ''

需要把文件名也命名为'2017-analysis.xls' 才能过正常运行。
 
不同于其他本文格式,可以随意命名后缀,然后生成文件后再修改后缀。
 

Dataframe中的plot函数绘图会把日期index自动补全

李魔佛 发表了文章 • 0 个评论 • 5981 次浏览 • 2017-12-26 14:49 • 来自相关话题

代码如下:
df=pd.read_excel('600050.xls',dtype={'datetime':np.datetime64})
df=df.set_index('datetime')
df['close'].plot(use_index=True,grid=True)
plt.show()
df为中国联通的日线数据,跨度为2016年到2017年底,中间有过一段时间的停牌。 用上面的代码绘制出来的曲线图,回发现,横坐标是日期,可是图中居然会把停牌的日子也插进去,这样导致了图形中间出现了一条长长的折线。
因为停牌后,股价是是不会变化的。 
  查看全部
代码如下:
	df=pd.read_excel('600050.xls',dtype={'datetime':np.datetime64})
df=df.set_index('datetime')
df['close'].plot(use_index=True,grid=True)
plt.show()

df为中国联通的日线数据,跨度为2016年到2017年底,中间有过一段时间的停牌。 用上面的代码绘制出来的曲线图,回发现,横坐标是日期,可是图中居然会把停牌的日子也插进去,这样导致了图形中间出现了一条长长的折线。
因为停牌后,股价是是不会变化的。 
 

pandas dataframe read_excel读取的列设置为日期类型datetime

李魔佛 发表了文章 • 0 个评论 • 22000 次浏览 • 2017-12-25 17:53 • 来自相关话题

比如excel中有一列是日期:





 
如果使用函数 pd.read_excel('xxx.xls') 读入,那么日期列实际会被认为是一个non-null object 类型,虽然可以后期对这个格式进行转换,但其实可以加入一个参数dtype, 就可以在读excel的时候就指定某列的数据类型。
 
pd.read_excel('xxx.xls',dtype={'出生日期':np.datetime64}
 
注意np中的datetime类型是datetime64. 查看全部
比如excel中有一列是日期:

timg.jpg

 
如果使用函数 pd.read_excel('xxx.xls') 读入,那么日期列实际会被认为是一个non-null object 类型,虽然可以后期对这个格式进行转换,但其实可以加入一个参数dtype, 就可以在读excel的时候就指定某列的数据类型。
 
pd.read_excel('xxx.xls',dtype={'出生日期':np.datetime64}
 
注意np中的datetime类型是datetime64.

菜鸟侦探挑战数据分析R源代码

李魔佛 发表了文章 • 0 个评论 • 2925 次浏览 • 2017-12-11 17:45 • 来自相关话题

菜鸟侦探挑战数据分析R源代码:
百度网盘下载链接:
https://pan.baidu.com/s/1miiScDM
 
菜鸟侦探挑战数据分析R源代码:
百度网盘下载链接:
https://pan.baidu.com/s/1miiScDM
 

TypeError: reduction operation 'argmin' not allowed for this dtype

李魔佛 发表了文章 • 0 个评论 • 11338 次浏览 • 2017-11-19 18:48 • 来自相关话题

使用pd.read_sql() 方法把Mysql的数据库转为dataframe后,使用 df['low'].idxmin() 或者df['low'].argmin() 方法是会出现这个错误。
 
date = date + '-01-01'
cmd = 'select * from `{}` where datetime > \'{}\''.format(code, date)

try:
df = pd.read_sql(cmd, history_engine,index_col='index')
except Exception,e:
print e
return None

# 不知道为啥,这里的类型发生改变
idx= df['low'].idxmin() 
 
TypeError: reduction operation 'argmin' not allowed for this dtype
 
把df的每列数据类型打印出来看看。
 
print df.dtypes
 
datetime datetime64[ns]
code object
name object
open object
close object
high object
low object
vol float64
amount float64
dtype: object
晕,居然把low这些float类型全部转为了object,所以解决办法就是把这些列的数据转为float64.
 
df['low']=df['low'].astype('float64')
这样之后,问题就解决了。
  查看全部
使用pd.read_sql() 方法把Mysql的数据库转为dataframe后,使用 df['low'].idxmin() 或者df['low'].argmin() 方法是会出现这个错误。
 
date = date + '-01-01'
cmd = 'select * from `{}` where datetime > \'{}\''.format(code, date)

try:
df = pd.read_sql(cmd, history_engine,index_col='index')
except Exception,e:
print e
return None

# 不知道为啥,这里的类型发生改变
idx= df['low'].idxmin()
 
 
TypeError: reduction operation 'argmin' not allowed for this dtype
 
把df的每列数据类型打印出来看看。
 
print df.dtypes
 
datetime    datetime64[ns]
code object
name object
open object
close object
high object
low object
vol float64
amount float64
dtype: object

晕,居然把low这些float类型全部转为了object,所以解决办法就是把这些列的数据转为float64.
 
df['low']=df['low'].astype('float64')

这样之后,问题就解决了。
 

TA-Lib中MOM的计算公式

李魔佛 发表了文章 • 0 个评论 • 6984 次浏览 • 2017-05-29 01:38 • 来自相关话题

MOM是价格动能。
 TA-Lib中MOM的参数有
ouput=talib.MOM(closed,timeperiod=5)
 
closed是你传入的价格list,可以是每天的收盘价,开盘价,或者你想要计算的所有价格。
timeperiod是你要计算的时间周期。
 
假如timeperiod=5,那么,这个计算的输出值就是 p5-p0, 如果今天是1月6日,股价为14块,而1月1日的股价为12块,那么这里通过MOM运算,得出来的就是14-12=2 这个值了。 然后如此类推,如果今天是1月7日,股价为15块,而1月2日股价为11块,那么MOM得出的是4,这样子获取到所有的值,绘制成曲线,就是MOM的曲线了。 查看全部
MOM是价格动能。
 TA-Lib中MOM的参数有
ouput=talib.MOM(closed,timeperiod=5)
 
closed是你传入的价格list,可以是每天的收盘价,开盘价,或者你想要计算的所有价格。
timeperiod是你要计算的时间周期。
 
假如timeperiod=5,那么,这个计算的输出值就是 p5-p0, 如果今天是1月6日,股价为14块,而1月1日的股价为12块,那么这里通过MOM运算,得出来的就是14-12=2 这个值了。 然后如此类推,如果今天是1月7日,股价为15块,而1月2日股价为11块,那么MOM得出的是4,这样子获取到所有的值,绘制成曲线,就是MOM的曲线了。

TA-Lib 量化交易代码实例 <二> 获取布林线的上轨,中轨,下轨的数据

李魔佛 发表了文章 • 0 个评论 • 24403 次浏览 • 2017-05-28 23:08 • 来自相关话题

BOLL指标的原理
BOLL指标是美国股市分析家约翰·布林根据统计学中的标准差原理设计出来的一种非常简单实用的技术分析指标。一般而言,股价的运动总是围绕某一价值中枢(如均线、成本线等)在一定的范围内变动,布林线指标指标正是在上述条件的基础上,引进了“股价通道”的概念,其认为股价通道的宽窄随着股价波动幅度的大小而变化,而且股价通道又具有变异性,它会随着股价的变化而自动调整。正是由于它具有灵活性、直观性和趋势性的特点,BOLL指标渐渐成为投资者广为应用的市场上热门指标。
在众多技术分析指标中,BOLL指标属于比较特殊的一类指标。绝大多数技术分析指标都是通过数量的方法构造出来的,它们本身不依赖趋势分析和形态分析,而BOLL指标却股价的形态和趋势有着密不可分的联系。BOLL指标中的“股价通道”概念正是股价趋势理论的直观表现形式。BOLL是利用“股价通道”来显示股价的各种价位,当股价波动很小,处于盘整时,股价通道就会变窄,这可能预示着股价的波动处于暂时的平静期;当股价波动超出狭窄的股价通道的上轨时,预示着股价的异常激烈的向上波动即将开始;当股价波动超出狭窄的股价通道的下轨时,同样也预示着股价的异常激烈的向下波动将开始。
投资者常常会遇到两种最常见的交易陷阱,一是买低陷阱,投资者在所谓的低位买进之后,股价不仅没有止跌反而不断下跌;二是卖高陷阱,股票在所谓的高点卖出后,股价却一路上涨。布林线特别运用了爱因斯坦的相对论,认为各类市场间都是互动的,市场内和市场间的各种变化都是相对性的,是不存在绝对性的,股价的高低是相对的,股价在上轨线以上或在下轨线以下只反映该股股价相对较高或较低,投资者作出投资判断前还须综合参考其他技术指标,包括价量配合,心理类指标,类比类指标,市场间的关联数据等。
总之,BOLL指标中的股价通道对预测未来行情的走势起着重要的参考作用,它也是布林线指标所特有的分析手段。
[编辑]
BOLL指标的计算方法
在所有的指标计算中,BOLL指标的计算方法是最复杂的之一,其中引进了统计学中的标准差概念,涉及到中轨线(MB)、上轨线(UP)和下轨线(DN)的计算。另外,和其他指标的计算一样,由于选用的计算周期的不同,BOLL指标也包括日BOLL指标、周BOLL指标、月BOLL指标年BOLL指标以及分钟BOLL指标等各种类型。经常被用于股市研判的是日BOLL指标和周BOLL指标。虽然它们的计算时的取值有所不同,但基本的计算方法一样。以日BOLL指标计算为例,其计算方法如下:
1、日BOLL指标的计算公式
中轨线=N日的移动平均线
上轨线=中轨线+两倍的标准差
下轨线=中轨线-两倍的标准差
2、日BOLL指标的计算过程
1)计算MA
MA=N日内的收盘价之和÷N2)计算标准差MD
MD=平方根N日的(C-MA)的两次方之和除以N3)计算MB、UP、DN线
MB=(N-1)日的MA
UP=MB+2×MD
DN=MB-2×MD在股市分析软件中,BOLL指标一共由四条线组成,即上轨线UP 、中轨线MB、下轨线DN和价格线。其中上轨线UP是UP数值的连线,用黄色线表示;中轨线MB是MB数值的连线,用白色线表示;下轨线DN是DN数值的连线,用紫色线表示;价格线是以美国线表示,颜色为浅蓝色。和其他技术指标一样,在实战中,投资者不需要进行BOLL指标的计算,主要是了解BOLL的计算方法和过程,以便更加深入地掌握BOLL指标的实质,为运用指标打下基础。
 
#通过tushare获取股票信息
df=ts.get_k_data('300580',start='2017-01-12',end='2017-05-26')
#提取收盘价
closed=df['close'].values

upper,middle,lower=talib.BBANDS(closed,matype=talib.MA_Type.T3)

print upper,middle,lower
plt.plot(upper)
plt.plot(middle)
plt.plot(lower)
plt.grid()
plt.show()
diff1=upper-middle
diff2=middle-lower
print diff1
print diff2





 
最后那里可以看到diff1和diff2是一样的。 验证了布林线的定义ma+2d,m-2d。 查看全部

BOLL指标的原理
BOLL指标是美国股市分析家约翰·布林根据统计学中的标准差原理设计出来的一种非常简单实用的技术分析指标。一般而言,股价的运动总是围绕某一价值中枢(如均线、成本线等)在一定的范围内变动,布林线指标指标正是在上述条件的基础上,引进了“股价通道”的概念,其认为股价通道的宽窄随着股价波动幅度的大小而变化,而且股价通道又具有变异性,它会随着股价的变化而自动调整。正是由于它具有灵活性、直观性和趋势性的特点,BOLL指标渐渐成为投资者广为应用的市场上热门指标。
在众多技术分析指标中,BOLL指标属于比较特殊的一类指标。绝大多数技术分析指标都是通过数量的方法构造出来的,它们本身不依赖趋势分析和形态分析,而BOLL指标却股价的形态和趋势有着密不可分的联系。BOLL指标中的“股价通道”概念正是股价趋势理论的直观表现形式。BOLL是利用“股价通道”来显示股价的各种价位,当股价波动很小,处于盘整时,股价通道就会变窄,这可能预示着股价的波动处于暂时的平静期;当股价波动超出狭窄的股价通道的上轨时,预示着股价的异常激烈的向上波动即将开始;当股价波动超出狭窄的股价通道的下轨时,同样也预示着股价的异常激烈的向下波动将开始。
投资者常常会遇到两种最常见的交易陷阱,一是买低陷阱,投资者在所谓的低位买进之后,股价不仅没有止跌反而不断下跌;二是卖高陷阱,股票在所谓的高点卖出后,股价却一路上涨。布林线特别运用了爱因斯坦的相对论,认为各类市场间都是互动的,市场内和市场间的各种变化都是相对性的,是不存在绝对性的,股价的高低是相对的,股价在上轨线以上或在下轨线以下只反映该股股价相对较高或较低,投资者作出投资判断前还须综合参考其他技术指标,包括价量配合,心理类指标,类比类指标,市场间的关联数据等。
总之,BOLL指标中的股价通道对预测未来行情的走势起着重要的参考作用,它也是布林线指标所特有的分析手段。
[编辑]
BOLL指标的计算方法
在所有的指标计算中,BOLL指标的计算方法是最复杂的之一,其中引进了统计学中的标准差概念,涉及到中轨线(MB)、上轨线(UP)和下轨线(DN)的计算。另外,和其他指标的计算一样,由于选用的计算周期的不同,BOLL指标也包括日BOLL指标、周BOLL指标、月BOLL指标年BOLL指标以及分钟BOLL指标等各种类型。经常被用于股市研判的是日BOLL指标和周BOLL指标。虽然它们的计算时的取值有所不同,但基本的计算方法一样。以日BOLL指标计算为例,其计算方法如下:
1、日BOLL指标的计算公式
中轨线=N日的移动平均线
上轨线=中轨线+两倍的标准差
下轨线=中轨线-两倍的标准差
2、日BOLL指标的计算过程
1)计算MA
MA=N日内的收盘价之和÷N2)计算标准差MD
MD=平方根N日的(C-MA)的两次方之和除以N3)计算MB、UP、DN线
MB=(N-1)日的MA
UP=MB+2×MD
DN=MB-2×MD在股市分析软件中,BOLL指标一共由四条线组成,即上轨线UP 、中轨线MB、下轨线DN和价格线。其中上轨线UP是UP数值的连线,用黄色线表示;中轨线MB是MB数值的连线,用白色线表示;下轨线DN是DN数值的连线,用紫色线表示;价格线是以美国线表示,颜色为浅蓝色。和其他技术指标一样,在实战中,投资者不需要进行BOLL指标的计算,主要是了解BOLL的计算方法和过程,以便更加深入地掌握BOLL指标的实质,为运用指标打下基础。
 
    #通过tushare获取股票信息
df=ts.get_k_data('300580',start='2017-01-12',end='2017-05-26')
#提取收盘价
closed=df['close'].values

upper,middle,lower=talib.BBANDS(closed,matype=talib.MA_Type.T3)

print upper,middle,lower
plt.plot(upper)
plt.plot(middle)
plt.plot(lower)
plt.grid()
plt.show()
diff1=upper-middle
diff2=middle-lower
print diff1
print diff2


布林线.PNG

 
最后那里可以看到diff1和diff2是一样的。 验证了布林线的定义ma+2d,m-2d。

TA-Lib 量化交易代码实例 <一> 获取5日,10日,20日均线数据

李魔佛 发表了文章 • 0 个评论 • 23971 次浏览 • 2017-05-28 21:37 • 来自相关话题

第一节
 
安装教程在前面内容已经介绍过了,对于新手也是有点障碍,可以参照前面的文章进行一步一步操作。 http://30daydo.com/article/195 #通过tushare获取股票信息
df=ts.get_k_data('300580',start='2017-01-12',end='2017-05-26')
#提取收盘价
closed=df['close'].values
#获取均线的数据,通过timeperiod参数来分别获取 5,10,20 日均线的数据。
ma5=talib.SMA(closed,timeperiod=5)
ma10=talib.SMA(closed,timeperiod=10)
ma20=talib.SMA(closed,timeperiod=20)

#打印出来每一个数据
print closed
print ma5
print ma10
print ma20

#通过plog函数可以很方便的绘制出每一条均线
plt.plot(closed)
plt.plot(ma5)
plt.plot(ma10)
plt.plot(ma20)
#添加网格,可有可无,只是让图像好看点
plt.grid()
#记得加这一句,不然不会显示图像
plt.show()
上面第一句使用tushare获取股票的数据,如果不知道怎么操作的,可以在这里参考,同样是入门的教程。
http://30daydo.com/article/13
 
 
运行上面的代码后,可以得到下面的曲线:
 





 
你们可以去对比一下贝斯特的收盘价,5日,10日,20日均线。是不是一样的?
就这样我们就完成了均线的获取。 是不是很简单?
 
 
  查看全部
第一节
 
安装教程在前面内容已经介绍过了,对于新手也是有点障碍,可以参照前面的文章进行一步一步操作。 http://30daydo.com/article/195
    #通过tushare获取股票信息
df=ts.get_k_data('300580',start='2017-01-12',end='2017-05-26')
#提取收盘价
closed=df['close'].values
#获取均线的数据,通过timeperiod参数来分别获取 5,10,20 日均线的数据。
ma5=talib.SMA(closed,timeperiod=5)
ma10=talib.SMA(closed,timeperiod=10)
ma20=talib.SMA(closed,timeperiod=20)

#打印出来每一个数据
print closed
print ma5
print ma10
print ma20

#通过plog函数可以很方便的绘制出每一条均线
plt.plot(closed)
plt.plot(ma5)
plt.plot(ma10)
plt.plot(ma20)
#添加网格,可有可无,只是让图像好看点
plt.grid()
#记得加这一句,不然不会显示图像
plt.show()

上面第一句使用tushare获取股票的数据,如果不知道怎么操作的,可以在这里参考,同样是入门的教程。
http://30daydo.com/article/13
 
 
运行上面的代码后,可以得到下面的曲线:
 

贝斯特曲线.PNG

 
你们可以去对比一下贝斯特的收盘价,5日,10日,20日均线。是不是一样的?
就这样我们就完成了均线的获取。 是不是很简单?
 
 
 

量化工具TA-Lib 使用例子

李魔佛 发表了文章 • 0 个评论 • 18269 次浏览 • 2017-05-26 23:51 • 来自相关话题

http://30daydo.com/article/196
 TA-Lib主要用来计算一些股市中常见的指标。
比如MACD,BOLL,均线等参数。
 #-*-coding=utf-8-*-
import Tkinter as tk
from Tkinter import *
import ttk
import matplotlib.pyplot as plt

import numpy as np
import talib as ta

series = np.random.choice([1, -1], size=200)
close = np.cumsum(series).astype(float)

# 重叠指标
def overlap_process(event):
print(event.widget.get())
overlap = event.widget.get()

upperband, middleband, lowerband = ta.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)
fig, axes = plt.subplots(2, 1, sharex=True)
ax1, ax2 = axes[0], axes[1]
axes[0].plot(close, '', markersize=3)
axes[0].plot(upperband, '')
axes[0].plot(middleband, '')
axes[0].plot(lowerband, '')
axes[0].set_title(overlap, fontproperties="SimHei")

if overlap == '布林线':
pass
elif overlap == '双指数移动平均线':
real = ta.DEMA(close, timeperiod=30)
axes[1].plot(real, '')
elif overlap == '指数移动平均线 ':
real = ta.EMA(close, timeperiod=30)
axes[1].plot(real, '')
elif overlap == '希尔伯特变换——瞬时趋势线':
real = ta.HT_TRENDLINE(close)
axes[1].plot(real, '')
elif overlap == '考夫曼自适应移动平均线':
real = ta.KAMA(close, timeperiod=30)
axes[1].plot(real, '')
elif overlap == '移动平均线':
real = ta.MA(close, timeperiod=30, matype=0)
axes[1].plot(real, '')
elif overlap == 'MESA自适应移动平均':
mama, fama = ta.MAMA(close, fastlimit=0, slowlimit=0)
axes[1].plot(mama, '')
axes[1].plot(fama, '')
elif overlap == '变周期移动平均线':
real = ta.MAVP(close, periods, minperiod=2, maxperiod=30, matype=0)
axes[1].plot(real, '')
elif overlap == '简单移动平均线':
real = ta.SMA(close, timeperiod=30)
axes[1].plot(real, '')
elif overlap == '三指数移动平均线(T3)':
real = ta.T3(close, timeperiod=5, vfactor=0)
axes[1].plot(real, '')
elif overlap == '三指数移动平均线':
real = ta.TEMA(close, timeperiod=30)
axes[1].plot(real, '')
elif overlap == '三角形加权法 ':
real = ta.TRIMA(close, timeperiod=30)
axes[1].plot(real, '')
elif overlap == '加权移动平均数':
real = ta.WMA(close, timeperiod=30)
axes[1].plot(real, '')
plt.show()

# 动量指标
def momentum_process(event):
print(event.widget.get())
momentum = event.widget.get()

upperband, middleband, lowerband = ta.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)
fig, axes = plt.subplots(2, 1, sharex=True)
ax1, ax2 = axes[0], axes[1]
axes[0].plot(close, '', markersize=3)
axes[0].plot(upperband, '')
axes[0].plot(middleband, '')
axes[0].plot(lowerband, '')
axes[0].set_title(momentum, fontproperties="SimHei")

if momentum == '绝对价格振荡器':
real = ta.APO(close, fastperiod=12, slowperiod=26, matype=0)
axes[1].plot(real, '')
elif momentum == '钱德动量摆动指标':
real = ta.CMO(close, timeperiod=14)
axes[1].plot(real, '')
elif momentum == '移动平均收敛/散度':
macd, macdsignal, macdhist = ta.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9)
axes[1].plot(macd, '')
axes[1].plot(macdsignal, '')
axes[1].plot(macdhist, '')
elif momentum == '带可控MA类型的MACD':
macd, macdsignal, macdhist = ta.MACDEXT(close, fastperiod=12, fastmatype=0, slowperiod=26, slowmatype=0, signalperiod=9, signalmatype=0)
axes[1].plot(macd, '')
axes[1].plot(macdsignal, '')
axes[1].plot(macdhist, '')
elif momentum == '移动平均收敛/散度 固定 12/26':
macd, macdsignal, macdhist = ta.MACDFIX(close, signalperiod=9)
axes[1].plot(macd, '')
axes[1].plot(macdsignal, '')
axes[1].plot(macdhist, '')
elif momentum == '动量':
real = ta.MOM(close, timeperiod=10)
axes[1].plot(real, '')
elif momentum == '比例价格振荡器':
real = ta.PPO(close, fastperiod=12, slowperiod=26, matype=0)
axes[1].plot(real, '')
elif momentum == '变化率':
real = ta.ROC(close, timeperiod=10)
axes[1].plot(real, '')
elif momentum == '变化率百分比':
real = ta.ROCP(close, timeperiod=10)
axes[1].plot(real, '')
elif momentum == '变化率的比率':
real = ta.ROCR(close, timeperiod=10)
axes[1].plot(real, '')
elif momentum == '变化率的比率100倍':
real = ta.ROCR100(close, timeperiod=10)
axes[1].plot(real, '')
elif momentum == '相对强弱指数':
real = ta.RSI(close, timeperiod=14)
axes[1].plot(real, '')
elif momentum == '随机相对强弱指标':
fastk, fastd = ta.STOCHRSI(close, timeperiod=14, fastk_period=5, fastd_period=3, fastd_matype=0)
axes[1].plot(fastk, '')
axes[1].plot(fastd, '')
elif momentum == '三重光滑EMA的日变化率':
real = ta.TRIX(close, timeperiod=30)
axes[1].plot(real, '')

plt.show()

# 周期指标
def cycle_process(event):
print(event.widget.get())
cycle = event.widget.get()

upperband, middleband, lowerband = ta.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)
fig, axes = plt.subplots(2, 1, sharex=True)
ax1, ax2 = axes[0], axes[1]
axes[0].plot(close, '', markersize=3)
axes[0].plot(upperband, '')
axes[0].plot(middleband, '')
axes[0].plot(lowerband, '')
axes[0].set_title(cycle, fontproperties="SimHei")

if cycle == '希尔伯特变换——主要的循环周期':
real = ta.HT_DCPERIOD(close)
axes[1].plot(real, '')
elif cycle == '希尔伯特变换,占主导地位的周期阶段':
real = ta.HT_DCPHASE(close)
axes[1].plot(real, '')
elif cycle == '希尔伯特变换——相量组件':
inphase, quadrature = ta.HT_PHASOR(close)
axes[1].plot(inphase, '')
axes[1].plot(quadrature, '')
elif cycle == '希尔伯特变换——正弦曲线':
sine, leadsine = ta.HT_SINE(close)
axes[1].plot(sine, '')
axes[1].plot(leadsine, '')
elif cycle == '希尔伯特变换——趋势和周期模式':
integer = ta.HT_TRENDMODE(close)
axes[1].plot(integer, '')

plt.show()


# 统计功能
def statistic_process(event):
print(event.widget.get())
statistic = event.widget.get()

upperband, middleband, lowerband = ta.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)
fig, axes = plt.subplots(2, 1, sharex=True)
ax1, ax2 = axes[0], axes[1]
axes[0].plot(close, '', markersize=3)
axes[0].plot(upperband, '')
axes[0].plot(middleband, '')
axes[0].plot(lowerband, '')
axes[0].set_title(statistic, fontproperties="SimHei")

if statistic == '线性回归':
real = ta.LINEARREG(close, timeperiod=14)
axes[1].plot(real, '')
elif statistic == '线性回归角度':
real = ta.LINEARREG_ANGLE(close, timeperiod=14)
axes[1].plot(real, '')
elif statistic == '线性回归截距':
real = ta.LINEARREG_INTERCEPT(close, timeperiod=14)
axes[1].plot(real, '')
elif statistic == '线性回归斜率':
real = ta.LINEARREG_SLOPE(close, timeperiod=14)
axes[1].plot(real, '')
elif statistic == '标准差':
real = ta.STDDEV(close, timeperiod=5, nbdev=1)
axes[1].plot(real, '')
elif statistic == '时间序列预测':
real = ta.TSF(close, timeperiod=14)
axes[1].plot(real, '')
elif statistic == '方差':
real = ta.VAR(close, timeperiod=5, nbdev=1)
axes[1].plot(real, '')

plt.show()


# 数学变换
def math_transform_process(event):
print(event.widget.get())
math_transform = event.widget.get()

upperband, middleband, lowerband = ta.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)
fig, axes = plt.subplots(2, 1, sharex=True)
ax1, ax2 = axes[0], axes[1]
axes[0].plot(close, '', markersize=3)
axes[0].plot(upperband, '')
axes[0].plot(middleband, '')
axes[0].plot(lowerband, '')
axes[0].set_title(math_transform, fontproperties="SimHei")


if math_transform == '反余弦':
real = ta.ACOS(close)
axes[1].plot(real, '')
elif math_transform == '反正弦':
real = ta.ASIN(close)
axes[1].plot(real, '')
elif math_transform == '反正切':
real = ta.ATAN(close)
axes[1].plot(real, '')
elif math_transform == '向上取整':
real = ta.CEIL(close)
axes[1].plot(real, '')
elif math_transform == '余弦':
real = ta.COS(close)
axes[1].plot(real, '')
elif math_transform == '双曲余弦':
real = ta.COSH(close)
axes[1].plot(real, '')
elif math_transform == '指数':
real = ta.EXP(close)
axes[1].plot(real, '')
elif math_transform == '向下取整':
real = ta.FLOOR(close)
axes[1].plot(real, '')
elif math_transform == '自然对数':
real = ta.LN(close)
axes[1].plot(real, '')
elif math_transform == '常用对数':
real = ta.LOG10(close)
axes[1].plot(real, '')
elif math_transform == '正弦':
real = ta.SIN(close)
axes[1].plot(real, '')
elif math_transform == '双曲正弦':
real = ta.SINH(close)
axes[1].plot(real, '')
elif math_transform == '平方根':
real = ta.SQRT(close)
axes[1].plot(real, '')
elif math_transform == '正切':
real = ta.TAN(close)
axes[1].plot(real, '')
elif math_transform == '双曲正切':
real = ta.TANH(close)
axes[1].plot(real, '')

plt.show()


# 数学操作
def math_operator_process(event):
print(event.widget.get())
math_operator = event.widget.get()

upperband, middleband, lowerband = ta.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)
fig, axes = plt.subplots(2, 1, sharex=True)
ax1, ax2 = axes[0], axes[1]
axes[0].plot(close, '', markersize=3)
axes[0].plot(upperband, '')
axes[0].plot(middleband, '')
axes[0].plot(lowerband, '')
axes[0].set_title(math_operator, fontproperties="SimHei")


if math_operator == '指定的期间的最大值':
real = ta.MAX(close, timeperiod=30)
axes[1].plot(real, '')
elif math_operator == '指定的期间的最大值的索引':
integer = ta.MAXINDEX(close, timeperiod=30)
axes[1].plot(integer, '')
elif math_operator == '指定的期间的最小值':
real = ta.MIN(close, timeperiod=30)
axes[1].plot(real, '')
elif math_operator == '指定的期间的最小值的索引':
integer = ta.MININDEX(close, timeperiod=30)
axes[1].plot(integer, '')
elif math_operator == '指定的期间的最小和最大值':
min, max = ta.MINMAX(close, timeperiod=30)
axes[1].plot(min, '')
axes[1].plot(max, '')
elif math_operator == '指定的期间的最小和最大值的索引':
minidx, maxidx = ta.MINMAXINDEX(close, timeperiod=30)
axes[1].plot(minidx, '')
axes[1].plot(maxidx, '')
elif math_operator == '合计':
real = ta.SUM(close, timeperiod=30)
axes[1].plot(real, '')

plt.show()


root = tk.Tk()

# 第一行:重叠指标
rowframe1 = tk.Frame(root)
rowframe1.pack(side=tk.TOP, ipadx=3, ipady=3)
tk.Label(rowframe1, text="重叠指标").pack(side=tk.LEFT)

overlap_indicator = tk.StringVar() # 重叠指标
combobox1 = ttk.Combobox(rowframe1, textvariable=overlap_indicator)
combobox1['values'] = ['布林线','双指数移动平均线','指数移动平均线 ','希尔伯特变换——瞬时趋势线',
'考夫曼自适应移动平均线','移动平均线','MESA自适应移动平均','变周期移动平均线',
'简单移动平均线','三指数移动平均线(T3)','三指数移动平均线','三角形加权法 ','加权移动平均数']
combobox1.current(0)
combobox1.pack(side=tk.LEFT)

combobox1.bind('<<ComboboxSelected>>', overlap_process)


# 第二行:动量指标
rowframe2 = tk.Frame(root)
rowframe2.pack(side=tk.TOP, ipadx=3, ipady=3)
tk.Label(rowframe2, text="动量指标").pack(side=tk.LEFT)

momentum_indicator = tk.StringVar() # 动量指标
combobox2 = ttk.Combobox(rowframe2, textvariable=momentum_indicator)
combobox2['values'] = ['绝对价格振荡器','钱德动量摆动指标','移动平均收敛/散度','带可控MA类型的MACD',
'移动平均收敛/散度 固定 12/26','动量','比例价格振荡器','变化率','变化率百分比',
'变化率的比率','变化率的比率100倍','相对强弱指数','随机相对强弱指标','三重光滑EMA的日变化率']

combobox2.current(0)
combobox2.pack(side=tk.LEFT)

combobox2.bind('<<ComboboxSelected>>', momentum_process)



# 第三行:周期指标
rowframe3 = tk.Frame(root)
rowframe3.pack(side=tk.TOP, ipadx=3, ipady=3)
tk.Label(rowframe3, text="周期指标").pack(side=tk.LEFT)

cycle_indicator = tk.StringVar() # 周期指标
combobox3 = ttk.Combobox(rowframe3, textvariable=cycle_indicator)
combobox3['values'] = ['希尔伯特变换——主要的循环周期','希尔伯特变换——主要的周期阶段','希尔伯特变换——相量组件',
'希尔伯特变换——正弦曲线','希尔伯特变换——趋势和周期模式']

combobox3.current(0)
combobox3.pack(side=tk.LEFT)

combobox3.bind('<<ComboboxSelected>>', cycle_process)


# 第四行:统计功能
rowframe4 = tk.Frame(root)
rowframe4.pack(side=tk.TOP, ipadx=3, ipady=3)
tk.Label(rowframe4, text="统计功能").pack(side=tk.LEFT)

statistic_indicator = tk.StringVar() # 统计功能
combobox4 = ttk.Combobox(rowframe4, textvariable=statistic_indicator)
combobox4['values'] = ['贝塔系数;投资风险与股市风险系数','皮尔逊相关系数','线性回归','线性回归角度',
'线性回归截距','线性回归斜率','标准差','时间序列预测','方差']

combobox4.current(0)
combobox4.pack(side=tk.LEFT)

combobox4.bind('<<ComboboxSelected>>', statistic_process)


# 第五行:数学变换
rowframe5 = tk.Frame(root)
rowframe5.pack(side=tk.TOP, ipadx=3, ipady=3)
tk.Label(rowframe5, text="数学变换").pack(side=tk.LEFT)

math_transform = tk.StringVar() # 数学变换
combobox5 = ttk.Combobox(rowframe5, textvariable=math_transform_process)
combobox5['values'] = ['反余弦','反正弦','反正切','向上取整','余弦','双曲余弦','指数','向下取整',
'自然对数','常用对数','正弦','双曲正弦','平方根','正切','双曲正切']

combobox5.current(0)
combobox5.pack(side=tk.LEFT)

combobox5.bind('<<ComboboxSelected>>', math_transform_process)


# 第六行:数学操作
rowframe6 = tk.Frame(root)
rowframe6.pack(side=tk.TOP, ipadx=3, ipady=3)
tk.Label(rowframe6, text="数学操作").pack(side=tk.LEFT)

math_operator = tk.StringVar() # 数学操作
combobox6 = ttk.Combobox(rowframe6, textvariable=math_operator_process)
combobox6['values'] = ['指定期间的最大值','指定期间的最大值的索引','指定期间的最小值','指定期间的最小值的索引',
'指定期间的最小和最大值','指定期间的最小和最大值的索引','合计']

combobox6.current(0)
combobox6.pack(side=tk.LEFT)

combobox6.bind('<<ComboboxSelected>>', math_operator_process)




root.mainloop() 查看全部
http://30daydo.com/article/196
 TA-Lib主要用来计算一些股市中常见的指标。
比如MACD,BOLL,均线等参数。
 
#-*-coding=utf-8-*-
import Tkinter as tk
from Tkinter import *
import ttk
import matplotlib.pyplot as plt

import numpy as np
import talib as ta

series = np.random.choice([1, -1], size=200)
close = np.cumsum(series).astype(float)

# 重叠指标
def overlap_process(event):
print(event.widget.get())
overlap = event.widget.get()

upperband, middleband, lowerband = ta.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)
fig, axes = plt.subplots(2, 1, sharex=True)
ax1, ax2 = axes[0], axes[1]
axes[0].plot(close, '', markersize=3)
axes[0].plot(upperband, '')
axes[0].plot(middleband, '')
axes[0].plot(lowerband, '')
axes[0].set_title(overlap, fontproperties="SimHei")

if overlap == '布林线':
pass
elif overlap == '双指数移动平均线':
real = ta.DEMA(close, timeperiod=30)
axes[1].plot(real, '')
elif overlap == '指数移动平均线 ':
real = ta.EMA(close, timeperiod=30)
axes[1].plot(real, '')
elif overlap == '希尔伯特变换——瞬时趋势线':
real = ta.HT_TRENDLINE(close)
axes[1].plot(real, '')
elif overlap == '考夫曼自适应移动平均线':
real = ta.KAMA(close, timeperiod=30)
axes[1].plot(real, '')
elif overlap == '移动平均线':
real = ta.MA(close, timeperiod=30, matype=0)
axes[1].plot(real, '')
elif overlap == 'MESA自适应移动平均':
mama, fama = ta.MAMA(close, fastlimit=0, slowlimit=0)
axes[1].plot(mama, '')
axes[1].plot(fama, '')
elif overlap == '变周期移动平均线':
real = ta.MAVP(close, periods, minperiod=2, maxperiod=30, matype=0)
axes[1].plot(real, '')
elif overlap == '简单移动平均线':
real = ta.SMA(close, timeperiod=30)
axes[1].plot(real, '')
elif overlap == '三指数移动平均线(T3)':
real = ta.T3(close, timeperiod=5, vfactor=0)
axes[1].plot(real, '')
elif overlap == '三指数移动平均线':
real = ta.TEMA(close, timeperiod=30)
axes[1].plot(real, '')
elif overlap == '三角形加权法 ':
real = ta.TRIMA(close, timeperiod=30)
axes[1].plot(real, '')
elif overlap == '加权移动平均数':
real = ta.WMA(close, timeperiod=30)
axes[1].plot(real, '')
plt.show()

# 动量指标
def momentum_process(event):
print(event.widget.get())
momentum = event.widget.get()

upperband, middleband, lowerband = ta.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)
fig, axes = plt.subplots(2, 1, sharex=True)
ax1, ax2 = axes[0], axes[1]
axes[0].plot(close, '', markersize=3)
axes[0].plot(upperband, '')
axes[0].plot(middleband, '')
axes[0].plot(lowerband, '')
axes[0].set_title(momentum, fontproperties="SimHei")

if momentum == '绝对价格振荡器':
real = ta.APO(close, fastperiod=12, slowperiod=26, matype=0)
axes[1].plot(real, '')
elif momentum == '钱德动量摆动指标':
real = ta.CMO(close, timeperiod=14)
axes[1].plot(real, '')
elif momentum == '移动平均收敛/散度':
macd, macdsignal, macdhist = ta.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9)
axes[1].plot(macd, '')
axes[1].plot(macdsignal, '')
axes[1].plot(macdhist, '')
elif momentum == '带可控MA类型的MACD':
macd, macdsignal, macdhist = ta.MACDEXT(close, fastperiod=12, fastmatype=0, slowperiod=26, slowmatype=0, signalperiod=9, signalmatype=0)
axes[1].plot(macd, '')
axes[1].plot(macdsignal, '')
axes[1].plot(macdhist, '')
elif momentum == '移动平均收敛/散度 固定 12/26':
macd, macdsignal, macdhist = ta.MACDFIX(close, signalperiod=9)
axes[1].plot(macd, '')
axes[1].plot(macdsignal, '')
axes[1].plot(macdhist, '')
elif momentum == '动量':
real = ta.MOM(close, timeperiod=10)
axes[1].plot(real, '')
elif momentum == '比例价格振荡器':
real = ta.PPO(close, fastperiod=12, slowperiod=26, matype=0)
axes[1].plot(real, '')
elif momentum == '变化率':
real = ta.ROC(close, timeperiod=10)
axes[1].plot(real, '')
elif momentum == '变化率百分比':
real = ta.ROCP(close, timeperiod=10)
axes[1].plot(real, '')
elif momentum == '变化率的比率':
real = ta.ROCR(close, timeperiod=10)
axes[1].plot(real, '')
elif momentum == '变化率的比率100倍':
real = ta.ROCR100(close, timeperiod=10)
axes[1].plot(real, '')
elif momentum == '相对强弱指数':
real = ta.RSI(close, timeperiod=14)
axes[1].plot(real, '')
elif momentum == '随机相对强弱指标':
fastk, fastd = ta.STOCHRSI(close, timeperiod=14, fastk_period=5, fastd_period=3, fastd_matype=0)
axes[1].plot(fastk, '')
axes[1].plot(fastd, '')
elif momentum == '三重光滑EMA的日变化率':
real = ta.TRIX(close, timeperiod=30)
axes[1].plot(real, '')

plt.show()

# 周期指标
def cycle_process(event):
print(event.widget.get())
cycle = event.widget.get()

upperband, middleband, lowerband = ta.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)
fig, axes = plt.subplots(2, 1, sharex=True)
ax1, ax2 = axes[0], axes[1]
axes[0].plot(close, '', markersize=3)
axes[0].plot(upperband, '')
axes[0].plot(middleband, '')
axes[0].plot(lowerband, '')
axes[0].set_title(cycle, fontproperties="SimHei")

if cycle == '希尔伯特变换——主要的循环周期':
real = ta.HT_DCPERIOD(close)
axes[1].plot(real, '')
elif cycle == '希尔伯特变换,占主导地位的周期阶段':
real = ta.HT_DCPHASE(close)
axes[1].plot(real, '')
elif cycle == '希尔伯特变换——相量组件':
inphase, quadrature = ta.HT_PHASOR(close)
axes[1].plot(inphase, '')
axes[1].plot(quadrature, '')
elif cycle == '希尔伯特变换——正弦曲线':
sine, leadsine = ta.HT_SINE(close)
axes[1].plot(sine, '')
axes[1].plot(leadsine, '')
elif cycle == '希尔伯特变换——趋势和周期模式':
integer = ta.HT_TRENDMODE(close)
axes[1].plot(integer, '')

plt.show()


# 统计功能
def statistic_process(event):
print(event.widget.get())
statistic = event.widget.get()

upperband, middleband, lowerband = ta.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)
fig, axes = plt.subplots(2, 1, sharex=True)
ax1, ax2 = axes[0], axes[1]
axes[0].plot(close, '', markersize=3)
axes[0].plot(upperband, '')
axes[0].plot(middleband, '')
axes[0].plot(lowerband, '')
axes[0].set_title(statistic, fontproperties="SimHei")

if statistic == '线性回归':
real = ta.LINEARREG(close, timeperiod=14)
axes[1].plot(real, '')
elif statistic == '线性回归角度':
real = ta.LINEARREG_ANGLE(close, timeperiod=14)
axes[1].plot(real, '')
elif statistic == '线性回归截距':
real = ta.LINEARREG_INTERCEPT(close, timeperiod=14)
axes[1].plot(real, '')
elif statistic == '线性回归斜率':
real = ta.LINEARREG_SLOPE(close, timeperiod=14)
axes[1].plot(real, '')
elif statistic == '标准差':
real = ta.STDDEV(close, timeperiod=5, nbdev=1)
axes[1].plot(real, '')
elif statistic == '时间序列预测':
real = ta.TSF(close, timeperiod=14)
axes[1].plot(real, '')
elif statistic == '方差':
real = ta.VAR(close, timeperiod=5, nbdev=1)
axes[1].plot(real, '')

plt.show()


# 数学变换
def math_transform_process(event):
print(event.widget.get())
math_transform = event.widget.get()

upperband, middleband, lowerband = ta.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)
fig, axes = plt.subplots(2, 1, sharex=True)
ax1, ax2 = axes[0], axes[1]
axes[0].plot(close, '', markersize=3)
axes[0].plot(upperband, '')
axes[0].plot(middleband, '')
axes[0].plot(lowerband, '')
axes[0].set_title(math_transform, fontproperties="SimHei")


if math_transform == '反余弦':
real = ta.ACOS(close)
axes[1].plot(real, '')
elif math_transform == '反正弦':
real = ta.ASIN(close)
axes[1].plot(real, '')
elif math_transform == '反正切':
real = ta.ATAN(close)
axes[1].plot(real, '')
elif math_transform == '向上取整':
real = ta.CEIL(close)
axes[1].plot(real, '')
elif math_transform == '余弦':
real = ta.COS(close)
axes[1].plot(real, '')
elif math_transform == '双曲余弦':
real = ta.COSH(close)
axes[1].plot(real, '')
elif math_transform == '指数':
real = ta.EXP(close)
axes[1].plot(real, '')
elif math_transform == '向下取整':
real = ta.FLOOR(close)
axes[1].plot(real, '')
elif math_transform == '自然对数':
real = ta.LN(close)
axes[1].plot(real, '')
elif math_transform == '常用对数':
real = ta.LOG10(close)
axes[1].plot(real, '')
elif math_transform == '正弦':
real = ta.SIN(close)
axes[1].plot(real, '')
elif math_transform == '双曲正弦':
real = ta.SINH(close)
axes[1].plot(real, '')
elif math_transform == '平方根':
real = ta.SQRT(close)
axes[1].plot(real, '')
elif math_transform == '正切':
real = ta.TAN(close)
axes[1].plot(real, '')
elif math_transform == '双曲正切':
real = ta.TANH(close)
axes[1].plot(real, '')

plt.show()


# 数学操作
def math_operator_process(event):
print(event.widget.get())
math_operator = event.widget.get()

upperband, middleband, lowerband = ta.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)
fig, axes = plt.subplots(2, 1, sharex=True)
ax1, ax2 = axes[0], axes[1]
axes[0].plot(close, '', markersize=3)
axes[0].plot(upperband, '')
axes[0].plot(middleband, '')
axes[0].plot(lowerband, '')
axes[0].set_title(math_operator, fontproperties="SimHei")


if math_operator == '指定的期间的最大值':
real = ta.MAX(close, timeperiod=30)
axes[1].plot(real, '')
elif math_operator == '指定的期间的最大值的索引':
integer = ta.MAXINDEX(close, timeperiod=30)
axes[1].plot(integer, '')
elif math_operator == '指定的期间的最小值':
real = ta.MIN(close, timeperiod=30)
axes[1].plot(real, '')
elif math_operator == '指定的期间的最小值的索引':
integer = ta.MININDEX(close, timeperiod=30)
axes[1].plot(integer, '')
elif math_operator == '指定的期间的最小和最大值':
min, max = ta.MINMAX(close, timeperiod=30)
axes[1].plot(min, '')
axes[1].plot(max, '')
elif math_operator == '指定的期间的最小和最大值的索引':
minidx, maxidx = ta.MINMAXINDEX(close, timeperiod=30)
axes[1].plot(minidx, '')
axes[1].plot(maxidx, '')
elif math_operator == '合计':
real = ta.SUM(close, timeperiod=30)
axes[1].plot(real, '')

plt.show()


root = tk.Tk()

# 第一行:重叠指标
rowframe1 = tk.Frame(root)
rowframe1.pack(side=tk.TOP, ipadx=3, ipady=3)
tk.Label(rowframe1, text="重叠指标").pack(side=tk.LEFT)

overlap_indicator = tk.StringVar() # 重叠指标
combobox1 = ttk.Combobox(rowframe1, textvariable=overlap_indicator)
combobox1['values'] = ['布林线','双指数移动平均线','指数移动平均线 ','希尔伯特变换——瞬时趋势线',
'考夫曼自适应移动平均线','移动平均线','MESA自适应移动平均','变周期移动平均线',
'简单移动平均线','三指数移动平均线(T3)','三指数移动平均线','三角形加权法 ','加权移动平均数']
combobox1.current(0)
combobox1.pack(side=tk.LEFT)

combobox1.bind('<<ComboboxSelected>>', overlap_process)


# 第二行:动量指标
rowframe2 = tk.Frame(root)
rowframe2.pack(side=tk.TOP, ipadx=3, ipady=3)
tk.Label(rowframe2, text="动量指标").pack(side=tk.LEFT)

momentum_indicator = tk.StringVar() # 动量指标
combobox2 = ttk.Combobox(rowframe2, textvariable=momentum_indicator)
combobox2['values'] = ['绝对价格振荡器','钱德动量摆动指标','移动平均收敛/散度','带可控MA类型的MACD',
'移动平均收敛/散度 固定 12/26','动量','比例价格振荡器','变化率','变化率百分比',
'变化率的比率','变化率的比率100倍','相对强弱指数','随机相对强弱指标','三重光滑EMA的日变化率']

combobox2.current(0)
combobox2.pack(side=tk.LEFT)

combobox2.bind('<<ComboboxSelected>>', momentum_process)



# 第三行:周期指标
rowframe3 = tk.Frame(root)
rowframe3.pack(side=tk.TOP, ipadx=3, ipady=3)
tk.Label(rowframe3, text="周期指标").pack(side=tk.LEFT)

cycle_indicator = tk.StringVar() # 周期指标
combobox3 = ttk.Combobox(rowframe3, textvariable=cycle_indicator)
combobox3['values'] = ['希尔伯特变换——主要的循环周期','希尔伯特变换——主要的周期阶段','希尔伯特变换——相量组件',
'希尔伯特变换——正弦曲线','希尔伯特变换——趋势和周期模式']

combobox3.current(0)
combobox3.pack(side=tk.LEFT)

combobox3.bind('<<ComboboxSelected>>', cycle_process)


# 第四行:统计功能
rowframe4 = tk.Frame(root)
rowframe4.pack(side=tk.TOP, ipadx=3, ipady=3)
tk.Label(rowframe4, text="统计功能").pack(side=tk.LEFT)

statistic_indicator = tk.StringVar() # 统计功能
combobox4 = ttk.Combobox(rowframe4, textvariable=statistic_indicator)
combobox4['values'] = ['贝塔系数;投资风险与股市风险系数','皮尔逊相关系数','线性回归','线性回归角度',
'线性回归截距','线性回归斜率','标准差','时间序列预测','方差']

combobox4.current(0)
combobox4.pack(side=tk.LEFT)

combobox4.bind('<<ComboboxSelected>>', statistic_process)


# 第五行:数学变换
rowframe5 = tk.Frame(root)
rowframe5.pack(side=tk.TOP, ipadx=3, ipady=3)
tk.Label(rowframe5, text="数学变换").pack(side=tk.LEFT)

math_transform = tk.StringVar() # 数学变换
combobox5 = ttk.Combobox(rowframe5, textvariable=math_transform_process)
combobox5['values'] = ['反余弦','反正弦','反正切','向上取整','余弦','双曲余弦','指数','向下取整',
'自然对数','常用对数','正弦','双曲正弦','平方根','正切','双曲正切']

combobox5.current(0)
combobox5.pack(side=tk.LEFT)

combobox5.bind('<<ComboboxSelected>>', math_transform_process)


# 第六行:数学操作
rowframe6 = tk.Frame(root)
rowframe6.pack(side=tk.TOP, ipadx=3, ipady=3)
tk.Label(rowframe6, text="数学操作").pack(side=tk.LEFT)

math_operator = tk.StringVar() # 数学操作
combobox6 = ttk.Combobox(rowframe6, textvariable=math_operator_process)
combobox6['values'] = ['指定期间的最大值','指定期间的最大值的索引','指定期间的最小值','指定期间的最小值的索引',
'指定期间的最小和最大值','指定期间的最小和最大值的索引','合计']

combobox6.current(0)
combobox6.pack(side=tk.LEFT)

combobox6.bind('<<ComboboxSelected>>', math_operator_process)




root.mainloop()

量化交易 获取获取上市公司年报

李魔佛 发表了文章 • 0 个评论 • 5766 次浏览 • 2017-05-22 11:37 • 来自相关话题

http://30daydo.com/article/192
 
 tushare有一个函数, ts.get_report_data(年份,季度), 可以获取每一年的季度的业绩。

如果想要获取上市公司的年报,只要吧季度参数改为4即可 

例如 要获取 中国银行的2016年的年报

df=ts.get_report_data(2016,4)

print df[df['code']=='601988']


输出的结果如下:
 
In [4]: print df[df['code']=='601988']
        code  name   eps  eps_yoy  bvps    roe  epcf  net_profits  \
1826  601988  中国银行  0.54    -3.57  4.46  12.58   NaN   16457800.0

      profits_yoy  distrib report_date
1826        -3.67  10派1.68       04-01
 
 
  查看全部
http://30daydo.com/article/192
 
 tushare有一个函数, ts.get_report_data(年份,季度), 可以获取每一年的季度的业绩。

如果想要获取上市公司的年报,只要吧季度参数改为4即可 

例如 要获取 中国银行的2016年的年报

df=ts.get_report_data(2016,4)

print df[df['code']=='601988']


输出的结果如下:
 
In [4]: print df[df['code']=='601988']
        code  name   eps  eps_yoy  bvps    roe  epcf  net_profits  \
1826  601988  中国银行  0.54    -3.57  4.46  12.58   NaN   16457800.0

      profits_yoy  distrib report_date
1826        -3.67  10派1.68       04-01
 
 
 

统计新股的连板天数,通过累计换手率预测开板时机

李魔佛 发表了文章 • 0 个评论 • 5168 次浏览 • 2017-05-11 17:12 • 来自相关话题

http://30daydo.com/article/182
 
对于一只新股,不少人会盯着它什么时候开板。 不过对于一般散户,如果换手率低于5%的一字涨停,也很难挤进去。 
那么今天我们来试一下计算新股的开板前的连板天数。# -*-coding=utf-8-*-
__author__ = 'Rocky'
'''
http://30daydo.com
Contact: weigesysu@qq.com
'''
#分析新股的开板时机
import tushare as ts
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
class New_Stock_Break():
def __init__(self):
#为了文件整齐,新建一个文件夹data用来专门存放数据
current = os.getcwd()
folder = os.path.join(current, 'data')
if os.path.exists(folder) == False:
os.mkdir(folder)
os.chdir(folder)
#调用tushare接口,获取A股信息
df0=ts.get_stock_basics()
#df0=pd.read_csv('bases.csv',dtype={'code':np.str})
self.bases=df0.sort_values('timeToMarket',ascending=False)

#获取样本, 获取最近一个年的新股情况

self.cxg=self.bases[(self.bases['timeToMarket']>20160101) & (self.bases['timeToMarket']<20170101)]
self.codes= self.cxg['code'].values

def calc_open_by_percent(self,code):
cont=100000000
#total_vol=self.bases[self.bases['code']==code]['totals'].values[0]
acutal_vol=self.bases[self.bases['code']==code]['outstanding'].values[0]
all_vol= acutal_vol*cont
df1=ts.get_k_data(code)
i=1
while 1:
s=df1.ix[1]
if s['high']!=s['low']:
#date=s['date']
break
i=i+1

j=i-1
date_end=df1.ix[j]['date']
date_start=df1.ix[0]['date']
df3=df1[(df1['date']>=date_start) & (df1['date']<=date_end)]
v_total_break=df3['volume'].sum()
l=len(df3)
print l
print v_total_break
rate=v_total_break*100*100.00/all_vol #手和股 注意
print round(rate,6)
return rate,l


def getData(self):
result=
max_line=
k=
for i in self.codes:
print i
name=self.bases[self.bases['code']==i]['name'].values[0]
rate,l=self.calc_open_by_percent(i)
if rate is not None:
result.append(rate)
max_line.append([name,l,rate])
k.append(l)
#写入文件
f=open('2016-2017-cixin.csv','w')
for x in max_line:
#f.write(';'.join(x))
f.write(x[0])
f.write('-')
f.write(str(x[1]))
f.write('-')
f.write(str(x[2]))
f.write('\n')

f.close()

def main():
obj=New_Stock_Break()
obj.testcase2()

main() 
运行后得到的数据如下:





 
你可以修改部分参数,可以获取每一年,或者每一个月的新股情况。
 
从上面的数据可以获取得到,最多的连班是海天精工的29板, 海天精工-29-12.8248076923 
累计的换手率达到了12.8。
 
当然上面的是在2016年IPO速度还没那么快的时候,2017年平均不到10个板就开了。 
 
附上抓取的数据文件
 
 链接: https://pan.baidu.com/s/1c1LpOZ2 密码: r3yk 查看全部
http://30daydo.com/article/182
 
对于一只新股,不少人会盯着它什么时候开板。 不过对于一般散户,如果换手率低于5%的一字涨停,也很难挤进去。 
那么今天我们来试一下计算新股的开板前的连板天数。
# -*-coding=utf-8-*-
__author__ = 'Rocky'
'''
http://30daydo.com
Contact: weigesysu@qq.com
'''
#分析新股的开板时机
import tushare as ts
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
class New_Stock_Break():
def __init__(self):
#为了文件整齐,新建一个文件夹data用来专门存放数据
current = os.getcwd()
folder = os.path.join(current, 'data')
if os.path.exists(folder) == False:
os.mkdir(folder)
os.chdir(folder)
#调用tushare接口,获取A股信息
df0=ts.get_stock_basics()
#df0=pd.read_csv('bases.csv',dtype={'code':np.str})
self.bases=df0.sort_values('timeToMarket',ascending=False)

#获取样本, 获取最近一个年的新股情况

self.cxg=self.bases[(self.bases['timeToMarket']>20160101) & (self.bases['timeToMarket']<20170101)]
self.codes= self.cxg['code'].values

def calc_open_by_percent(self,code):
cont=100000000
#total_vol=self.bases[self.bases['code']==code]['totals'].values[0]
acutal_vol=self.bases[self.bases['code']==code]['outstanding'].values[0]
all_vol= acutal_vol*cont
df1=ts.get_k_data(code)
i=1
while 1:
s=df1.ix[1]
if s['high']!=s['low']:
#date=s['date']
break
i=i+1

j=i-1
date_end=df1.ix[j]['date']
date_start=df1.ix[0]['date']
df3=df1[(df1['date']>=date_start) & (df1['date']<=date_end)]
v_total_break=df3['volume'].sum()
l=len(df3)
print l
print v_total_break
rate=v_total_break*100*100.00/all_vol #手和股 注意
print round(rate,6)
return rate,l


def getData(self):
result=
max_line=
k=
for i in self.codes:
print i
name=self.bases[self.bases['code']==i]['name'].values[0]
rate,l=self.calc_open_by_percent(i)
if rate is not None:
result.append(rate)
max_line.append([name,l,rate])
k.append(l)
#写入文件
f=open('2016-2017-cixin.csv','w')
for x in max_line:
#f.write(';'.join(x))
f.write(x[0])
f.write('-')
f.write(str(x[1]))
f.write('-')
f.write(str(x[2]))
f.write('\n')

f.close()

def main():
obj=New_Stock_Break()
obj.testcase2()

main()
 
运行后得到的数据如下:

开板.PNG

 

你可以修改部分参数,可以获取每一年,或者每一个月的新股情况。
 
从上面的数据可以获取得到,最多的连班是海天精工的29板, 海天精工-29-12.8248076923 
累计的换手率达到了12.8。
 
当然上面的是在2016年IPO速度还没那么快的时候,2017年平均不到10个板就开了。 
 
附上抓取的数据文件
 
 链接: https://pan.baidu.com/s/1c1LpOZ2 密码: r3yk

python 计算当天指定某个时段的成交量

李魔佛 发表了文章 • 0 个评论 • 6910 次浏览 • 2017-05-08 23:32 • 来自相关话题

计算当天指定某个时段的成交量
 
为什么需要这个功能? 因为平时复盘的时候,会切换当天的分时图,一般喜欢切换成5分钟图,这样子就对每个时刻的成交量有比较直观的认识。比如今天(2017-05-08)的无锡银行。
 






很无耻是吧? 我就像看看尾盘的20分钟内,主力动用了多少资金把股价从水下直接拉到涨停。 用程序处理,比用手工计算,要节省多时间了(前阵子的确是每笔粗略的相加)。
 
只要在main()中修改股票代码和你要获取成交量的时间,就可以获取你想要的数据。 还有一个数据就是该成交量占当天成交量的比例。# -*-coding=utf-8-*-
__author__ = 'Rocky'
#计算某个股票的某个时间段的成交量
import tushare as ts
import pandas as pd
import datetime
pd.set_option('display.max_rows',None)
class amount_calculation():
def __init__(self,code):
self.df=ts.get_today_ticks(code)

#转换str为时间格式,便于下面用来比较时间的大小
self.df['time']=self.df['time'].map(lambda x:datetime.datetime.strptime(str(x),'%H:%M:%S'))
print '\n'
self.total= self.df['volume'].sum()

def calc(self,start,end):
s0=datetime.datetime.strptime(start,'%H:%M:%S')
e0=datetime.datetime.strptime(end,'%H:%M:%S')
new_df=self.df[(self.df['time']>=s0) & (self.df['time']<e0) ]
part=new_df['volume'].sum()
print part
rate=round(part*1.00/self.total*100,2)
print rate
return rate




def main():
obj=amount_calculation('600908')
#s1=obj.calc('09:24:00','10:30:00')
#s2=obj.calc('10:30:00','11:30:00')
#s3=obj.calc('13:00:00','14:00:00')
s4=obj.calc('14:35:00','15:05:00')
#print s1+s2+s3+s4

main()
 
运行上面代码,得到
 
114046
34.16
成交量为11.4万手,大概占当天成交量的34.16%, 半小时的时间。(1/8的时间,涨了1/3的成交量)
算出这个有什么用呢?
 
对于庄股,可以便于你计算出主力当天吸了多少货,或者出了多少货。 数据不会完全精确,但是能够知道交易的量级。 像上面的例子,大概就10w-12w手的样子。
 
更多文章
30天学会量化交易模型 Day01 查看全部
计算当天指定某个时段的成交量
 
为什么需要这个功能? 因为平时复盘的时候,会切换当天的分时图,一般喜欢切换成5分钟图,这样子就对每个时刻的成交量有比较直观的认识。比如今天(2017-05-08)的无锡银行。
 

无锡银行.PNG


很无耻是吧? 我就像看看尾盘的20分钟内,主力动用了多少资金把股价从水下直接拉到涨停。 用程序处理,比用手工计算,要节省多时间了(前阵子的确是每笔粗略的相加)。
 
只要在main()中修改股票代码和你要获取成交量的时间,就可以获取你想要的数据。 还有一个数据就是该成交量占当天成交量的比例。
# -*-coding=utf-8-*-
__author__ = 'Rocky'
#计算某个股票的某个时间段的成交量
import tushare as ts
import pandas as pd
import datetime
pd.set_option('display.max_rows',None)
class amount_calculation():
def __init__(self,code):
self.df=ts.get_today_ticks(code)

#转换str为时间格式,便于下面用来比较时间的大小
self.df['time']=self.df['time'].map(lambda x:datetime.datetime.strptime(str(x),'%H:%M:%S'))
print '\n'
self.total= self.df['volume'].sum()

def calc(self,start,end):
s0=datetime.datetime.strptime(start,'%H:%M:%S')
e0=datetime.datetime.strptime(end,'%H:%M:%S')
new_df=self.df[(self.df['time']>=s0) & (self.df['time']<e0) ]
part=new_df['volume'].sum()
print part
rate=round(part*1.00/self.total*100,2)
print rate
return rate




def main():
obj=amount_calculation('600908')
#s1=obj.calc('09:24:00','10:30:00')
#s2=obj.calc('10:30:00','11:30:00')
#s3=obj.calc('13:00:00','14:00:00')
s4=obj.calc('14:35:00','15:05:00')
#print s1+s2+s3+s4

main()

 
运行上面代码,得到
 
114046
34.16
成交量为11.4万手,大概占当天成交量的34.16%, 半小时的时间。(1/8的时间,涨了1/3的成交量)
算出这个有什么用呢?
 
对于庄股,可以便于你计算出主力当天吸了多少货,或者出了多少货。 数据不会完全精确,但是能够知道交易的量级。 像上面的例子,大概就10w-12w手的样子。
 
更多文章
30天学会量化交易模型 Day01

ts.get_stock_basics() to_excel("base.xls") 保存dataframe 编码错误

李魔佛 发表了文章 • 0 个评论 • 4609 次浏览 • 2017-04-21 18:36 • 来自相关话题

 
基本代码片:
base=ts.get_stock_basics()
base.to_csv('2.xls')
 出现的错误:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 1: ordinal not in range(128) 
然后替换几种编码方式:
base.to_excel('base.xls',encoding='GBK')
base.to_excel('111.xls',encoding='utf8')
base.to_excel('111.xls‘)
不过问题还在。
 
而保存为csv文件却没有这个编码问题:
 
base.to_csv('base.csv)
 
 
于是采取了迂回战术, 先把数据保存为csv, 然后读取这个文件,然后 再保存为exel文件。
 
居然给我弄成功了!!
 
  查看全部
 
基本代码片:
    base=ts.get_stock_basics()
base.to_csv('2.xls')

 出现的错误:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 1: ordinal not in range(128) 
然后替换几种编码方式:
    base.to_excel('base.xls',encoding='GBK')
base.to_excel('111.xls',encoding='utf8')
base.to_excel('111.xls‘)

不过问题还在。
 
而保存为csv文件却没有这个编码问题:
 
base.to_csv('base.csv)
 
 
于是采取了迂回战术, 先把数据保存为csv, 然后读取这个文件,然后 再保存为exel文件。
 
居然给我弄成功了!!
 
 

JoinQuant 遇到的问题总结 --定期更新

李魔佛 发表了文章 • 0 个评论 • 3234 次浏览 • 2017-04-20 23:51 • 来自相关话题

1. 一些涨停一字板的个股或者新股,你是无法买入的。 经过测试,会发现没有买入任何的个股。
1. 一些涨停一字板的个股或者新股,你是无法买入的。 经过测试,会发现没有买入任何的个股。

pandas dataframe 读取csv文件 数据类型转化 字符变成了数字

李魔佛 发表了文章 • 0 个评论 • 40203 次浏览 • 2017-04-17 22:43 • 来自相关话题

因为csv中包含了大量的股票代码,如果是002开头的股票,比如002111, 使用pd.read_csv('text.csv') 则会让所有的002xxx,变成了2xxx,前面2个0不见了,当然你可以收工操作,填充那2个0。 不过对于pandas大法,何须这么麻烦?
 
直接在参数一栏设置一下即可:
df=pd.read_csv('text.csv', dtype={'code':str}
 
这样,把你要转换的列的名字设定好, “code”列中的数据读取为str
 
这样,读取到的数据就是按照我们的要求的了。 查看全部
因为csv中包含了大量的股票代码,如果是002开头的股票,比如002111, 使用pd.read_csv('text.csv') 则会让所有的002xxx,变成了2xxx,前面2个0不见了,当然你可以收工操作,填充那2个0。 不过对于pandas大法,何须这么麻烦?
 
直接在参数一栏设置一下即可:
df=pd.read_csv('text.csv', dtype={'code':str}
 
这样,把你要转换的列的名字设定好, “code”列中的数据读取为str
 
这样,读取到的数据就是按照我们的要求的了。