资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

pythonema函数 python ema

使用python实现ema(指数移动平均的计算)

a = 2/13

创新互联服务项目包括蒸湘网站建设、蒸湘网站制作、蒸湘网页制作以及蒸湘网络营销策划等。多年来,我们专注于互联网行业,利用自身积累的技术优势、行业经验、深度合作伙伴关系等,向广大中小型企业、政府机构等提供互联网行业的解决方案,蒸湘网站推广取得了明显的社会效益与经济效益。目前,我们服务的客户以成都为中心已经辐射到蒸湘省份的部分城市,未来相信会继续扩大服务区域并继续获得客户的支持与信任!

Prices = [0.0] #prices of everyday

EMAs = [0.0] # ems of everyday

def ema ( N , Price) :

Prices.append(Price)

if N=1:

EMAs.append(Price)

else :

EMAs.append((1-a)*EMAs[N-1] + a*Price)

ema(1,1)

ema(2,3)

print (EMAs[1])

print (EMAs[2])

average在python中的用法

函数函数是代码的一种组织形式

函数应该能完成一项特定的工作,而且一般一个函数只完成一项工作

有些语言,分函数和过程两个概念,通俗解释是,有返回结果的是函数,无返回结果的叫过程,python不加以区分

函数的使用函数使用需要先定义

使用函数,俗称调用# 定义一个函数

# 只是定义的话不会执行

# 1. def关键字,后跟一个空格

# 2. 函数名,自己定义,起名需要遵循便令命名规则,约定俗成,大驼峰命名只给类用

# 3. 后面括号和冒号不能省,括号内可以有参数

# 4. 函数内所有代码缩进

def func():

print("我是一个函数")

print("爱生活")

print("函数结束了")函数结束了# 函数的调用

# 直接写出函数名字,后面小括号不能省略,括号内内容根据情况

func()我是一个函数

爱生活# 函数定义

def func():

print('A')

print('B')func()A

B

函数的参数和返回值参数:负责给函数传递一些必要的数据或者信息形参(形式参数):在函数定义的时候用到的参数,没有具体值,只是一个占位符号

实参(实际参数):在调用函数的时候输入的值

返回值:调用函数的时候的一个执行结果使用return返回结果

如果没有值需要返回,我们推荐使用return None表示函数结束

函数一旦执行return,则函数立即结束

如果函数没有return关键字,则函数默认返回None# 形参和实参的案例

# 参数person只是一个符号

# 调用的时候用另一个

def hello(person):

print("{},你好吗?".format(person))

return None

p = "小明"

# 调用函数,需要把p作为实参传入

hello(p)小明,你好吗?p = "小五"

hello(p)小五,你好吗?pp = hello("小柒")

print(pp)小柒,你好吗?

None# return案例

def hello(person):

print("{0},你好吗?".format(person))

return "提前结束!"

print(1)

p = "小明"

rst = hello(p)

print(rst)小明,你好吗?

提前结束!# help负责随时为你提供帮助

help(None) # 等价于help(peint())Help on built-in function print in module builtins:

print(...)

print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.

Optional keyword arguments:

file: a file-like object (stream); defaults to the current sys.stdout.

sep: string inserted between values, default a space.

end: string appended after the last value, default a newline.

flush: whether to forcibly flush the stream.# 九九乘法表

# version 1.0

for o in range(1, 10): # 控制外循环 从 1 到 9

for i in range(1, o + 1): # 内循环,每次从第一个数字开始,打印到跟行数相同的数量

print(o * i, end=" ")

print()1

2 4

3 6 9

4 8 12 16

5 10 15 20 25

6 12 18 24 30 36

7 14 21 28 35 42 49

8 16 24 32 40 48 56 64

9 18 27 36 45 54 63 72 81help(print)Help on built-in function print in module builtins:

print(...)

print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.

Optional keyword arguments:

file: a file-like object (stream); defaults to the current sys.stdout.

sep: string inserted between values, default a space.

end: string appended after the last value, default a newline.

flush: whether to forcibly flush the stream.# 尝试用函数来打印九九乘法表

def jiujiu():

for o in range(1, 10): # 控制外循环 从 1 到 9

for i in range(1, o + 1): # 内循环,每次从第一个数字开始,打印到跟行数相同的数量

print(o * i, end=" ")

print()

return None

jiujiu()

jiujiu()1

2 4

3 6 9

4 8 12 16

5 10 15 20 25

6 12 18 24 30 36

7 14 21 28 35 42 49

8 16 24 32 40 48 56 64

9 18 27 36 45 54 63 72 81

1

2 4

3 6 9

4 8 12 16

5 10 15 20 25

6 12 18 24 30 36

7 14 21 28 35 42 49

8 16 24 32 40 48 56 64

