如何使用JSON数据中的python来比较昨天和今天的change_data?

时间:2020-04-03 03:40:10

标签: python json

我有以下代码,但不知道如何为change_data编写公式,因此我将其包含在下面的引号中。

import json

with open('data.kospi', 'r') as f:
        data = json.load(f)

loaded_data = data
time_series_data = loaded_data["Time Series (Daily)"]
temp = "^KS11"
for date, date_data in time_series_data.items():
    formatted_date = date.replace("-","")
    low_data = date_data["3. low"]
    change_data = "change_date = 2020-04-02.close data- 2020-04-01.close data"
    open_data = date_data["1. open"]
    high_data = date_data["2. high"]
    close_data = date_data["4. close"]
    print("{}|{}|{}|{}|{}|{}|{}".format(temp.ljust(10), formatted_date, low_data.ljust(12), change_data.ljust(12), open_data.ljust(12), high_data.ljust(12), close_data.ljust(12)))

1 个答案:

答案 0 :(得分:0)

from dateutil.parser import parse
import pandas as pd
import json

with open ('data.kospi') as f:
        data = json.load(f)


time_series_data = data["Time Series (Daily)"]
temp = "^KS11"


for date, date_data in time_series_data.items():
    formatted_date = date.replace("-","")
    low_data = date_data["3. low"]
    open_data = date_data["1. open"]
    high_data = date_data["2. high"]
    close_data = date_data["4. close"]
    ydate = datetime.strptime(date, '%Y-%m-%d').date() - timedelta(days=1)
    sydate = str(ydate)
    yclose = data['Time Series (Daily)'][sydate]['4. close']
    change_data = float(close_data) - float(yclose)
    cchange = str(change_data)
    data2 = "{}|{}|{}|{}|{}|{}|{}|".format(temp.ljust(10), formatted_date, low_data.ljust(12), cchange.ljust(12), open_data.ljust(12), high_data.ljust(12), close_data.ljust(12))
    print(data2)

此代码有效。