移動平均線ma分析_使用動態移動平均線構建交互式庫存量和價格分析圖

移動平均線ma分析

I decided to code out my own stock tracking chart despite a wide array of freely available tools that serve the same purpose. Why? Knowledge gain, it’s fun, and because I recognize that a simple project can generate many new ideas. Even the basic googling I did to learn more about moving averages and interactive Jupyter python charts opened the door to many amazing resources. My current 2 favorites:

盡管有許多用于相同目的的免費工具,但我還是決定編寫自己的庫存跟蹤圖。 為什么? 獲得知識,這很有趣,而且因為我認識到一個簡單的項目可以產生許多新想法。 即使是基本的谷歌搜索,我也要學習更多有關移動平均值的信息,而交互式Jupyter python圖表也打開了許多神奇資源的大門。 我目前的2個最愛:

  • Financial Signal Processing and Machine Learning by Ali Akansu

    Ali Akansu撰寫的金融信號處理和機器學習

  • This article on signal processing and trend following: https://alphaarchitect.com/2020/08/13/an-introduction-to-digital-signal-processing-for-trend-following/

    有關信號處理和趨勢的文章如下: https : //alphaarchitect.com/2020/08/13/an-introduction-to-digital-signal-processing-for-trend-following/

Regardless of the reason and research rabbit holes I found myself in, I conceded to accomplishing one small task before tackling all the new large projects inflating my notes board. The end result of my work? A simple and easily recreated chart that has some unique interactive features. By simply passing 3 parameters, you can choose whatever stock you would like to look at and then set the window size of the simple moving averages. I’ve provided the full code later in the article, but all you have to do is copy, paste, and play with these parameters.

不管我發現自己的原因和研究的麻煩,我都答應先完成一項小任務,然后再處理所有使筆記板膨脹的新的大型項目。 我工作的最終結果? 一個簡單且易于重新創建的圖表,具有一些獨特的交互功能。 通過簡單地傳遞3個參數,您可以選擇想要查看的任何股票,然后設置簡單移動平均線的窗口大小。 我將在本文后面提供完整的代碼,但是您要做的就是復制,粘貼和使用這些參數。

查詢財務數據 (Querying Financial Data)

A constant fact of life for those of us working in the data science/analytics field is that we rarely get a data set that is clean. Missing data, mismatched date-time formats, and my personal favorite… misspelled categorical values (nothing like realizing you forgot to consider all of the ‘Canceld’ data points when counting ‘Canceled’).

對于我們從事數據科學/分析領域工作的人們來說,一個永恒的事實是,我們很少獲得干凈的數據集。 數據丟失,日期時間格式不匹配,以及我個人最喜歡的……分類值拼寫錯誤(沒想到您忘了在計算“取消”時忘記考慮所有“取消”數據點)。

Like a breath of fresh air, the yfinance library for python quickly downloads financial data in a clean ready-to-work-with format: https://pypi.org/project/yfinance/

就像呼吸一口新鮮空氣一樣,用于python的yfinance庫快速以干凈的即用型格式下載財務數據: https : //pypi.org/project/yfinance/

import yfinance as yf
# data = yf.download(ticker, start_date, end_date)
data = yf.download('AAPL', '2019-08-21','2020-08-21')
data.head()

The above code downloads stock data for Apple into a pandas data-frame with Date as the index. In terms of granularity, the data returned is daily, including each day’s open, high, low, close, adjusted close, and volume for the given ticker, and looks like this:

上面的代碼將Apple的股票數據下載到以Date為索引的熊貓數據框中。 就粒度而言,每天返回的數據包括給定股票的每日開盤價,最高價,最低價,收盤價,調整后的收盤價和交易量,如下所示:

Image for post

簡單移動平均線 (Simple Moving Average)

The simple moving average is calculated by adding the daily price of an asset over a specified window of time and then dividing by the number of time periods. When talking securities, we sum the adjusted closing price of ‘Stock A’ over the last ’n’ days and divide by ‘n.’ Simply put (ha ha):

通過將指定時間段內資產的每日價格相加,然后除以時間段數,可以計算出簡單移動平均線。 在談論證券時,我們將最近“ n”天的“ A股”調整后的收盤價相加,然后除以“ n”。 簡單地說(哈哈):

