移動平均線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為索引的熊貓數據框中。 就粒度而言,每天返回的數據包括給定股票的每日開盤價,最高價,最低價,收盤價,調整后的收盤價和交易量,如下所示:

簡單移動平均線 (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”。 簡單地說(哈哈):

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天移動平均線:

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中的“工具提示”。 最終看起來像這樣:

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更改為所需的任何公開列出的安全性(當然包含在“”中),然后運行它即可。 更改移動平均線窗口大小還將動態更改其標簽,該標簽將出現在圖表上,因此無需進入功能并手動更改移動平均線的名稱。 最終結果將如下所示:

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線,只需復制并粘貼這些線,但在滾動后替換數字:

And then don’t forget to include a new parameter for the function.
然后不要忘記為該函數包括一個新參數。

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,一經查實,立即刪除!