0

I am attempting to write both the symbol name, and the last price of the stock(which the code gets from an API) into a csv file. When I simply print out both the name and price into the command line, it works just fine. But when I tried writing these into two different columns in a csv, the symbols worked, but the code only printed the price of the last stock into the file (there should be the same number of prices as the number of symbols ~100). I don't know if this is an error in the csv writer part, or somewhere else. Thank you for any help you can give!

data_sheet1 = pd.read_excel('C:\\Users\\sss\\Downloads\\Book1.xlsx')
data_impor = data_sheet1['DDD'].tolist()

def get_ohlc(**kwargs):
    data = get_quotes(symbol=kwargs.get('symbol'))
    for symbol in kwargs.get('symbol'):
        global lastPrice
        lastPrice = (data[symbol]['lastPrice'])


get_ohlc(symbol=data_impor)

#write csv

with open ("mycsv.csv", "w" , newline='' ) as f:
    thewriter = csv.writer(f)

    thewriter.writerow(['col1', 'col2'])
    thewriter.writerow([data_impor, lastPrice])

with open('mycsv.csv', 'r') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row)

What this gives:

{'col1': "['MMM', 'WBAI', 'WUBA', 'EGHT', 'AHC', 'AOS', 'ATEN', 'AIR', 'AAN', 'ABB', 'ABT', 'ABBV', 'ANF', 'AGD']", 'col2': '8.84'}

```
2

1 Answer 1

2

This error occurs because you keep reassigning lastPrice (and discarding previous values) in each iteration of the for-loop: lastPrice = (data[symbol]['lastPrice']). To keep all values you should save them to a list.

I've added some additional improvement suggestions also:

  1. Instead of making lastPrice a global variable, a better way would be to return it from the function.
  2. It's easier to pass input values to functions as positional arguments instead of keyword arguments.
  3. By the look of your output I believe the symbols isn't printed correct either. It looks like the first column in the second row contains the string "['MMM', 'WBAI', 'WUBA', 'EGHT', 'AHC', 'AOS', 'ATEN', 'AIR', 'AAN', 'ABB', 'ABT', 'ABBV', 'ANF', 'AGD']" and not each entry in a new row as I believe you wish. To avoid this we could either iterate through all rows and write one by one, or we could gather all the data in a list where each entry is a list representing a csv row and write it all with writerows(). I'm doing the latter here.
data_sheet1 = pd.read_excel('C:\\Users\\sss\\Downloads\\Book1.xlsx')
data_impor = data_sheet1['DDD'].tolist()

def get_ohlc(symbols): #no kwarg here, just positional argument
    data = get_quotes(symbols)
    symbols_and_lastPrices = [] #create empty list
    for symbol in symbols:
        symbols_and_lastPrices.append([symbol, data[symbol]['lastPrice']]) #append [symbol, lastPrice]-pairs to list.
    return symbols_and_lastPrices #return list


csv_data = get_ohlc(data_impor) #save returned list

#write csv

with open ("mycsv.csv", "w" , newline='' ) as f:
    thewriter = csv.writer(f)

    thewriter.writerow(['col1', 'col2'])
    thewriter.writerows(csv_data) #write all data rows at the same time

with open('mycsv.csv', 'r') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much but now Im getting the error; TypeError: get_quotes() takes 0 positional arguments but 1 was given
@n2001177 that's a mistake from my side, according to your code get_quotes() takes symbols as a keyword argument and not as a positional argument. so the call should look data = get_quotes(symbol=symbols).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.