1

我目前正在尝试创建自己的股票交易代码。使用嵌套字典

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"}
}

使用上面的字典,我试图找到一种方法来比较每个以前的“价格”值,然后从那里继续。我想到的东西就像下面的一样。虽然我知道 Dict[i-1] 是愚蠢的,因为 i 是一个字符串,“2020-03-27”等等,并且不会工作,但是有没有办法做到这样的事情?

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

以我对python的有限知识,我能想到的最好的解决方法如下。但是,我不喜欢我必须制作一个临时变量来与循环运行的价格值进行比较的事实......

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

5 回答 5

2

使用熊猫

  • Pandas 专为此类分析而设计
    • 许多 pandas 方法都是矢量化的,这意味着它们比迭代要快得多。
  • 一个问题有太多方法可以解决
  • 但是,数据现在采用了所有值都可以轻松访问的格式
  • 用于pandas.Series.shift将一个值与前一个值进行比较
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
于 2020-07-26T06:12:12.163 回答
0

我认为这就是你要找的东西。
这是我的一段代码,它很直观。在这里我们可以使用,Dict.keys()稍后我们可以将其转换为list存储所有可以使用任何int变量引用的键,就像您尝试使用的那样。稍后我们放置一个try except块来捕获任何IndexError当我们到达 and 时会发生的情况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 !")
于 2020-07-26T06:40:54.153 回答
0

这里有一个方法,

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

于 2020-07-26T06:14:25.247 回答
0

使用 pandas(正如 Trenton 建议的那样)是一个好主意。

但是如果你不想使用 pandas,你可以使用 python 的 OrderedDict 来维护键的顺序(按它们插入字典的顺序): https://docs.python.org/3/library/collections。 html#collections.OrderedDict

示例代码:

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"}
于 2020-07-26T06:22:09.920 回答
0

这是我能为你提供的最好的。很抱歉没有对我的代码发表太多评论。希望你能理解。

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
于 2020-07-26T06:47:49.377 回答