9 18 27 36 45 54 63 72 81# 改造上面函数

def printLine(line_num):

'''

line_num;代表行号

打印一行九九乘法表

'''

for i in range(1, line_num + 1):

print(line_num * i, end=" ")

print()

def jiujiu():

for o in range(1, 10): # 控制外循环 从 1 到 9

printLine(o)

return None

jiujiu()1

2 4

3 6 9

4 8 12 16

5 10 15 20 25

6 12 18 24 30 36

7 14 21 28 35 42 49

8 16 24 32 40 48 56 64

9 18 27 36 45 54 63 72 81

参数详解python参考资料:headfirst python - 零基础入门学习python(小甲鱼)、流畅的python - 习题

参数分类普通参数/位置参数

默认参数

关键字参数

收集参数

普通参数c参见上例

定义的时候直接定义变量名

调用的时候直接把变量或者值放入指定位置def 函数名(参数1,参数2,.....):

函数体

# 调用

函数名(value1,value2,......)

# 调用的时候,具体值参考的是位置,按位置赋值

默认参数形参带有默认值

调用的时候,如果没有对相应形参赋值,则使用默认值

python数据分析与应用第三章代码3-5的数据哪来的

savetxt

import numpy as np

i2 = np.eye(2)

np.savetxt("eye.txt", i2)

3.4 读入CSV文件

# AAPL,28-01-2011, ,344.17,344.4,333.53,336.1,21144800

c,v=np.loadtxt('data.csv', delimiter=',', usecols=(6,7), unpack=True) #index从0开始

3.6.1 算术平均值

np.mean(c) = np.average(c)

3.6.2 加权平均值

t = np.arange(len(c))

np.average(c, weights=t)

3.8 极值

np.min(c)

np.max(c)

np.ptp(c) 最大值与最小值的差值

3.10 统计分析

np.median(c) 中位数

np.msort(c) 升序排序

np.var(c) 方差

3.12 分析股票收益率

np.diff(c) 可以返回一个由相邻数组元素的差

值构成的数组

returns = np.diff( arr ) / arr[ : -1] #diff返回的数组比收盘价数组少一个元素

np.std(c) 标准差

对数收益率

logreturns = np.diff( np.log(c) ) #应检查输入数组以确保其不含有零和负数

where 可以根据指定的条件返回所有满足条件的数

组元素的索引值。

posretindices = np.where(returns 0)

np.sqrt(1./252.) 平方根,浮点数

3.14 分析日期数据

# AAPL,28-01-2011, ,344.17,344.4,333.53,336.1,21144800

dates, close=np.loadtxt('data.csv', delimiter=',', usecols=(1,6), converters={1:datestr2num}, unpack=True)

print "Dates =", dates

def datestr2num(s):

return datetime.datetime.strptime(s, "%d-%m-%Y").date().weekday()

# 星期一 0

# 星期二 1

# 星期三 2

# 星期四 3

# 星期五 4

# 星期六 5

# 星期日 6

#output

Dates = [ 4. 0. 1. 2. 3. 4. 0. 1. 2. 3. 4. 0. 1. 2. 3. 4. 1. 2. 4. 0. 1. 2. 3. 4. 0.

1. 2. 3. 4.]

averages = np.zeros(5)

for i in range(5):

indices = np.where(dates == i)

prices = np.take(close, indices) #按数组的元素运算,产生一个数组作为输出。

a = [4, 3, 5, 7, 6, 8]

indices = [0, 1, 4]

np.take(a, indices)

array([4, 3, 6])

np.argmax(c) #返回的是数组中最大元素的索引值

np.argmin(c)

3.16 汇总数据

# AAPL,28-01-2011, ,344.17,344.4,333.53,336.1,21144800

#得到第一个星期一和最后一个星期五

first_monday = np.ravel(np.where(dates == 0))[0]

last_friday = np.ravel(np.where(dates == 4))[-1]

#创建一个数组,用于存储三周内每一天的索引值

weeks_indices = np.arange(first_monday, last_friday + 1)

#按照每个子数组5个元素,用split函数切分数组

weeks_indices = np.split(weeks_indices, 5)

#output

[array([1, 2, 3, 4, 5]), array([ 6, 7, 8, 9, 10]), array([11,12, 13, 14, 15])]

weeksummary = np.apply_along_axis(summarize, 1, weeks_indices,open, high, low, close)

def summarize(a, o, h, l, c): #open, high, low, close

monday_open = o[a[0]]

week_high = np.max( np.take(h, a) )

week_low = np.min( np.take(l, a) )

friday_close = c[a[-1]]

return("APPL", monday_open, week_high, week_low, friday_close)

np.savetxt("weeksummary.csv", weeksummary, delimiter=",", fmt="%s") #指定了文件名、需要保存的数组名、分隔符(在这个例子中为英文标点逗号)以及存储浮点数的格式。

