There is no need to pre-create a list, you could use list.append()
instead. This also avoids having to keep a counter to index into Dates
.
I'd use a list comprehension here, looping directly over the cursor to fetch rows:
cursor.execute(date_query, [Code])
Dates = [datetime.strptime(r[0], "%Y-%m-%d") for r in cursor]
You may want to add .date()
to the datetime.strptime()
result to get datetime.date
objects instead.
Iterating over the cursor is preferable as it avoids loading all rows as a list into memory, only to replace that list with another, processed list of dates. See the cursor.fetchall()
documentation:
Since this reads all rows into memory, it should not be used if there are a lot of rows. Consider iterating over the rows instead.
To produce your numpy.array
, don't prepopulate. Instead use numpy.asarray()
to turn the cursor items into an array, with the help of a generator:
dtype=[('TradeDate', datetime), ('Expiry', datetime),
('Moneyness', float), ('Volatility', float)]
dt = lambda v: datetime.strptime(v, "%Y-%m-%d")
filtered_rows = ((dt(r[0]), dt(r[1]) + r[2:]) for r in cursor)
all_values = np.asarray(filtered_rows, dtype=dtype)
For future reference, you can use enumerate()
to produce a counter with a loop:
for r, row in enumerate(rows):
# r starts at 0 and counts along