1.5 KiB
1.5 KiB
Exercise 8.3 - Solution
# coticker.py
from structure import Structure
from validate import String, Integer, Float
class Ticker(Structure):
= String()
name = Float()
price = String()
date = String()
time = Float()
change open = Float()
= Float()
high = Float()
low = Integer()
volume
from cofollow import consumer, follow
from tableformat import create_formatter
import csv
# Coroutine that splits rows using the CSV module. This is rather
# mind-bending due to the fact that the csv module only understands
# iteration with the for-loop. To make it work, we wrap it around
# a generator that simply produces the last item received.
@consumer
def to_csv(target):
def producer():
while True:
yield line
= csv.reader(producer())
reader while True:
= yield
line next(reader))
target.send(
@consumer
def create_ticker(target):
while True:
= yield
row
target.send(Ticker.from_row(row))
@consumer
def negchange(target):
while True:
= yield
record if record.change < 0:
target.send(record)
@consumer
def ticker(fmt, fields):
= create_formatter(fmt)
formatter
formatter.headings(fields)while True:
= yield
rec = [getattr(rec, name) for name in fields]
row
formatter.row(row)
if __name__ == '__main__':
'Data/stocklog.csv',
follow(
to_csv(
create_ticker(
negchange('text', ['name','price','change']))))) ticker(