使用csv文件制作一个以日期为关键字的股价词典



基本上,我使用的是一个csv文件,里面有我从雅虎金融获得的苹果的每日股价。我让用户输入一个文件名,并使用它来浏览和打印股票价格。我的第一个功能有问题

示例输出

[{'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': '74.287498', 'High': '75.144997', 'Low': '74.125000', 'Close': '74.357498', 'Adj Close': '73.610840', 'Volume': '146322800'}... ]

代码尝试:

import csv
def createdict(file_name):
perfect_dict=[]
with open('apple.dat') as f:
file_name = list(csv.file_name(f))

for row in file_name[1:]:
temp_dict = {}
temp_dict["Date"] = row[0]
temp_dict["Open"] = row[1]
temp_dict["High"] = row[2]
temp_dict["Low"] = row[3]
temp_dict["Close"] = row[4]
temp_dict["Adj Close"] =row[5]
temp_dict["Volume"] = row[6]
perfect_dict.append(temp_dict)
return perfect_dict
def main():
print("Welcome to the Stock Price Program")
print()
file_name=input("Enter the data file name: ")
main()

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

数据设置

# 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

第二种选择,使用熊猫。

# 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

使用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的变量实际上是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}]

相关内容

最新更新