creat stock data from cvs file, list, dictionary

1.7k Views Asked by At

My stock programs input is as follow

'Sqin.txt' data read in and is a cvs file

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

The output is

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

dat1[0] is the stock symbol 'ACC' used for lookup and data updates Dat1[1....?] Is the EOD (end of day) data At the close of stock markets the EOD data will be inserted at dat1.insert (1,M) each update cycle . Guys you can code this out in probably one line. Mine so far is over 30 lines, so seeing my code isn't relevant. Above is an example of some simple input and the desired output.

If you decide to take on some real world programing please keep it verbose. Declare your variables, then populate it, and finally use them ex.

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

Maybe it would be OK to be some what pythonic and a little less verbose.

1

There are 1 best solutions below

2
On

You should use a dictionary with the names as keys:

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)

To add data you do data[name].insert(0, new_data). Where name could be AAC and value is a list of the data. This places the new data at the beginning of the list like you said in your post.

I would recommend append instead of insert, it is faster. If you really want the data added to the begin of the list use collections.deque instead of list.