Image for post

In python, this equation can be performed in many ways, I feel this function is straightforward:

在python中,可以通過多種方式執行此方程式,我覺得這個函數很簡單:

import pandas as pd
import yfinance as yfdata = yf.download('AAPL', '2019-08-21', '2020-08-21')def SMA(values, window):"""SMA - returns a list of moving avg. values based on input list of values and window size  inputs:values - takes a list or pandas frame column containing ints/floatswindow - takes int as input, size of period to calc. moving avg.returns null if larger than length of param values."""x = 0moving_avg = []while x < len(values) - window + 1:current_window = values[x:x+window]window_avg = sum(current_window)/windowmoving_avg.append(window_avg)x += 1return(moving_avg)SMA(data['Adj Close'], 20)

Luckily, though, the pandas library has a built in function to accomplish this same goal, so we can easily pass a pandas data frame column and return a custom simple moving average:

不過,幸運的是,pandas庫具有一個內置函數來實現相同的目標,因此我們可以輕松地傳遞pandas數據框列并返回自定義的簡單移動平均值:

import yfinance as yf
import pandas as pddata = yf.download('AAPL', '2019-08-21', '2020-08-21')
moving_avg = data['Adj Close'].rolling(window=100).mean()
moving_avg

Here, we extend the query range to 2-years to visualize a 100-day moving average on top of the adjusted closing price:

在這里,我們將查詢范圍擴展到2年,以便在調整后的收盤價之上可視化100天移動平均線:

Image for post

The 100-day moving average completely eliminates any noise in the data, especially compared to the daily adjusted close price. A caveat of using moving averages to analyze trends is the smoothing effect that results from large window sizes. A 25, 50, and even 75 window size will show more noise from the variance in the data than the 100-day window. At what point does the moving average window size cause the trend to be too smooth, and no longer representative of the data? The answer varies based on the data itself and what signals we are looking to find.

100天移動平均線完全消除了數據中的任何噪音,尤其是與每日調整后的收盤價相比。 使用移動平均值分析趨勢的一個警告是,較大的窗口尺寸會導致平滑效果。 25天,50天甚至75天的窗口大小將比100天的窗口顯示更多來自數據差異的噪聲。 在什么時候移動平均窗口大小會導致趨勢變得過于平滑,從而不再代表數據? 答案因數據本身以及我們要查找的信號而異。

data = yf.download('AAPL', '2018-08-21', '2020-08-21')data.reset_index(level=0, inplace=True)fig, ax = plt.subplots(figsize=(15, 7))ax.set_ylabel('Adj. Closing Price ($)')
ax.set_xlabel('Date')ax.plot(data['Date'], data['Adj Close'], label='Adj. Close',color = 'red')moving100 = data['Adj Close'].rolling(window=100).mean()
ax.plot(data['Date'], moving100, label='100-Day Moving Avg.',color='orange', linestyle="--")legend = ax.legend(loc=2)
plt.show()

動態繪圖以比較移動平均趨勢并識別信號 (Dynamic Plotting to Compare Moving Average Trends and Identify Signals)

Making 3, 4, 5 charts each with their own simple moving average and underlying data is, frankly, inefficient. That’s why I wanted to build a plot that allows me to chart out as many moving averages as I desire to c.

坦率地說,制作3、4、5個圖表時,每個圖表都有自己的簡單移動平均值和基礎數據,效率很低。 這就是為什么我想構建一個圖,使我能夠繪制出我想要的任意數量的移動平均線。

The first step to making an interactive matplotlib chart is making sure the package is updated and then the simple command:

制作交互式matplotlib圖表的第一步是確保已更新軟件包,然后執行簡單命令:

%matplotlib nbagg

%matplotlib nbagg

Switching back to static plots is just as simple:

切換回靜態圖非常簡單:

%matplotlib inline

%matplotlib內聯

Another fun tool to add is the mplcursors package. This package allows us to hover over data points and receive some information, like the ‘tooltip’ in Tableau if you’re familiar with that. It’ll end up looking like this:

