python:自行计算 OBV

自行计算 OBV (On-Balance Volume,净额成交量或叫能量潮指标)

用于检验 talib.OBV(df.close, df.volume) 的正确性。

stock_obv.py

# -*- coding: utf-8 -*-
import os, sys
import tushare as ts
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

if len(sys.argv) ==2:
    code = sys.argv[1]
else:
    print('usage: python stock_obv.py stockcode ')
    sys.exit(1)

if len(code) !=6:
    print('stock code length: 6')
    sys.exit(2)

df = ts.get_k_data(code)
if df.empty ==True:
    print(" df is empty ")
    sys.exit(2)

df = df[ df.date > '2019-01-01']
if len(df) <10:
    print(" len(df) <10 ")
    sys.exit(2)

# 收盘价
close = np.array(df.close)
# 成交量
vol = np.array(df.volume)
# 为了判断计算中成交量前的正负号,我们先使用diff函数计算收盘价的变化量。
# diff函数可以计算数组中两个连续元素的差值,并返回一个由这些差值组成的数组:
change = np.diff(close)
#print(change)

# 使用sign函数可以返回数组中每个元素的正负符号,数组元素为负时返回-1,
# 为正时返回1,否则返回0。
signs = np.sign(change)
#print(signs)

# 我们也可以使用piecewise函数来获取数组元素的正负。
# piecewise 函数可以分段给定取值。使用合适的返回值和对应的条件调用该函数:
pieces = np.piecewise(change, [change <0, change >0], [-1, 1])
#print(pieces)
print("Array equal?", np.array_equal(signs, pieces))

# OBV值的计算依赖于前一日的收盘价
vols = np.concatenate(([vol[0]], vol[1:] * signs )) # np 拼接
#print(vols[-5:])
# 求OBV值 := 计算累加之和
obv = np.cumsum(vols)
#print(type(obv))
print(obv[-5:])

df2 = pd.DataFrame(columns=['OBV'], data=obv)
df.index = pd.to_datetime(df.date)
# 画股票收盘价图
fig,axes = plt.subplots(2,1)
df[['close']].plot(ax=axes[0], grid=True, title=code)
# 画 OBV 曲线图
df2.plot(ax=axes[1], grid=True)
plt.show()

运行 python stock_obv.py 600030

参考: https://www.cnblogs.com/zhangshuwen/p/7017074.html

OBV是指净额成交量或叫能量潮指标(On-Balance Volume)。它是一种量价指标,用于衡量买卖压力的强度。根据引用\[1\]和引用\[2\]的代码,可以看出两种计算OBV的方法。引用\[1\]中的代码使用了talib库中的OBV函数来计算OBV值,并将结果打印出来。而引用\[2\]中的代码是自定义的计算OBV的方法,通过遍历数据,根据收盘价的涨跌情况来计算OBV值,并将结果存储在df\['OBV'\]这一列中。根据引用\[3\]的描述,可以看出在第21行从指定的csv文件中读取了交易数据,并在第23行调用了calOBV方法计算OBV值,并将结果存放在df对象中。如果想要验证计算OBV结果,可以取消第24行的注释,使得打印语句生效。 #### 引用[.reference_title] - *1* [python:talib 计算 OBV](https://blog.csdn.net/belldeep/article/details/103220513)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [用Python语言绘制股市OBV指标效果](https://blog.csdn.net/sxeric/article/details/107178192)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值