Skip to content

python递归函数

ChannelCMT edited this page Jun 3, 2019 · 1 revision

Python 递归函数

在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数。

可视化过程链接: http://www.pythontutor.com/visualize.html#mode=edit

def fact(n):
    if n==1:
        return 1
    return n * fact(n - 1)

fact(1) = $1$

fact(2) = $1*2 = 2$

fact(3) = $3*2 = 6$

fact(4) = $432 = 4*6 = 24$

fact(5) = $5432 = 524 = 120$

print(fact(5))
120

EMA计算

$EMA_t=α*Price_t + ( 1 - α ) * EMA_{t-1}$

$α为平滑指数,一般取作2/(n+1)$

  1. 自定义方法
  2. Pandas递归函数
  3. talib的EMA

1. 自定义方法

import pandas as pd

a = 2/7
Prices = list(range(10)) #prices
def ema ( N , Price) :
    if N < 1:
        return Price[0]
    return (1-a)*ema(N-1,Price) + a*Price[N]

print (pd.Series([ema(i,Prices) for i in range(10)]))
0    0.000000
1    0.285714
2    0.775510
3    1.411079
4    2.150771
5    2.964836
6    3.832026
7    4.737161
8    5.669401
9    6.621001
dtype: float64

2. Pandas递归函数

recursion_df = pd.DataFrame({'test': Prices})
recursion_result = recursion_df.ewm(alpha=2/7, adjust=False).mean()
print(recursion_result)
       test
0  0.000000
1  0.285714
2  0.775510
3  1.411079
4  2.150771
5  2.964836
6  3.832026
7  4.737161
8  5.669401
9  6.621001

3. talib的EMA

import talib as ta
import numpy as np

EMA = pd.Series(ta.EMA(np.array(Prices, dtype=np.float64),6))
print(EMA)
0    NaN
1    NaN
2    NaN
3    NaN
4    NaN
5    2.5
6    3.5
7    4.5
8    5.5
9    6.5
dtype: float64
Clone this wiki locally