另一個有趣的工具是mplcursors軟件包。 此軟件包使我們可以將鼠標懸停在數據點上并接收一些信息,例如如果您熟悉Tableau中的“工具提示”。 最終看起來像這樣:

Image for post

Below, I’ve provided the code that will yield the full chart. For reference, I’ve commented out the mplcursor argument and set my matplotlib back to static — they’re the only two lines commented out so just know that removing the # and commenting out the ‘%matplotlib inline’ will allow the output of the following function to be interactive.

在下面,我提供了將生成完整圖表的代碼。 作為參考,我已經注釋掉了mplcursor參數并將我的matplotlib設置為靜態-它們是僅有的兩行被注釋掉了,所以只要知道刪除#并注釋掉'%matplotlib inline'將允許輸出以下功能是交互式的。

#%matplotlib nbagg
%matplotlib inlinedef Volume_Line_Chart(ticker, SMA_Window1, SMA_Window2):x = datetime.date.today()y = x - dateutil.relativedelta.relativedelta(months = 24)data = yf.download(ticker, y,x)data.reset_index(level=0, inplace=True)fig, ax1 = plt.subplots(figsize=(15, 7))ax1.set_ylabel('Vol.')ax1.set_xlabel('Date')ax1.bar(data['Date'], data['Volume'], label='Volume', alpha=0.3)ax2 = ax1.twinx()ax2.set_ylabel('Adj. Close Price')roll1 = data['Adj Close'].rolling(window=SMA_Window1).mean()ax2.plot(data['Date'], roll1, color='red', label=str(SMA_Window1)+' - Day Moving Avg.', linestyle='--')roll2 = data['Adj Close'].rolling(window=SMA_Window2).mean()ax2.plot(data['Date'], roll2, color='orange', label=str(SMA_Window2)+' - Day Moving Avg.', linestyle='-')ax2.plot(data['Date'], data['Adj Close'], color='blue', label='Adj Close', linestyle='-.')ax1.get_yaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))legend = ax1.legend(loc=2), ax2.legend(loc=9)fig.tight_layout()#mplcursors.cursor(hover=True)plt.show()Volume_Line_Chart('AAPL', 50, 100)

I’ve made it as simple as plug and play — just change the ticker symbol from AAPL to whatever publicly listed security you want, contained in ‘ ’ of course, and then run it. Changing the moving average window sizes will also dynamically change their label that will appear on the chart, so no need to go into the function and change the name of the moving average lines manually. The end result will look like this:

我已經做到了即插即用的簡單操作-只需將代碼從AAPL更改為所需的任何公開列出的安全性(當然包含在“”中),然后運行它即可。 更改移動平均線窗口大小還將動態更改其標簽,該標簽將出現在圖表上,因此無需進入功能并手動更改移動平均線的名稱。 最終結果將如下所示:

Image for post

By enabling the two commented out lines you will be able to hover and get a tooltip pop-up like the previous image.

通過啟用兩條注釋掉的行,您將能夠像以前的圖像一樣懸停并彈出工具提示彈出窗口。

It’s basic, simple, but a great chart to have the ability to build. To add more SMA lines, simply copy and paste these lines, but replace the number after roll:

它是基本的,簡單的但具有構建能力的強大圖表。 要添加更多SMA線,只需復制并粘貼這些線,但在滾動后替換數字:

Image for post

And then don’t forget to include a new parameter for the function.

然后不要忘記為該函數包括一個新參數。

Image for post

In terms of signal recognition, I don’t have anything automated. My next project will ideally result in a function that can identify the crossover points of the moving average lines. A basic signal would be to buy shares of the given stock when the shorter window moving average crosses above the longer moving average, indicating upward momentum. I drew that green box in Microsoft Paint — which is my preferred method of disappointing every art teacher I’ve ever had.

在信號識別方面,我沒有自動化的東西。 理想情況下,我的下一個項目將產生一個可以識別移動平均線交叉點的函數。 一個基本的信號是,當較短的窗口移動平均線超過較長的移動平均線時,買入給定股票的股票,表明上升勢頭。 我在Microsoft Paint中畫了一個綠色框,這是讓我曾經有過的每位美術老師失望的首選方法。

