Python Forum

Full Version: Passing Values of Dictionaries to Function & Unable to Access Them
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello Everyone!
I need your help with the following problem. I have a list of dictionaries and try to access the value of each dictionary in the list that are then passed to a function, e.i. ExpMovingAverage, which in turn is supposed to return the calculated value (based on the function formula) and will associate that returned value with its corresponding key. For example, for AAPL would get its current and open prices and stores them in val, thus if ExpMovingAverage(val, 3)= 1.245.. then result should be{'AAPL',1.245..} and do the same for other dictionaries in my list.
This is the error message i get:
Error:
Traceback (most recent call last): File "C:/Users/.../Desktop/multiEMAs.py", line 35, in <module> ema_val = ExpMovingAverage(val, 3) NameError: name 'val' is not defined
This is my scrip:
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

get_curprices = lambda:stockdata()[0]
#getting dataset of current prices into a dictionary
dict_curprices = {}
dict_curprices.update(get_curprices())

get_openprices  = lambda:stockdata()[1]
#getting dataset of open prices into a dictionary
dict_openprices = {}
dict_openprices.update(get_openprices())

def ExpMovingAverage(values, window):
    dataList = []
    #attempting to access only the value part of each above dictionary, e.g. get_curprices, get_openprices,...
    dataList = [get_curprices, get_openprices]
    for dic in dataList:
        for val in dic.values():
            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__":
    ema_val = ExpMovingAverage(val, 3)
    print(ema_val, dic.key()) 
In the line
ema_val = ExpMovingAverage(val, 3)
val has not been defined.
you need to define it before using it
val = # set it as something usefull
Hi Yoriz, thank you for the reply and help. I tried some reworking the script in the hope of making changes based on your suggestion (i hope i did). I am getting the following error message
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\bgeor\Desktop\multiEMAs.py", line 16, in ExpMovingAverage a = np.convolve(values, weights, mode='full')[:len(values)] File "C:\Users\bgeor\AppData\Local\Programs\Python\Python37-32\lib\site-packages\numpy\core\numeric.py", line 1114, in convolve return multiarray.correlate(a, v[::-1], mode) TypeError: Cannot cast array data from dtype('float64') to dtype('<U32') according to the rule 'safe'
in the reworked version i removed the lines
get_curprices = lambda:stockdata()[0]
#getting dataset of current prices into a dictionary
dict_curprices = {}
dict_curprices.update(get_curprices())
 
get_openprices  = lambda:stockdata()[1]
#getting dataset of open prices into a dictionary
dict_openprices = {}
dict_openprices.update(get_openprices())
as it seems they won't affect the result i'm after
This is the new version:
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__":
    dF = pd.DataFrame(stockdata())
    data = dict(dF)
    for val in data.keys():
        ema_val = ExpMovingAverage(val, 3)
        print(ema_val, key) 
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:
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