-1

This code correctly prints all four live stock quotes from Interactive Brokers using ib_insync. Stock is an imported function within ib_insync.

stocks = ['SPY','ANGL','GDX','TMV']

test = list()
for stock in stocks:
    stock = Stock(stock, 'SMART','USD')
    contract = ib.qualifyContracts(stock)
    test.append(ib.reqMktData(contract[0],snapshot=True))
    ib.sleep(1)
for stock in test:
    print(stock.last)

This code below will only print the last quote in the list, in this case TMV. I believe this is because the 'w' is overwriting the entire file every time the loop is run? Or is the loop not setup correctly.

import csv
from ib_insync import *
stocks = ['SPY','ANGL','GDX','TMV']

stocks = ['SPY', 'TVIX']
while True:
test = list()

    for stock in stocks:
        stock = Stock(stock, 'SMART','USD')
        contract = ib.qualifyContracts(stock)
        test.append(ib.reqMktData(contract[0],snapshot=True))
        ib.sleep(15)

    for stock in test:
        f = open('spy-price.csv','w')
        f.write(str(stock.last))
        f.close()

How would I get the quotes to be setup so all four quotes are in the same file?

John Smith
  • 97
  • 8
  • 1
    Possible duplicate of [How do you append to a file in Python?](https://stackoverflow.com/questions/4706499/how-do-you-append-to-a-file-in-python) – MrPromethee Jun 17 '19 at 14:23
  • Hopefully someone can verify my loop is setup correctly as I have heard I may have to increment this instead of using the for stock in stocks. But yeah I will try using 'a' and 'ab' instead of 'w'. – John Smith Jun 17 '19 at 14:27
  • The simplest way is to open the file only once and close it after you're done. – molbdnilo Jun 17 '19 at 14:27
  • And use the [open statement](https://www.pythonforbeginners.com/files/with-statement-in-python) – olinox14 Jun 17 '19 at 14:29
  • @molbdnilo You are probably right. I am assuming I have to move f = open('stocks.csv','w') to above the while True – John Smith Jun 17 '19 at 14:30

1 Answers1

0

use f = open('spy-price.csv','w+') to append to file w = write w+ = append