动量策略 python_在Python中使用动量通道进行交易

动量策略 python

Most traders use Bollinger Bands. However, price is not normally distributed. That’s why only 42% of prices will close within one standard deviation. Please go ahead and read this article. However, I have some good news.

大多数交易者使用布林带。 但是,价格不是正态分布的。 这就是为什么只有42%的价格会在一个标准偏差之内收盘的原因。 请继续阅读本文 。 但是,我有一些好消息。

Price is not normally distributed. Returns are!

价格不是正态分布。 退货都是!

Yes price is not normally distributed. Because price is nothing but sum of returns. And returns are normally distributed. So let’s jump in coding and hopefully you will have an “Aha!” moment.

是的,价格不是正态分布。 因为价格不过是回报之和。 收益是正态分布的。 因此,让我们开始编码,希望您会得到一个“ 啊哈 !” 时刻。

I’m going to use EURUSD daily chart in my sample. However, it’s going to work with all assets and all timeframes.

我将在示例中使用EURUSD每日图表。 但是,它将适用于所有资产和所有时间范围。

Add required libraries

添加所需的库

# we only need these 3 libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

Not let’s write the code to load our time-series dataset

不让我们编写代码来加载时间序列数据集

def load_file(f):
fixprice = lambda x: float(x.replace(',', '.'))
df = pd.read_csv(f)
if "Gmt time" in df.columns:
df['Date'] = pd.to_datetime(df['Gmt time'], format="%d.%m.%Y %H:%M:%S.%f")
elif "time" in df.columns:
df['Date'] = pd.to_datetime(df['time'], unit="s")
df['Date'] = df['Date'] + np.timedelta64(3 * 60, "m")
df[['Date', 'Open', 'High', 'Low', 'Close']] = df[['Date', 'open', 'high', 'low', 'close']]
df = df[['Date', 'Open', 'High', 'Low', 'Close']]
elif "Tarih" in df.columns:
df['Date'] = pd.to_datetime(df['Tarih'], format="%d.%m.%Y")
df['Open'] = df['Açılış'].apply(fixprice)
df['High'] = df['Yüksek'].apply(fixprice)
df['Low'] = df['Düşük'].apply(fixprice)
df['Close'] = df['Şimdi'].apply(fixprice)
else:
df["Date"] = pd.to_datetime(df["Date"])
# we need to shift or we will have lookahead bias in code
df["Returns"] = (df["Close"].shift(1) - df["Close"].shift(2)) / df["Close"].shift(2)
return df

Now if you look at the code, I have added a column “Returns” and it’s shifted. We don’t want our indicator to repaint and i don’t want to have lookahead bias. I am basically calculating the change from yesterday’s close to today’s close and shifting.

现在,如果您看一下代码,我添加了“ Returns”列,它已转移。 我们不希望我们的指标重新粉刷,我也不想有前瞻性偏见。 我基本上是在计算从昨天的收盘价到今天的收盘价的变化。

Load your dataset and plot histogram of Returns

加载数据集并绘制退货的直方图

sym = "EURUSD"
period = "1d"
fl = "./{YOUR_PATH}/{} {}.csv".format(period, sym)
df = load_file(fl)
df["Returns"].hist(bins=1000, grid=False)
Image for post
EURUSD daily returns histogram
EURUSD每日收益柱状图

Perfect bell shape curve. Now we know that we can get some real probabilities right? Empirical Rule (a.k.a. 68–95–99.7 rule) states that 68% of data will fall within one standard deviation, 95% of data will fall within two standard deviation and 99.7% of data will fall within three standard deviation. Ok let’s write the code to calculate it for us.

完美的钟形曲线。 现在我们知道可以得到一些真实的概率了吗? 经验法则 (也称为68–95–99.7规则)指出,68%的数据将落在一个标准偏差内,95%的数据将落在两个标准偏差内,而99.7%的数据将落在三个标准偏差内。 好的,让我们编写代码为我们计算一下。

