使用csv文件制作以日期为键的股票价格字典

Using a csv file to make a dictionary of stock prices with date as the key

python 股票程序,使用 csv

您可以使用 Pandas 更快地完成此操作。

import pandas as pd

df = pd.read_csv('apple.dat') #read CSV file into a dataframe df
perfect_dict = list(df.T.to_dict().values())
print (perfect_dict) 

注意 - 您名为 perfect_dict 的变量实际上是一个字典对象列表。

输出:

[{'Date': '2020-04-27', 'Open': 70.449997, 'High': 71.135002, 'Low': 69.987503, 'Close': 70.792503, 'Adj Close': 70.247971, 'Volume': 117087600}, {'Date': '2020-04-28', 'Open': 71.269997, 'High': 71.457497, 'Low': 69.550003, 'Close': 69.644997, 'Adj Close': 69.109299, 'Volume': 112004800}, {'Date': '2020-04-29', 'Open': 71.182503, 'High': 72.417503, 'Low': 70.972504, 'Close': 71.932503, 'Adj Close': 71.379196, 'Volume': 137280800}]

还有很多方法,这里只列出两种。

数据设置

# Test Data , sorry did not had csv, so this is starting point
my_csv_data=[{'Date': '2020-01-02', 'Open': '74.059998', 'High': '75.150002', 'Low': '73.797501', 'Close': '75.087502', 'Adj Close': '74.333511', 'Volume': '135480400'},
          {'Date': '2020-01-03', 'Open': '75.059998', 'High': '75.150002', 'Low': '73.797501', 'Close': '75.087502', 'Adj Close': '74.333511', 'Volume': '135480400'},
          {'Date': '2020-01-04', 'Open': '76.059998', 'High': '75.150002', 'Low': '73.797501', 'Close': '75.087502', 'Adj Close': '74.333511', 'Volume': '135480400'}]

查询日期需要查询的日期

input_date='2020-01-04' # date the system received for query (1)
# 1st option
for each in my_csv_data:
    if each['Date'] == input_date: # find record matching with the query date
        for each_key in each:
            print(f"{each_key}:{each[each_key]}")

输出:

Date:2020-01-04
Open:76.059998
High:75.150002
Low:73.797501
Close:75.087502
Adj Close:74.333511
Volume:135480400

第二个选项,使用 pandas。

# 2nd option
import pandas as pd
df=pd.DataFrame(my_csv_data)
df_result=df[df["Date"] == input_date] # find the record for the query date
for each in df_result:
    print(each,(df_result[each].tolist()[0])) # loop and reformat for printing

输出:

Date 2020-01-04
Open 76.059998
High 75.150002
Low 73.797501
Close 75.087502
Adj Close 74.333511
Volume 135480400