Reputation: 97
This correctly gets live quotes from Interactive Brokers using ib_sync and can print them onto a Jupter platform:
from ib_insync import *
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 correctly opens a CSV file and writes text within it:
with open('stocks-test.csv','w',newline='') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',')
spamwriter.writerow(['stock','price','datetime'])
f = open('stocks-test.csv','w')
f.write('hi there\n') #Give your csv text here.
How do I combine the two together?
So far I have:
import csv
with open('stocks-test.csv','w',newline='') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',')
spamwriter.writerow(['stock','price','datetime'])
spamwriter.writerow(time.strftime("%Y-%m-%d %H:%M") )
#file closed
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:
f.write(stock.last)
f.write('hi there\n') #Give your csv text here.
f.close()
For some reason the f.write has trouble reading a list?
Upvotes: 0
Views: 269
Reputation: 44888
f
is opened in 'w'
mode, which means that one can only write str
ings to it. Apparently, stock.last
is not a string, so it can't be written to the file directly. You should convert it to a string somehow, probably with str(stock.last)
.
Upvotes: 1
Reputation: 134
In your combined version you never declare f. Insert the
f = open('stocks-test.csv','w')
before your for loops
Upvotes: 1