def add_momentum(df, lb=20, std=2):
df["MA"] = df["Returns"].rolling(lb).mean()
df["STD"] = df["Returns"].rolling(lb).std()
df["OVB"] = df["Close"].shift(1) * (1 + (df["MA"] + df["STD"] * std))
df["OVS"] = df["Close"].shift(1) * (1 + (df["MA"] - df["STD"] * std))
return df

Now as we already have previous Bar’s close, it’s easy and safe to use and calculate the standard deviation. Also it’s easy for us to have overbought and oversold levels in advance. And they will stay there from the beginning of the current period. I also want to be sure if my data going to follow the empirical rule. So i want to get the statistics. Let’s code that block as well.

现在,由于我们已经关闭了先前的Bar,因此可以轻松安全地使用和计算标准偏差。 同样,我们很容易提前超买和超卖。 他们将从当前阶段开始一直呆在那里。 我还想确定我的数据是否遵循经验法则。 所以我想获得统计数据。 让我们也对该块进行编码。

def stats(df):
total = len(df)
ins1 = df[(df["Close"] > df["OVS"]) & (df["Close"] < df["OVB"])]
ins2 = df[(df["Close"] > df["OVS"])]
ins3 = df[(df["Close"] < df["OVB"])]
il1 = len(ins1)
il2 = len(ins2)
il3 = len(ins3)
r1 = np.round(il1 / total * 100, 2)
r2 = np.round(il2 / total * 100, 2)
r3 = np.round(il3 / total * 100, 2)
return r1, r2, r3

Now let’s call these function…

现在让我们称这些功能为…

df = add_momentum(df, lb=20, std=1)
stats(df)

Output is (67.36, 83.3, 83.77). So close price falls 67.36% within one standard deviation. Closing price is above OVS with 83.3% and below OVB with 83.77%. Amazing results… Now time to plot our bands to see how they look in the chart.

输出为(67.36、83.3、83.77)。 因此,收盘价在一个标准偏差之内下跌67.36%。 收盘价高于OVS,为83.3%,低于OVB,为83.77%。 惊人的结果...现在该绘制我们的乐队,看看它们在图表中的样子。

I love candles. So let’s code it in a quick and dirty way and plot how our levels look.

我爱蜡烛。 因此,让我们以一种快速而肮脏的方式对其进行编码,并绘制出关卡的外观。

def plot_candles(df, l=0):
"""
Plots candles
l: plot last n candles. If set zero, draw all
"""
db = df.copy()
if l > 0:
db = db[-l:]
db = db.reset_index(drop=True).reset_index()
db["Up"] = db["Close"] > db["Open"]
db["Bottom"] = np.where(db["Up"], db["Open"], db["Close"])
db["Bar"] = db["High"] - db["Low"]
db["Body"] = abs(db["Close"] - db["Open"])
db["Color"] = np.where(db["Up"], "g", "r")
fig, ax = plt.subplots(1, 1, figsize=(16, 9))
ax.yaxis.tick_right()
ax.bar(db["index"], bottom=db["Low"], height=db["Bar"], width=0.25, color="#000000")
ax.bar(db["index"], bottom=db["Bottom"], height=db["Body"], width=0.5, color=db["Color"])
ax.plot(db["OVB"], color="r", linewidth=0.25)
ax.plot(db["OVS"], color="r", linewidth=0.25)
plt.show()

I want to see last 100 candles. Now let’s call this function

我想看最后100支蜡烛。 现在我们叫这个功能

plot_candles(df, l=100)
Image for post
EURUSD daily momentum channel bands
欧元兑美元每日动能通道带

接下来做什么? (What to do next?)

Well to be honest, if i would be making money using this strategy, i wouldn’t share it here with you (no offense). I wouldn’t even sell it. However, you can use your own imagination and add some strategies on this. You can thank me later if you decide to use this code and make money. I will send you my IBAN later :)

老实说,如果我要使用这种策略来赚钱,我不会在这里与您分享(无罪)。 我什至不卖。 但是,您可以发挥自己的想象力,并为此添加一些策略。 如果您决定使用此代码并赚钱,稍后可以感谢我。 稍后我将把您的IBAN发送给您:)

