J-K24
J-K24

Reputation: 13

How to Use Loop for Nested Dictionaries to Compare Previous Values

I am currently working on a trying to create my own code for stock trade. With a Nested Dictionary

Dict = { 
  "2020-03-27": {"Price": "483.4200", "Volume": "14377408"},
  "2020-03-30": {"Price": "543.3600", "Volume": "14377408"},
  "2020-04-01": {"Price": "613.1600", "Volume": "14377408"},
  "2020-04-02": {"Price": "631.0900", "Volume": "14377408"}
}

With the above dictionary, I was trying to find a way how I can compare each previous "Price" value, and go on from there. Something I have in mind is like the one below. Although I know Dict[i-1] is stupid because i is a string, "2020-03-27" and etc, and not going to work, but is there a way how something like this can be done??

for i in Dict:
   if (float(Dict[i]["Price"])) > (float(Dict[i-1]["Price"]))): 
       print("Higher price than previous day")

The best I can come up to get around this with my limited knowledge in python is as below. But, I don`t like the fact that I have to make a temporary variable to compare with the price value running in loop...

previous = 9999999999
for i in Dict:
if (float(previous) < float(Dict[i]["Price"])): 
    print("Higher price than previous day")
previous = float(Dict[i]["Price"])

Upvotes: 1

Views: 865

Answers (5)

Hemel
Hemel

Reputation: 88

I think that's pretty what you are looking for.
Here's my piece of code and it is intuitive. Here we may make use of Dict.keys() and we may later transform it as a list storing all the keys that can be referenced using any int variable like you tried to use. Later we put a try except block to catch any IndexError that will occur once when we reach at the and of the Dict

Dict = { 
  "2020-03-27": {"Price": "483.4200", "Volume": "14377408"},
  "2020-03-30": {"Price": "543.3600", "Volume": "14377408"},
  "2020-04-01": {"Price": "613.1600", "Volume": "14377408"},
  "2020-04-02": {"Price": "631.0900", "Volume": "14377408"}
}


for i in range(len(Dict)):
  prev_key = list(Dict.keys())[i]

  try:
    next_key = list(Dict.keys())[i+1]

    if float(Dict[next_key]['Price']) > float(Dict[prev_key]['Price']):
      print("Higher Price than Previousday")

  except:
    print("Reached at The end !")

Upvotes: 0

Trenton McKinney
Trenton McKinney

Reputation: 62413

Use pandas

  • Pandas was designed for this type of analysis
    • Many of the pandas methods are vectorized, which means they're considerably faster than iterating.
  • There are too many methods to go over in a single question
  • However, the data is now in a format where all the value are easily accessible
  • Use pandas.Series.shift to compare a value to a previous value
import pandas as pd

# the data
my_dict = {"2020-03-27": {"Price": "483.4200", "Volume": "14377408"},
           "2020-03-30": {"Price": "543.3600", "Volume": "14377408"},
           "2020-04-01": {"Price": "613.1600", "Volume": "14377408"},
           "2020-04-02": {"Price": "631.0900", "Volume": "14377408"}}

# read it into pandas
df = pd.DataFrame.from_dict(my_dict, orient='index')

# display(df)
               Price    Volume
2020-03-27  483.4200  14377408
2020-03-30  543.3600  14377408
2020-04-01  613.1600  14377408
2020-04-02  631.0900  14377408

# check if a value is greater than the previous value
df['greater_previous_value'] = df.Price > df.Price.shift()

# display(df)
               Price    Volume  greater_previous_value
2020-03-27  483.4200  14377408                   False
2020-03-30  543.3600  14377408                    True
2020-04-01  613.1600  14377408                    True
2020-04-02  631.0900  14377408                    True

Upvotes: 2

Albert Alberto
Albert Alberto

Reputation: 950

This is the best I can offer for you. Sorry for not commenting much on my code. Hope you will understand.

my_dict = {
    "2020-03-27": {"Price": "483.4200", "Volume": "14377408"},
    "2020-03-30": {"Price": "543.3600", "Volume": "14377408"},
    "2020-04-01": {"Price": "613.1600", "Volume": "14377408"},
    "2020-04-02": {"Price": "631.0900", "Volume": "14377408"}
}

sorted_lst = sorted(my_dict)  # sort the dates

prev_date = sorted_lst[0]
prev_price = my_dict[prev_date]["Price"]

i = 1  # start at index one since we have fetched values for index 0
while i < len(sorted_lst):
    result_string = "Prev Date: \t{}\n".format(prev_date)
    result_string += "Current Date: \t{}\n".format(sorted_lst[i])
    result_string += "Prev Price: \t{}\n".format(prev_price)
    result_string += "Current Price \t{}\n".format(my_dict[sorted_lst[i]]["Price"])
    comparison = ""
    if my_dict[sorted_lst[i]]["Price"] == prev_price:
        comparison = "Price same as previous price"
    elif my_dict[sorted_lst[i]]["Price"] > prev_price:
        comparison = "Price higher than the previous price"
    elif my_dict[sorted_lst[i]]["Price"] < prev_price:
        comparison = "Price lower than the previous price"
    result_string += "Comparison: \t{}\n".format(comparison)
    print(result_string)
    print("----------------------------------------------")
    prev_date = sorted_lst[i]
    prev_price = my_dict[sorted_lst[i]]["Price"]
    i += 1

Upvotes: 0

Daniser
Daniser

Reputation: 162

Using pandas (as Trenton suggested) is a good idea.

But if you don't want to use pandas, you can use python's OrderedDict to maintain the order of keys (by the order they were inserted into the dictionary): https://docs.python.org/3/library/collections.html#collections.OrderedDict

Example code:

import collections

Dict  = collections.OrderedDict()

Dict["2020-03-27"] = {"Price": "483.4200", "Volume": "14377408"}
Dict["2020-03-30"] = {"Price": "543.3600", "Volume": "14377408"}
Dict["2020-04-01"] = {"Price": "613.1600", "Volume": "14377408"}
Dict["2020-04-02"] = {"Price": "631.0900", "Volume": "14377408"}

Upvotes: 0

sushanth
sushanth

Reputation: 8302

Here is a way,

dict_ = {
  "2020-03-27": {"Price": "483.4200", "Volume": "14377408"},
  "2020-03-30": {"Price": "543.3600", "Volume": "14377408"},
  "2020-04-01": {"Price": "613.1600", "Volume": "14377408"},
  "2020-04-02": {"Price": "631.0900", "Volume": "14377408"}
}

prev_date = ""

for k,v in enumerate(dict_):
    # 0, 2020-03-27
    # 1, 2020-03-30
    # ...
    if k == 0:
        prev_date = v
        continue
    
    # dict_['2020-03-30']['Price'] > dict['2020-03-27']["Price"]
    # dict_['2020-03-01']['Price'] > dict['2020-03-30']["Price"]
    # ...
    if dict_[v]['Price'] > dict_[prev_date]['Price']:
        print("Higher price than previous day")

    # update previous date.
    prev_date = v

Upvotes: 0

Related Questions