Further, another simple signal is to sell when the shorter window average line dips below the longer window average line. Many rudimentary algorithm trading bots are built on this simple buy/sell rule set for simple moving averages.

此外,當較短的窗口平均線跌落至較長的窗口平均線以下時,另一個簡單的信號就是賣出。 許多基本的算法交易機器人都基于此簡單的買賣規則集,用于簡單的移動平均線。

I hope this article helps someone build a better chart, learn something new, or inspire a small project. Regardless, thanks for reading it.

我希望本文能幫助某人建立更好的圖表,學習新知識或激發一個小型項目。 無論如何,感謝您的閱讀。

翻譯自: https://medium.com/@desant_c1/building-an-interactive-stock-volume-and-price-analysis-chart-with-dynamic-moving-averages-7c0798abe373

移動平均線ma分析

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391861.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391861.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391861.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

敏捷開發創始人_開發人員和技術創始人如何將他們的想法轉化為UI設計

敏捷開發創始人by Simon McCade西蒙麥卡德(Simon McCade) 開發人員和技術創始人如何將他們的想法轉化為UI設計 (How developers and tech founders can turn their ideas into UI design) Discover how to turn a great idea for a product or service into a beautiful UI de…

在ubuntu怎樣修改默認的編碼格式

ubuntu修改系統默認編碼的方法是&#xff1a;1. 參考 /usr/share/i18n/SUPPORTED 編輯/var/lib/locales/supported.d/* gedit /var/lib/locales/supported.d/localgedit /var/lib/locales/supported.d/zh-hans如&#xff1a;more /var/lib/locales/supported.d/localzh_CN GB18…

JAVA中PO,BO,VO,DTO,POJO,Entity

https://my.oschina.net/liaodo/blog/2988512轉載于:https://www.cnblogs.com/dianzan/p/11311217.html

【Lolttery】項目開發日志 (三)維護好一個項目好難

項目的各種配置開始出現混亂的現象了 在只有一個人開發的情況下也開始感受到維護一個項目的難度。 之前明明還好用的東西&#xff0c;轉眼就各種莫名其妙的報錯&#xff0c;完全不知道為什么。 今天一天的工作基本上就是整理各種配置。 再加上之前數據庫設計出現了問題&#xf…

leetcode 567. 字符串的排列(滑動窗口)

給定兩個字符串 s1 和 s2&#xff0c;寫一個函數來判斷 s2 是否包含 s1 的排列。 換句話說&#xff0c;第一個字符串的排列之一是第二個字符串的子串。 示例1: 輸入: s1 “ab” s2 “eidbaooo” 輸出: True 解釋: s2 包含 s1 的排列之一 (“ba”). 解題思路 和s1每個字符…

靜態變數和非靜態變數_統計資料:了解變數

靜態變數和非靜態變數Statistics 101: Understanding the different type of variables.統計101&#xff1a;了解變量的不同類型。 As we enter the latter part of the year 2020, it is safe to say that companies utilize data to assist in making business decisions. F…

代碼走查和代碼審查_如何避免代碼審查陷阱降低生產率

代碼走查和代碼審查Code reviewing is an engineering practice used by many high performing teams. And even though this software practice has many advantages, teams doing code reviews also encounter quite a few code review pitfalls.代碼審查是許多高性能團隊使用…

Zabbix3.2安裝

一、環境 OS: CentOS7.0.1406 Zabbix版本: Zabbix-3.2 下載地址: http://repo.zabbix.com/zabbix/3.2/rhel/7/x86_64/zabbix-release-3.2-1.el7.noarch.rpm MySQL版本: 5.6.37 MySQL: http://repo.mysql.com/mysql-community-release-el7-5.noarch.r…

Warensoft Unity3D通信庫使用向導4-SQL SERVER訪問組件使用說明

Warensoft Unity3D通信庫使用向導4-SQL SERVER訪問組件使用說明 (作者:warensoft,有問題請聯系warensoft163.com) 在前一節《warensoft unity3d通信庫使用向導3-建立WarensoftDataService》中已經說明如何配置Warensoft Data Service&#xff0c;從本節開始&#xff0c;將說明…