0818b9ca8b590ca3270a3433284dd417.png

格式字符串以一个百分号开始。接下来是一个可选的标志字符:-表示结果左对齐,0表示左端补0,+表示输出符号(正号+或负号-)。第三部分为可选的输出宽度参数,表示输出的最小位数。第四部分是精度格式符,以”.”开头,后面跟一个表示精度的整数。最后是一个类型指定字符,在例子中指定为字符串类型。

numpy.apply_along_axis(func1d, axis, arr, *args, **kwargs)

def my_func(a):

... """Average first and last element of a 1-D array"""

... return (a[0] + a[-1]) * 0.5

b = np.array([[1,2,3], [4,5,6], [7,8,9]])

np.apply_along_axis(my_func, 0, b) #沿着X轴运动,取列切片

array([ 4., 5., 6.])

np.apply_along_axis(my_func, 1, b) #沿着y轴运动,取行切片

array([ 2., 5., 8.])

b = np.array([[8,1,7], [4,3,9], [5,2,6]])

np.apply_along_axis(sorted, 1, b)

array([[1, 7, 8],

[3, 4, 9],

[2, 5, 6]])

3.20 计算简单移动平均线

(1) 使用ones函数创建一个长度为N的元素均初始化为1的数组,然后对整个数组除以N,即可得到权重。如下所示:

N = int(sys.argv[1])

weights = np.ones(N) / N

print "Weights", weights

在N = 5时,输出结果如下:

Weights [ 0.2 0.2 0.2 0.2 0.2] #权重相等

(2) 使用这些权重值,调用convolve函数:

c = np.loadtxt('data.csv', delimiter=',', usecols=(6,),unpack=True)

sma = np.convolve(weights, c)[N-1:-N+1] #卷积是分析数学中一种重要的运算,定义为一个函数与经过翻转和平移的另一个函数的乘积的积分。

t = np.arange(N - 1, len(c)) #作图

plot(t, c[N-1:], lw=1.0)

plot(t, sma, lw=2.0)

show()

3.22 计算指数移动平均线

指数移动平均线(exponential moving average)。指数移动平均线使用的权重是指数衰减的。对历史上的数据点赋予的权重以指数速度减小,但永远不会到达0。

x = np.arange(5)

print "Exp", np.exp(x)

#output

Exp [ 1. 2.71828183 7.3890561 20.08553692 54.59815003]

Linspace 返回一个元素值在指定的范围内均匀分布的数组。

print "Linspace", np.linspace(-1, 0, 5) #起始值、终止值、可选的元素个数

#output

Linspace [-1. -0.75 -0.5 -0.25 0. ]

(1)权重计算

N = int(sys.argv[1])

weights = np.exp(np.linspace(-1. , 0. , N))

(2)权重归一化处理

weights /= weights.sum()

print "Weights", weights

#output

Weights [ 0.11405072 0.14644403 0.18803785 0.24144538 0.31002201]

(3)计算及作图

c = np.loadtxt('data.csv', delimiter=',', usecols=(6,),unpack=True)

ema = np.convolve(weights, c)[N-1:-N+1]

t = np.arange(N - 1, len(c))

plot(t, c[N-1:], lw=1.0)

plot(t, ema, lw=2.0)

show()

3.26 用线性模型预测价格

(x, residuals, rank, s) = np.linalg.lstsq(A, b) #系数向量x、一个残差数组、A的秩以及A的奇异值

print x, residuals, rank, s

#计算下一个预测值

print np.dot(b, x)

3.28 绘制趋势线

x = np.arange(6)

x = x.reshape((2, 3))

x

array([[0, 1, 2], [3, 4, 5]])

np.ones_like(x) #用1填充数组

array([[1, 1, 1], [1, 1, 1]])

类似函数

zeros_like

empty_like

zeros

ones

empty

3.30 数组的修剪和压缩

a = np.arange(5)

print "a =", a

print "Clipped", a.clip(1, 2) #将所有比给定最大值还大的元素全部设为给定的最大值,而所有比给定最小值还小的元素全部设为给定的最小值

#output

a = [0 1 2 3 4]

Clipped [1 1 2 2 2]

a = np.arange(4)

print a

print "Compressed", a.compress(a 2) #返回一个根据给定条件筛选后的数组

#output

[0 1 2 3]

Compressed [3]

b = np.arange(1, 9)

print "b =", b

print "Factorial", b.prod() #输出数组元素阶乘结果

#output

b = [1 2 3 4 5 6 7 8]

Factorial 40320

print "Factorials", b.cumprod()

#output


当前名称:pythonema函数 python ema
URL标题:http://cdkjz.cn/article/dosgpji.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220