【Python 量化交易】SAR技术指标

2023-05-16

SAR Source Code

class SARIndicator(object):
    def __init__(self,
                 high: pd.Series,
                 low: pd.Series,
                 close: pd.Series,
                 period: int = 4,
                 step: float = 0.02,
                 max_step: float = 0.20,
                 fillna: bool = False,
                 ):
        self._high = high.copy()
        self._low = low.copy()
        self._close = close.copy()
        self._length = self._close.__len__()
        self._period = period - 1
        self._step = step
        self._max_step = max_step  # 步长最大值
        self._fillna = fillna  # 是否填充空值
        self._run()

    def _run(self):
        up_trend = True  # 默认初始是上升趋势
        acceleration_factor = self._step  # 初始加速因子是0.02
        up_trend_high = self._high.iloc[0]  # 初始上升趋势最高值,为第一天的最高
        down_trend_low = self._low.iloc[0]  # 初始下降趋势最低值,为第一天的最低

        self._psar = pd.Series([np.nan] * self._length, index=self._close.index)
        self._psar_up = pd.Series([np.nan] * self._length, index=self._close.index)
        self._psar_down = pd.Series([np.nan] * self._length, index=self._close.index)
        self._psar_indicator = pd.Series([np.nan] * self._length, index=self._close.index)
        self._psar_af = pd.Series([np.nan] * self._length, index=self._close.index)

        for i in range(1, self._length):
            if i < self._period:
                up_trend_high = max(self._high.iloc[i], up_trend_high)
                down_trend_low = min(self._low.iloc[i], down_trend_low)
                continue
            # print(up_trend_high, down_trend_low)

            if up_trend:
                down_trend_low = min(self._low.iloc[i], down_trend_low)

                if np.isnan(self._psar.iloc[i - 1]):  # 如果一开始是空值,上升趋势默认,min最低点
                    self._psar.iloc[i] = down_trend_low
                else:
                    self._psar.iloc[i] = self._psar.iloc[i - 1] + (  # 如果有前值,计算
                        acceleration_factor * (up_trend_high - self._psar.iloc[i - 1])
                    )
                self._psar.iloc[i] = round(self._psar.iloc[i], 2)

                if self._psar.iloc[i] > self._low.iloc[i]:  # 上升趋势中SAR大于当前最低点,则翻转
                    up_trend = False  # 表示翻转了
                    self._psar.iloc[i] = up_trend_high  # 上一周期的max最高
                    down_trend_low = self._low.iloc[i]  # 最低值是当前的最低点
                    acceleration_factor = self._step  # 加速因子重置

                else:  # 没有翻转
                    if self._high.iloc[i] > up_trend_high:  # 如果有新高
                        up_trend_high = self._high.iloc[i]  # 更新当前周期内的最高价
                        acceleration_factor = min(  # 更新加速因子
                            acceleration_factor + self._step, self._max_step
                        )
            else:  # 进入下降趋势
                up_trend_high = max(self._high.iloc[i], up_trend_high)

                self._psar.iloc[i] = self._psar.iloc[i - 1] - (  # 如果有前值,计算
                    acceleration_factor * (self._psar.iloc[i - 1] - down_trend_low)
                )
                self._psar.iloc[i] = round(self._psar.iloc[i], 2)

                if self._psar.iloc[i] < self._high.iloc[i]:  # 下降趋势中,SAR小于当前最高点,则翻转
                    up_trend = True  # 表示翻转了
                    self._psar.iloc[i] = down_trend_low  # 上一周期的min最低
                    up_trend_high = self._high.iloc[i]  # 最高值是当前的最高点
                    acceleration_factor = self._step  # 加速因子重置

                else:
                    if self._low.iloc[i] < down_trend_low:  # 如果有新低
                        down_trend_low = self._low.iloc[i]  # 更新当前周期内的最低价
                        acceleration_factor = min(  # 更新加速因子
                            acceleration_factor + self._step, self._max_step
                        )

            if up_trend:
                self._psar_up.iloc[i] = 1
                self._psar_indicator.iloc[i] = 1
            else:
                self._psar_down.iloc[i] = 1
                self._psar_indicator.iloc[i] = -1
            self._psar_af.iloc[i] = acceleration_factor

    def psar(self):
        """
        返回SAR数值
        :return:
        """
        return pd.Series(self._psar, name='psar')

    def psar_up(self):
        """
        返回上升趋势
        :return:
        """
        return pd.Series(self._psar_up, name='psar_up')

    def psar_down(self):
        """
        返回下降趋势
        :return:
        """
        return pd.Series(self._psar_down, name='psar_down')

    def psar_indicator(self):
        """
        返回多头和空头
        :return:
        """
        return pd.Series(self._psar_indicator, name='indicator')

    def psar_acceleration_factor(self):
        """
        返回加速因子
        :return:
        """
        return pd.Series(self._psar_af, name='acceleration_factor')

