Last active
January 11, 2021 10:14
-
-
Save s-tlm/7b264c64e2d74373dd552ce51a969684 to your computer and use it in GitHub Desktop.
Moving Average Code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import pandas as pd | |
| import os | |
| # Class setup | |
| class MovingAverage(): | |
| def __init__(self, closing_prices): | |
| self.data = pd.DataFrame(closing_prices) | |
| def EMA(self, averaging_length=50): | |
| ret = self.data.ewm( | |
| span=averaging_length, | |
| adjust=False).mean() | |
| return ret.rename(columns={'Close': 'EMA'}) | |
| def MACD(self, a=12, b=26, c=9): | |
| MACD_line = self.EMA(a) - self.EMA(b) | |
| signal_line = MACD_line.ewm(span=c, adjust=False).mean() | |
| histogram = MACD_line - signal_line | |
| return MACD_line, signal_line, histogram | |
| # Importing stock data | |
| DATA_DIR = ('C:\\MY_DIRECTORY\\ANZ.AX.csv') | |
| STOCK_SYM = os.path.basename(DATA_DIR).split('.csv')[0] # reads the stock ticker symbol from the file name | |
| df = pd.read_csv( | |
| DATA_DIR, | |
| index_col='Date', # dates parsed as index | |
| parse_dates=True, | |
| dayfirst=True # DD/MM formatting | |
| ) | |
| df = df.asfreq('B') # B for Business calendar (no weekends) | |
| df = df.fillna(method='ffill') # fills any missing day's data with previous day's | |
| closing_prices = df.Close # takes column labelled 'Close' | |
| # Executing class | |
| MACD_indicator = MovingAverage(closing_prices) | |
| MACD_line, signal_line, histogram = MACD_indicator.MACD() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment