首页 > 编程语言 >Python 量化投资(一):滑动均值、布林带、MACD、RSI、KDJ、OBV

Python 量化投资(一):滑动均值、布林带、MACD、RSI、KDJ、OBV

时间:2023-07-12 15:57:38浏览次数:45  
标签:return RSI KDJ Python win rolling close np alpha

滑动均值和标准差

为了更好利用向量化来加速,滑动窗口使用np.lib.stride_tricks.sliding_window_view(x, win)提取,它会返回所有x[i]开头并且长度为win的数组的数组。

def rolling(x, win):
    r = np.lib.stride_tricks.sliding_window_view(x, win)
    pad = np.zeros([len(x) - len(r), win]) * np.nan
    return np.vstack([pad, r])
	
def rolling_mean(x, win):
    return rolling(x, win).mean(-1)

def rolling_std(x, win):
    return rolling(x, win).std(-1)

布林带

def bollinger(close, win=10, nstd=2):
    means = rolling_mean(close, win)
	stds = rolling_std(close, win)
	upper = means + nstd * stds
	lower = means - nstd * stds
	return upper, means, lower

指数滑动均值

这是原始实现:

# 计算指数平滑 
# y[i] = alpha * x[i] + (1 - alpha) * y[i - 1]
def exp_smooth_naive(x, alpha):
    y = x.copy()
    for i in range(1, len(y)):
		y[i] = y[i] * alpha + y[i - 1] * (1 - alpha)
	return y

原始公式是递归的,需要改成通项才能向量化,这是推导过程:

y[0] = x[0] = init

y[t] = alpha * x[t]  + (1-alpha) * y[t-1]
     = alpha * x[t]  + (1-alpha) * alpha * x[t-1] + (1-alpha) ** 2 * y[t-2]
	 = alpha * x[t]  + (1-alpha) * alpha * x[t-1] + ... + (1-alpha)** t * init
	 = alpha * x[t]  + (1-alpha) * alpha * x[t-1] + ... + alpha * (1-alpha)** t * init + (1 - alpha) ** (t + 1) * init
	 = Σ(alpha * (1 - alpha) ** i * x[t-i]; i: 0 -> t) + (1 - alpha) ** (t + 1) * init

corr[i] = alpha * (1-alpha) ** i
supl[t] = (1 - alpha) ** (t + 1) * init 

y[t] = Σ(corr[i] * x(t-i); i: 0 -> t) + supl[t]
y = conv(corr, x) + supl

这就完成了向量化,因为 NumPy 或者 PyTorch 都针对卷积做了特殊优化。

def exp_smooth_vec(x, alpha):
	init, n = x[0], len(x)
	corr =  alpha * (1 - alpha) ** np.arange(0, n)
	supl = (1 - alpha) ** (np.arange(0, n) + 1) * init
	y = np.convolve(corr, x, 'full')[:n] + supl
	return y

exp_smooth = exp_smooth_vec

def rolling_ema(x, win):
    x = np.asarray(x)
    alpha = 2 / (win + 1.0)
	return exp_smooth(x, alpha)

MACD

def macd(close, fast_win=12, slow_win=26, sig_win=9):
	fast = rolling_ema(close, fast_win)
	slow = rolling_ema(close, slow_win)
	dif = fast - slow
	dea = rolling_ema(dif, sig_win)
	macd_ = dif - dea * 2
	return macd_, dif, dea

RSI

def rsi(close, win=3):
	change = np.diff(close)
	up = np.where(change > 0, change, 0)
	down = np.where(change < 0, change, 0)
	sum_up = rolling(up, win).sum(-1)
	sum_down = rolling(down, win).sum(-1)
	eps = 1e-12
	rs = sum_up / (sum_down + eps)
	rsi_ = 100 - 100 / (1 + rs)
	return np.hstack([[np.nan], rsi_])

KDJ

