BCR
BCR

Reputation: 982

numpy loadtxt function throws a syntax error using converters and mdates

I've been following a tutorial for plotting stock charts and have encountered a syntax error that has me stumped. My configuration is Windows XP, Python 2.7 Anaconda distribution.

My text file looks like this with no headers: date, close, high, low, open, volume:

20130128,449.8300,453.2100,435.8600,437.8300,28054200 20130129,458.2700,460.2000,452.1200,458.5000,20398500 20130130,456.8300,462.6000,454.5000,457.0000,14898400 20130131,455.4900,459.2800,454.9800,456.9800,11404800 20130201,453.6200,459.4800,448.3500,459.1100,19267300 20130204,442.3200,455.9400,442.0000,453.9100,17039900

Here is the code:

import time
import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.dates as mdates

eachStock = 'TSLA','AAPL'

def graphData(stock):
    try:
        stockFile = stock+'.txt'

        date, closep, highp, lowp, openp, volume = np.loadtxt(stockFile, delimiter=",", unpack=True, converters=(0: mdates.strpdate2num('%Y%m%d')))

        fig = plt.figure()
        ax1 = plt.subplot(1,1,1)
        ax1.plot(date, openp)
        ax1.plot(date, highp)
        ax1.plot(date, lowp)
        ax1.plot(date, closep)

        plt.show()

    except Exception, e:
        print 'failed main loop',str(e)


for stock in eachStock:
    graphData(stock)
    time.sleep(300)

I keep getting the following error:

date, closep, highp, lowp, openp, volume = np.loadtxt(stockFile, delimiter=",", unpack=True, converters=(0: mdates.strpdate2num('%Y%m%d')))
                                                                                                              ^
SyntaxError: invalid syntax

I'm stumped as I believe I have copied a code function that works for others but for some reason is throwing an error for me. Thanks for your help!

Upvotes: 1

Views: 1312

Answers (1)

hpaulj
hpaulj

Reputation: 231385

Instead of

 (0: mdates.strpdate2num('%Y%m%d'))

try

 {0: mdates.strpdate2num('%Y%m%d')}

That should at least remove the syntax error. {:} are all part of a dictionary definition.

Upvotes: 1

Related Questions