Disclaimer

免责声明

I’m not a professional financial advisor. This article and codes, shared for educational purposes only and not financial advice. You are responsible your own losses or wins.

我不是专业的财务顾问。 本文和代码仅用于教育目的,不用于财务建议。 您应对自己的损失或胜利负责。

The whole code of this article can be found on this repository:

可以在此存储库中找到本文的完整代码:

Ah also; remember to follow me on the following social channels:

也啊 记得在以下社交渠道关注我:

MediumTwitterTradingViewYouTube!

中级 Twitter TradingViewYouTube !

Until next time; stay safe, trade safe!!!

直到下一次; 保持安全,交易安全!!!

Atilla Yurtseven

阿蒂拉·尤尔特斯文(Atilla Yurtseven)

翻译自: https://medium.com/swlh/trading-with-momentum-channels-in-python-f58a0f3ebd37

动量策略 python

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/388886.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

css3 变换、过渡效果、动画

1 CSS3 选择器 1.1 基本选择器 1.2 层级 空格 > .itemli ~ .item~p 1.3 属性选择器 [attr] [attrvalue] [attr^value] [attr$value] [attr*value] [][][] 1.4 伪类选择器 :link :visited :hover :active :focus :first-child .list li:first-child :last-chi…

mysql常用的存储引擎_Mysql存储引擎

什么是存储引擎&#xff1f;关系数据库表是用于存储和组织信息的数据结构&#xff0c;可以将表理解为由行和列组成的表格&#xff0c;类似于Excel的电子表格的形式。有的表简单&#xff0c;有的表复杂&#xff0c;有的表根本不用来存储任何长期的数据&#xff0c;有的表读取时非…

android studio设计模式和文本模式切换

转载于:https://www.cnblogs.com/judes/p/9437104.html

高斯模糊为什么叫高斯滤波_为什么高斯是所有发行之王?

高斯模糊为什么叫高斯滤波高斯分布及其主要特征&#xff1a; (Gaussian Distribution and its key characteristics:) Gaussian distribution is a continuous probability distribution with symmetrical sides around its center. 高斯分布是连续概率分布&#xff0c;其中心周…

C# webbrowser 代理

百度&#xff0c;google加自己理解后&#xff0c;将所得方法总结一下&#xff1a; 方法1&#xff1a;修改注册表Software//Microsoft//Windows//CurrentVersion//Internet Settings下 ProxyEnable和ProxyServer。这种方法适用于局域网用户&#xff0c;拨号用户无效。 1p…

C MySQL读写分离连接串_Mysql读写分离

一 什么是读写分离MySQL Proxy最强大的一项功能是实现“读写分离(Read/Write Splitting)”。基本的原理是让主数据库处理事务性查询&#xff0c;而从数据库处理SELECT查询。数据库复制被用来把事务性查询导致的变更同步到集群中的从数据库。当然&#xff0c;主服务器也可以提供…

从Jupyter Notebook到脚本

16 Aug: My second article: From Scripts To Prediction API8月16日&#xff1a;我的第二篇文章&#xff1a; 从脚本到预测API As advanced beginners, we know quite a lot: EDA, ML concepts, model architectures etc…… We can write a big Jupyter Notebook, click “Re…

加勒比海兔_加勒比海海洋物种趋势

加勒比海兔Ok, here’s a million dollar question: is the Caribbean really dying? Or, more specifically, are marine species found on Caribbean reefs becoming less abundant?好吧&#xff0c;这是一个百万美元的问题&#xff1a;加勒比海真的死了吗&#xff1f; 或者…

tornado 简易教程

引言 回想Django的部署方式 以Django为代表的python web应用部署时采用wsgi协议与服务器对接&#xff08;被服务器托管&#xff09;&#xff0c;而这类服务器通常都是基于多线程的&#xff0c;也就是说每一个网络请求服务器都会有一个对应的线程来用web应用&#xff08;如Djang…

