从CSV文件、列表和字典创建股票数据

0 投票
1 回答
1760 浏览
提问于 2025-04-17 11:18

我的股票程序的输入如下:

读取名为'Sqin.txt'的数据,这是一份CSV文件。

AAC,D,20111207,9.83,9.83,9.83,9.83,100
AACC,D,20111207,3.46,3.47,3.4,3.4,13400
AACOW,D,20111207,0.3,0.3,0.3,0.3,500
AAME,D,20111207,1.99,1.99,1.95,1.99,8600
AAON,D,20111207,21.62,21.9,21.32,21.49,93200
AAPL,D,20111207,389.93,390.94,386.76,389.09,10892800
AATI,D,20111207,5.75,5.75,5.73,5.75,797900

输出结果是:

 dat1[]
['AAC', ['9.83', '9.83', '9.83', '9.83', '100'], ['9.83', '9.83', '9.83', '9.83', '100']]

dat1[0]是股票代码'ACC',用于查找和更新数据。
dat1[1....?]是收盘时的数据。
在股市收盘时,收盘数据会在每次更新循环中插入到dat1.insert(1,M)的位置。
大家可以把这个代码写成一行,我的代码目前已经超过30行,所以不需要看我的代码。上面是一些简单输入和期望输出的例子。

如果你决定进行一些实际的编程,请保持代码清晰易懂。先声明你的变量,然后给它们赋值,最后使用它们,比如:

M = []
M = q [0][3:]  ## had to do it this way because 'ACC' made the variable M [] begin as a string (inmutable).  So I could not add M to the data.-dat1[]- because -dat1[]- also became a string (inmutable strings how stupid). Had to force 'ACC' to be a list so I can create a list of lists -dat1-

Dat1.insert(1.M)  ## -M- is used to add another list to the master.dat record

也许可以稍微简化一下,让代码看起来更像Python风格,而不是那么啰嗦。

1 个回答

0

你应该用字典来存储名字,名字作为键:

import csv
import collections

filename = 'csv.txt'

with open(filename) as file_:
    reader = csv.reader(file_)
    data = collections.defaultdict(list)
    for line in reader:
        # line[1] contains "D" and line[2] is the date
        key, value = line[0], line[3:]
        data[key].append(value)

要添加数据,你可以用 data[name].insert(0, new_data)。这里的名字可以是 AAC,而对应的值是一个数据列表。这样做会把新数据放到列表的最前面,就像你在帖子里说的那样。

我建议用 append 方法,而不是 insert,因为 append 更快。如果你真的想把数据加到列表的开头,可以用 collections.deque,而不是普通的 list

撰写回答