def kdj(close, low, high, n=9):
	hn = rolling(high, n).max(-1)
	ln = rolling(low, n).min(-1)
	rsv = (close - ln) / (hn - ln) * 100
	rsv = [x for x in rsv if not np.isnan(x)]
	rsv = np.hstack([[50], rsv])
	k = exp_smooth(rsv, 2/3)
	d = exp_smooth(k, 2/3)
	j = 3 * k - 2 * d
	pad = [np.nan] * (len(close) - len(k))
	k = np.hstack([pad, k])
	d = np.hstack([pad, d])
	j = np.hstack([pad, j])
	return k, d, j

OBV

def obv(close, vol):
	change = np.diff(close)
	sig = np.hstack([[1], np.sign(change)])
	obv_ = np.cumsum(vol * sig)
	return obv_

标签:return,RSI,KDJ,Python,win,rolling,close,np,alpha
From: https://www.cnblogs.com/apachecn/p/17547691.html

相关文章

  • python魔术方法之__new__
    一、基本用法#从一个类建立一个对象#__new__从class建立一个object过程#__init__有了object初始化过程classLanguage:def__new__(cls,*args,**kwargs):print("__new__")returnsuper().__new__(cls)def__init__(self):print(......
  • 【Python】对密码文本进行加密, 并判断 hashlib
    importhashlibdefencrypt_password(password,salt):#创建一个sha256的哈希对象sha256_hash=hashlib.sha256()#将盐值和密码组合起来并进行哈希hashed_password=salt.encode('utf-8')+password.encode('utf-8')sha256_hash.update(hashed_......
  • 5python学习笔记
    1.python特点​Python具有代码简单、学习难度低、语法清楚、功能库丰富等优势,同样功能的代码,Python代码数量只有C或Java的1/5,甚至1/10。例:打印HelloWorld,C语言需要6行,Java需要5行,Python只需要1行。2.python相关概念第三方库:需要自行安装的库python解释器:将源代码翻译......
  • python解析xml
    主要是查询标签:importxml.dom.minidoms='''xml字符串''''''这里做一些解释:<?xmlversion="1.0"encoding="UTF-8"?><soapenv:Envelopexmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/......
  • Python异步编程
    协程不是计算机提供,程序员人为创造也称为微线程,是一种上下文切换技术(通过一个线程实现代码块互相切换执行)普通代码的执行流程自上而下顺序执行deffun1():print(1)#...print(2)deffun2():print(3)#...print(4)fun1()fun2()-结......
  • 用Python编写网页自动答题工具,满分轻松到手,你就是全班最靓的仔!
    最近自动答题的外包很多,来给大家分享一下如何用Python来实现自动答题。好了话不多说,我们开始操作。首先你需要准备这些环境使用Python3.8解释器Pycharm编辑器 模块使用importrequests--->数据请求模块pipinstallrequestsimportrefromsele......
  • python安装教程
    1.下载安装python解释器:地址:https://www.python.org/downloads/release/python-372/(选择此项) 2.pycharm安装教程:安装地址:https://www.jetbrains.com/pycharm/download/download-thanks.html?platform=windows&code=PCC ......
  • python3。1
          print('您拥有三次机会输入正确的账号和密码')print('三次输入错误,账号将被锁定')i=3whilei>0:user_name=input('请输入您的账号:')psw=input('请输入密码:')ifuser_name=='zy'andpsw=='666666':......
  • 解决python升级的具体操作步骤
    如何升级Python版本作为一名经验丰富的开发者,我将帮助你学习如何升级Python版本。在本文中,我将为你提供一个详细的步骤表格,并解释每一步应该做什么,并提供相应的代码示例。升级Python的步骤以下是升级Python版本的步骤:步骤描述步骤1确定当前Python版本步骤2下载......
  • python学习笔记:继承与超类
    与java类似,继承的出现是为了提高代码的重复利用率,避免多次输入同样的代码。而超类就是java中的父类。1.继承要指定超类,可在定义类时,在class语句中的类名后加上超类名基类就是超类,派生类就是子类格式classDog:# passclassBobo(Dog):#Dog类的子类 pass子类会......