01-gt;選中UITableViewCell后,Cell中的UILabel的背景顏色變成透明色

解決方案有兩種方法一 -> 新建一個UILabel類, 繼承UILabel, 然后重寫 setBackgroundColor: 方法, 在這個方法里不做任何操作, 讓UILabel的backgroundColor不發生改變.寫在最后, 感謝參考的出處:不是謝志偉StackOverflow: UITableViewCell makes labels background clear whe…

leetcode 703. 數據流中的第 K 大元素(堆)

設計一個找到數據流中第 k 大元素的類&#xff08;class&#xff09;。注意是排序后的第 k 大元素&#xff0c;不是第 k 個不同的元素。 請實現 KthLargest 類&#xff1a; KthLargest(int k, int[] nums) 使用整數 k 和整數流 nums 初始化對象。 int add(int val) 將 val 插…

不知道輸入何時停止_知道何時停止

不知道輸入何時停止In predictive analytics, it can be a tricky thing to know when to stop.在預測分析中&#xff0c;知道何時停止可能是一件棘手的事情。 Unlike many of life’s activities, there’s no definitive finishing line, after which you can say “tick, I…

移動認證_如何在移動設備上實施安全的生物特征認證

移動認證by Kathy Dinh凱西丁(Kathy Dinh) 如何在移動設備上實施安全的生物特征認證 (How to implement secure Biometric Authentication on mobile devices) A quick search for React Native biometric authentication would give you several tutorials. That was the fir…

[Luogu1890]gcd區間

原題鏈接https://www.luogu.org/problem/show?pid1890 暴力中的暴力。 對于每一組詢問l..r&#xff0c;我們先循環暴力枚舉l..r中最大值到1&#xff0c;再暴力循環l..r的每一個數&#xff0c;判斷前一重循環能否整除后一重&#xff0c;如果全部都能&#xff0c;則可判定它就是…

Android Studio自定義模板 做開發竟然可以如此輕松 后篇

###1.概述 最近有很多人反饋&#xff0c;有些哥們不喜歡看文字性的東西&#xff0c;還有一些哥們根本就不知道我在搞啥子&#xff0c;那么以后我就采用博客加視頻的方式&#xff0c;我們可以選擇看視頻講解&#xff1a;http://pan.baidu.com/s/1i5uh2uD   內涵段子項目資料及…

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. 解決方案&#xff1a; 異步更新&#xff08;建議使用&#xff09;強制進行變更檢測&#xff0c;但是會觸發子組件的變更檢測&#xff0c;再次導致父組件屬性改變Parent.Component.…

leetcode 119. 楊輝三角 II

給定一個非負索引 k&#xff0c;其中 k ≤ 33&#xff0c;返回楊輝三角的第 k 行。 在楊輝三角中&#xff0c;每個數是它左上方和右上方的數的和。 示例: 輸入: 3 輸出: [1,3,3,1] 解題思路 因為楊輝三角的下層由上一層決定&#xff0c;所以只需要保存上一層的元素&#x…

掌握大數據數據分析師嗎?_要掌握您的數據嗎? 這就是為什么您應該關心元數據的原因...

掌握大數據數據分析師嗎?Either you are a data scientist, a data engineer, or someone enthusiastic about data, understanding your data is one thing you don’t want to overlook. We usually regard data as numbers, texts, or images, but data is more than that.…

react 使用 mobx_如何使用React和MobX狀態樹構建基于狀態的路由器

react 使用 mobxby Miles Till由Miles Till 如何使用React和MobX狀態樹構建基于狀態的路由器 (How to build a state-based router using React and MobX State Tree) Introducing mobx-state-tree-routerMobx狀態樹路由器簡介 If you want to skip ahead to the finished ex…

docker在Centos上的安裝

Centos6安裝docker 系統&#xff1a;centos6.5 內核&#xff1a;3.10.107-1(已升級)&#xff0c;docker對RHEL/Centos的最低內核支持是2.6.32-431&#xff0c;epel源的docker版本推薦內核為3.10版本。 內核升級可參考&#xff1a;https://www.jslink.org/linux/centos-kernel-u…