人口密度可视化_使用GeoPandas可视化菲律宾的人口密度

人口密度可视化GeoVisualization /菲律宾。 (GeoVisualization /Philippines.) Population density is a crucial concept in urban planning. Theories on how it affects economic growth are divided. Some claim, as Rappaport does, that an economy is a form of “spati…

Unity - Humanoid设置Bip骨骼导入报错

报错如下&#xff1a; 解决&#xff1a; 原因是biped骨骼必须按照Unity humanoid的要求设置&#xff0c;在max中设置如下&#xff1a; 转载于:https://www.cnblogs.com/CloudLiu/p/10746052.html

Kubernetes - - k8s - v1.12.3 OpenLDAP统一认证

1&#xff0c;基本概念 为了方便管理和集成jenkins&#xff0c;k8s、harbor、jenkins均使用openLDAP统一认证。2&#xff0c;部署openLDAP 根据之前的文档&#xff0c;openLDAP使用GFS进行数据持久化。下载对应的openLDAP文件git clone https://github.com/xiaoqshuo/k8s-clust…

srpg 胜利条件设定_英雄联盟获胜条件

srpg 胜利条件设定介绍 (Introduction) The e-sports community has been growing rapidly in the past few years, and what used to be a casual pastime has morphed into an industry projected to generate $1.8 B in revenue by 2022. While there are many video games …

机器学习 综合评价_PyCaret:机器学习综合

机器学习 综合评价Any Machine Learning project journey starts with loading the dataset and ends (continues ?!) with the finalization of the optimum model or ensemble of models for predictions on unseen data and production deployment.任何机器学习项目的旅程都…

silverlight 3D 游戏开发

http://www.postvision.net/SilverMotion/DemoTech.aspx silverlight 3D 游戏开发 时间:2010-10-22 06:33来源:开心银光 作者:黎东海 点击: 562次意外发现一个silverlight的实时3D渲染引擎。性能比开源那些强很多。 而且支持直接加载maya,3Dmax等主流3D模型文件。 附件附上它的…

皮尔逊相关系数 相似系数_皮尔逊相关系数

皮尔逊相关系数 相似系数数据科学和机器学习统计 (STATISTICS FOR DATA SCIENCE AND MACHINE LEARNING) In the last post, we analyzed the relationship between categorical variables and categorical and continuous variables. In this case, we will analyze the relati…

Kubernetes持续交付-Jenkins X的Helm部署

Jenkins X 是一个集成化的 CI / CD 平台&#xff0c;可用于 部署在Kubernetes集群或云计算中心。支持在云计算环境下简单地开发和部署应用。本项目是在Kubernetes上的安装支持工具集。 本工具集中包含&#xff1a; Jenkins - 定制好的流水线和运行环境&#xff0c;完全整合CI/C…

中国石油大学(华东)暑期集训--二进制(BZOJ5294)【线段树】

问题 C: 二进制 时间限制: 1 Sec 内存限制: 128 MB提交: 8 解决: 2[提交] [状态] [讨论版] [命题人:]题目描述 pupil发现对于一个十进制数&#xff0c;无论怎么将其的数字重新排列&#xff0c;均不影响其是不是3的倍数。他想研究对于二进制&#xff0c;是否也有类似的性质。于…

Java 8 新特性之Stream API

1. 概述 1.1 简介 Java 8 中有两大最为重要的改革&#xff0c;第一个是 Lambda 表达式&#xff0c;另外一个则是 Stream API&#xff08;java.util.stream.*&#xff09;。 Stream 是 Java 8 中处理集合的关键抽象概念&#xff0c;它可以指定你希望对集合进行的操作&#xff0c…

Ubuntu中NS2安装详细教程

前言&#xff1a; NS2是指 Network Simulator version 2&#xff0c;NS&#xff08;Network Simulator&#xff09; 是一种针对网络技术的源代码公开的、免费的软件模拟平台&#xff0c;研究人员使用它可以很容易的进行网络技术的开发&#xff0c;而且发展到今天&#xff0c;它…