References

1、https://school.stockcharts.com/doku.php?id=technical_indicators:parabolic_sar
2、https://www.investopedia.com/terms/p/parabolicindicator.asp
3、https://www.spreadsheetml.com/technicalindicators/parabolicSAR.shtml
4、https://technical-analysis-library-in-python.readthedocs.io/en/latest/ta.html#momentum-indicators



欢迎关注~ SandQuant 专注于全球金融数据和量化投资策略

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

【Python 量化交易】SAR技术指标 的相关文章

  • Python、Tkinter、更改标签颜色

    有没有一种简单的方法来更改按钮中文本的颜色 I use button text input text here 更改按下后按钮文本的内容 是否存在类似的颜色变化 button color red Use the foreground设置按钮
  • Python PAM 模块的安全问题?

    我有兴趣编写一个 PAM 模块 该模块将利用流行的 Unix 登录身份验证机制 我过去的大部分编程经验都是使用 Python 进行的 并且我正在交互的系统已经有一个 Python API 我用谷歌搜索发现pam python http pa
  • 如何使用固定的 pandas 数据框进行动态 matplotlib 绘图?

    我有一个名为的数据框benchmark returns and strategy returns 两者具有相同的时间跨度 我想找到一种方法以漂亮的动画风格绘制数据点 以便它显示逐渐加载的所有点 我知道有一个matplotlib animat
  • 更改自动插入 tkinter 小部件的文本颜色

    我有一个文本框小部件 其中插入了三条消息 一条是开始消息 一条是结束消息 一条是在 单位 被摧毁时发出警报的消息 我希望开始和结束消息是黑色的 但被毁坏的消息 参见我在代码中评论的位置 插入小部件时颜色为红色 我不太确定如何去做这件事 我看
  • Python 多处理示例不起作用

    我正在尝试学习如何使用multiprocessing但我无法让它发挥作用 这是代码文档 http docs python org 2 library multiprocessing html from multiprocessing imp
  • pandas 替换多个值

    以下是示例数据框 gt gt gt df pd DataFrame a 1 1 1 2 2 b 11 22 33 44 55 gt gt gt df a b 0 1 11 1 1 22 2 1 33 3 2 44 4 3 55 现在我想根据
  • 如何使用装饰器禁用某些功能的中间件?

    我想模仿的行为csrf exempt see here https docs djangoproject com en 1 11 ref csrf django views decorators csrf csrf exempt and h
  • keras加载模型错误尝试将包含17层的权重文件加载到0层的模型中

    我目前正在使用 keras 开发 vgg16 模型 我用我的一些图层微调 vgg 模型 拟合我的模型 训练 后 我保存我的模型model save name h5 可以毫无问题地保存 但是 当我尝试使用以下命令重新加载模型时load mod
  • 在循环中每次迭代开始时将变量重新分配给原始值(在循环之前定义)

    在Python中 你使用 在每次迭代开始时将变量重新分配给原始值 在循环之前定义 时 也就是说 original 1D o o o for i in range 0 3 new original 1D revert back to orig
  • 使用 Pycharm 在 Windows 下启动应用程序时出现 UnicodeDecodeError

    问题是当我尝试启动应用程序 app py 时 我收到以下错误 UnicodeDecodeError utf 8 编解码器无法解码位置 5 中的字节 0xb3 起始字节无效 整个文件app py coding utf 8 from flask
  • Python 中的二进制缓冲区

    在Python中你可以使用StringIO https docs python org library struct html用于字符数据的类似文件的缓冲区 内存映射文件 https docs python org library mmap
  • python pandas 中的双端队列

    我正在使用Python的deque 实现一个简单的循环缓冲区 from collections import deque import numpy as np test sequence np array range 100 2 resha
  • 当玩家触摸屏幕一侧时,如何让 pygame 发出警告?

    我使用 pygame 创建了一个游戏 当玩家触摸屏幕一侧时 我想让 pygame 给出类似 你不能触摸屏幕两侧 的错误 我尝试在互联网上搜索 但没有找到任何好的结果 我想过在屏幕外添加一个方块 当玩家触摸该方块时 它会发出警告 但这花了很长
  • 检查所有值是否作为字典中的键存在

    我有一个值列表和一本字典 我想确保列表中的每个值都作为字典中的键存在 目前我正在使用两组来确定字典中是否存在任何值 unmapped set foo set bar keys 有没有更Pythonic的方法来测试这个 感觉有点像黑客 您的方
  • 如何从没有结尾的管道中读取 python 中的 stdin

    当管道来自 打开 时 不知道正确的名称 我无法从 python 中的标准输入或管道读取数据 文件 我有作为例子管道测试 py import sys import time k 0 try for line in sys stdin k k
  • 在 Pandas DataFrame Python 中添加新列[重复]

    这个问题在这里已经有答案了 例如 我在 Pandas 中有数据框 Col1 Col2 A 1 B 2 C 3 现在 如果我想再添加一个名为 Col3 的列 并且该值基于 Col2 式中 如果Col2 gt 1 则Col3为0 否则为1 所以
  • 如何使用google colab在jupyter笔记本中显示GIF?

    我正在使用 google colab 想嵌入一个 gif 有谁知道如何做到这一点 我正在使用下面的代码 它并没有在笔记本中为 gif 制作动画 我希望笔记本是交互式的 这样人们就可以看到代码的动画效果 而无需运行它 我发现很多方法在 Goo
  • 您可以在 Python 类型注释中指定方差吗?

    你能发现下面代码中的错误吗 米皮不能 from typing import Dict Any def add items d Dict str Any gt None d foo 5 d Dict str str add items d f
  • Pandas 与 Numpy 数据帧

    看这几行代码 df2 df copy df2 1 df 1 df 1 values 1 df2 ix 0 0 我们的教练说我们需要使用 values属性来访问底层的 numpy 数组 否则我们的代码将无法工作 我知道 pandas Data
  • PyAudio ErrNo 输入溢出 -9981

    我遇到了与用户相同的错误 Python 使用 Pyaudio 以 16000Hz 录制音频时出错 https stackoverflow com questions 12994981 python error audio recording

