動量策略 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.pswp.cn/news/388886.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/388886.shtml
英文地址,請注明出處:http://en.pswp.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…

webservice 啟用代理服務器

您會發現你寫完了一個webservice在調用的時候發現怎也沒辦法調用&#xff0c;一個簡單的webservice怎么不能使用&#xff0c;一肚子的怨恨&#xff0c;哈哈您可能沒有為webservice設置代理。 下面就給您寫個調用的用例和大家分享下。其實很簡單&#xff0c;但是你沒有想到的時…

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;主服務器也可以提供…

golang 編寫的在線redis 內存分析工具 rma4go

redis 內存分析工具 rma4go redis是一個很有名的內存型數據庫&#xff0c;這里不做詳細介紹。而rma4go (redis memory analyzer for golang) 是一個redis的內存分析工具&#xff0c;這個工具的主要作用是針對運行時期的redis進行內存的分析&#xff0c;統計redis中key的分布情…

從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…

【EasyNetQ】- 使用Future Publish調度事件

許多業務流程要求在將來某個日期安排事件。例如&#xff0c;在與客戶進行初次銷售聯系后&#xff0c;我們可能希望在將來的某個時間安排跟進電話。EasyNetQ可以通過其Future Publish功能幫助您實現此功能。例如&#xff0c;這里我們使用FuturePublish擴展方法來安排未來一個月的…

Java這些多線程基礎知識你會嗎?

0、并發和并行、進程核線程、多進程和多線程的區別&#xff1a; &#xff08;這里的時間和時刻上的概念同物理上的一樣&#xff09; 并發&#xff1a;在一段時間內多個任務同時執行&#xff0c;或者說是在一段很短的時間內可以執行多條程序指令&#xff0c;微觀上看起來好像是可…

MySQL set names 命令_mysql set names 命令和 mysql 字符編碼問題

先看下面的執行結果&#xff1a;(rootlocalhost)[(none)]mysql>show variables like character%;---------------------------------------------------------------------------------------| Variable_name | Value |---------------------------------------------------…

設置Proxy Server和SQL Server實現數據庫安全

首先&#xff0c;我們需要了解一下SQL Server在WinSock上定義協議的步驟&#xff1a; 1. 在”啟動”菜單上&#xff0c;指向”程序/Microsoft Proxy Server”&#xff0c;然后點擊”Microsoft Management Console”。 2. 展開”Internet Information Service”,再展開運行Proxy…

Python django解決跨域請求的問題

解決方案 1.安裝django-cors-headers pip3 install django-cors-headers 2.配置settings.py文件 INSTALLED_APPS [...corsheaders&#xff0c;...] MIDDLEWARE_CLASSES (...corsheaders.middleware.CorsMiddleware,django.middleware.common.CommonMiddleware, # 注意順序...…

加勒比海兔_加勒比海海洋物種趨勢

加勒比海兔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; 或者…

mysql 查出相差年數_MySQL計算兩個日期相差的天數、月數、年數

MySQL自帶的日期函數TIMESTAMPDIFF計算兩個日期相差的秒數、分鐘數、小時數、天數、周數、季度數、月數、年數&#xff0c;當前日期增加或者減少一天、一周等等。SELECT TIMESTAMPDIFF(類型,開始時間,結束時間)相差的秒數&#xff1a;SELECT TIMESTAMPDIFF(SECOND,1993-03-23 0…

tornado 簡易教程

引言 回想Django的部署方式 以Django為代表的python web應用部署時采用wsgi協議與服務器對接&#xff08;被服務器托管&#xff09;&#xff0c;而這類服務器通常都是基于多線程的&#xff0c;也就是說每一個網絡請求服務器都會有一個對應的線程來用web應用&#xff08;如Djang…

如果你的電腦是通過代理上網的.就要用端口映射

由于公網IP地址有限&#xff0c;不少ISP都采用多個內網用戶通過代理和網關路由共用一個公網IP上INTERNET的方法&#xff0c; 這樣就限制了這些用戶在自己計算機上架設個人網站&#xff0c;要實現在這些用戶端架設網站&#xff0c;最關鍵的一點是&#xff0c; 怎樣把多用戶的內網…

人口密度可視化_使用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