Aug-03-2019, 10:25 PM
Hi Yoriz, thank you for the help as it led me to review and see what was wrong. Just for anyone to see the final solution, this is the full working script:
Exp. moving average based on open and current price is [205.53] AAPL
Exp. moving average based on open and current price is [138.09] MSFT
Exp. moving average based on open and current price is [231.35] TSLA
It is important to note that in
import numpy as np import pandas as pd from yahoofinancials import YahooFinancials stocks = ['AAPL', 'MSFT', 'TSLA'] def stockdata(): yahoo_financials = YahooFinancials(stocks) price = yahoo_financials.get_current_price() Open = yahoo_financials.get_open_price() return price, Open def ExpMovingAverage(values, window): weights = np.exp(np.linspace(-1., 0., window)) weights /= weights.sum() a = np.convolve(values, weights, mode='full')[:len(values)] a[:window] = a[window] return a if __name__ == "__main__": price = get_curprice() dF = pd.DataFrame(stockdata()) data = dict(dF) for index, val in data.items(): ema_val = ExpMovingAverage(val, 1) print("Exp. moving average based on open and current price is ", ema_val[-1:], index)The output, as expected, is:
Exp. moving average based on open and current price is [205.53] AAPL
Exp. moving average based on open and current price is [138.09] MSFT
Exp. moving average based on open and current price is [231.35] TSLA
It is important to note that in
weights = np.exp(np.linspace(-1., 0., window))'window' refers to the number of data points to be averaged, in my example i'm using the 'open' and 'current' prices hence i use 'window = 1' since the index starts at 0. Not taking this into account will result in a thrown error such as
Error:Traceback (most recent call last):
File "C:\Users\bgeor\Desktop\multiEMAs.py", line 24, in <module>
ema_val = ExpMovingAverage(val, 3)
File "C:\Users\...\Desktop\multiEMAs.py", line 17, in ExpMovingAverage
a[:window] = a[window]
IndexError: index 3 is out of bounds for axis 0 with size 2