随机推荐

  • python e指数函数,常用的e指数代码

    在 python中 xff0c 有一种函数叫做e指数函数 xff08 exponential function xff09 xff0c 它的名称非常的直接 xff0c 是我们在进行数值计算时经常用到的一种函数 下面就让我们一起来学习一下这种
  • 栈的概念及性质

    栈的基本概念 栈的定义 栈是一种只能在一端进行插入或删除的线性表 其中插入被称作进栈 xff0c 删除被称作出栈 允许进行插入或删除操作的一端被称为栈顶 xff0c 另一段被称为栈底 xff0c 栈底固定不变 其中 xff0c 栈顶由一个称
  • python requests post 使用方法

    使用python模拟浏览器发送post请求 span class token keyword import span requests 1 格式request post xff1a request span class token punc
  • 各类Python项目的项目结构及代码组织最佳实践

    1 了解Python项目文件组织结构非常重要 为什么要掌握pythob项目结构 xff1f 优秀的程序员都使用规范的项目代码结构 xff0c 了解这些好的习惯方式 xff0c 能帮助你快速读懂代码如果项目是几个人合作开发 xff0c 好的代
  • Python简单的位运算

    位运算 程序中的数在计算机内存中都是以二进制的形式存在的 xff0c 位运算就是直接对整数在内存中对应的二进制位进行操作 位运算分为 6 种如下 xff1a 1 按位与 按位与运算符 xff1a 参与运算的两个值 如果两个相应位都为1 则该
  • 【Linux】WLAN接口桥接

    一 内核补丁 因为Linux内核会在注册特定设备时将会将dev gt priv flags置为IFF DONT BRIDGE xff0c 所以现还不支持sta p2p client adhoc等无线接口加入到桥接中去的 xff0c 所以要支
  • Python学习小记-爬虫基础例子之抓取热门游戏排行榜-2020-3-2

    span class token keyword import span urllib span class token punctuation span request span class token keyword import sp
  • 《A Survey on Aspect-Based Sentiment Analysis: Tasks, Methods, and Challenges》阅读笔记

    忙活了一阵子后 xff0c 现在终于有空研究一下目前如火如荼的ABSA了 xff0c 当然 xff0c 还是先从综述出发 A Survey on Aspect Based Sentiment Analysis Tasks Methods a
  • A problem has occurred and the system can‘t recover问题的解决

    A problem has occurred and the system can 39 t recover问题的解决 问题描述解决方法参考博客 问题描述 启动后无法进入图形界面 xff0c 出现如下报错内容 按 ctrl 43 alt 4
  • 安装:WSL2(Ubuntu18.04)+miniconda3+mysql数据库+windows pycharm连接wsl

    一 WSL2 xff08 Ubuntu18 04安装 xff09 1 开启 适用于Linux的Windows子系统 找到控制面板 程序和功能 启用或关闭Windows功能 xff0c 选中 适用于Linux的Windows子系统 和 虚拟机
  • 【Python入门】:字典与集合

    Problems span class token number 1 span span class token punctuation span 创建一个通讯录 xff0c 步骤如下 xff0c 请根据步骤完成以下操作 xff1a spa
  • 【Python入门】:函数1

    Problems span class token number 1 span span class token punctuation span 编写函数showMsg span class token punctuation span
  • 【Python】@property私有属性的控制和保护

    64 property的使用 xff1a 对属性的控制和保护 一 保护变量 xff0c 防止被修改 64 property的首要目的是在访问私有变量时 xff0c 保护变量不被随意修改 span class token keyword cl
  • 【Python入门】:函数2

    Problems Source Code Output span class token number 318 span span class token number 321 span span class token number 19
  • 由浅入深介绍 Python Websocket 编程

    目录 1 为什么使用 Websocket 1 1 websocket 协议简介1 2 基本原理 2 如何用 Python 搭建 Websocket 服务2 1 安装websockets包2 2 编写 server 端代码 3 Python
  • 【Python入门】:文件与异常

    Problems Source Code Output 慈母手中线 xff0c 游子身上衣 临行密密缝 xff0c 意恐迟迟归 谁言寸草心 xff0c 报得三春晖 span class token number 7 795 span spa
  • 【Python】ESC服务器通过SMTP收发邮件

    解决方法 xff1a 1 25端口基本都不能用 xff0c 所以要用SSL xff0c qq用465 2 需要添加安全组 3 关闭防火墙 4 邮箱密码是授权码 Step1 xff1a 开通邮箱smtp服务 授权码作为后续的登录密码 Step
  • 【Python 量化交易】什么是择时策略

    量化金融 xff1a 什么是择时策略 xff1f 什么是市场择时 xff1f 市场择时概要择时成本损失机会的代价交易成本的代价真实例子 什么是市场择时 xff1f 市场择时 xff0c 也可以叫做市场选时 xff0c 是一种投资或者交易的策
  • 【Python】Spy++使用

    SPY 43 43 的使用和Python操作 1 spy 43 43 的基本操作1 1 窗口属性查找1 2 窗口spy 43 43 定位 2 python与spy 43 43 Source CodeUse 下载 Spy 43 43 xff1
  • 【Python 量化交易】SAR技术指标

    SAR Source Code span class token keyword class span span class token class name SARIndicator span span class token punct