Python Forum

Full Version: Beginner trying to run simple code
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
headline ... How do i run this code

I read the thread
[Basic] How to execute python code

although helpful.. im still not sure how i run this?

I have python 2.7 installed and here is the script
import sys
import operator

if (len(sys.argv) == 3):
    inputFileName = sys.argv[1]
    outputFolder = sys.argv[2]
    
    # open symbols file
    tradelogFile = open(inputFileName,"rU")

    month_names = {'JAN':1,'FEB':2,'MAR':3,'APR':4,'MAY':5,'JUN':6,'JUL':7,'AUG':8,'SEP':9,'OCT':10,'NOV':11,'DEC':12}
    expiry_dict = {}

    # for each line in the log file
    for line in tradelogFile:
        # remove the line terminator if any
        line = line.rstrip('\n')

        tokens = line.split('|')
        if tokens[0] == 'OPT_TRD':
            transaction_id = tokens[1]
            
            subtokens = tokens[3].split(' ')
            underlying = subtokens[0]

            expiry = subtokens[1]
            # Reformat date for sorting expiry_key
            year = expiry[5:7]
            full_year = '20' + year
            month = expiry[2:5]
            month_num =  str(month_names[expiry[2:5]]).zfill(2)
            day = expiry[0:2]
            key_expiry = full_year + month_num + day

            strike = int(float(subtokens[2]))
            
            if subtokens[3] == 'P':
                callPut = 'PUT'
            else:
                callPut = 'CALL'
            
            openClose = tokens[6]
            transDate = tokens[7]
            transTime = tokens[8]
            lots = int(float(tokens[10]))
            contract_size = int(float(tokens[11]))
            fillPrice = tokens[12]
            proceeds = tokens[13]
            commission = tokens[14]
            #print underlying,expiry,strike,callPut,openClose,transDate,transTime,lots,fillPrice,proceeds,commission
            
            # Trades are grouped by a combination of underlying symbol and expiration date.
            expiry_key = key_expiry + '_' + underlying
            
            record = ''
            if lots > 0:
                record = record + 'BUY '
            else:
                record = record + 'SELL '
                
            record = record + str(lots) + ' ' + underlying + ' ' + str(contract_size) + ' ' + day + ' ' + month + ' ' + year + ' ' + str(strike) + ' ' + callPut + \
                     ' @' + fillPrice + ' LMT FIXED'
                     
            # If this expiry entry isn't in the map yet then create it as a blank map
            if expiry_key not in expiry_dict:
                expiry_dict[expiry_key] = {}

            # transaction key needs to be unique and date/time is insufficient so append transaction_id
            # transaction_id is sequential in time *except* for expired options which have their own separate starting point
            transactionTimestamp = transDate + transTime + transaction_id
            expiry_dict[expiry_key][transactionTimestamp] = record

    for key1,value1 in expiry_dict.iteritems():
        outFileName = outputFolder + "/" + key1 + ".txt"
        outputFile = open(outFileName,"w")
        sortedRecords = sorted(value1.items(), key=operator.itemgetter(0), reverse=False)
        for trade in sortedRecords:
            outputFile.write(trade[1] + '\r')
        outputFile.close()
        
    tradelogFile.close()
else:
    print "wrong number of aruments"
    print "example:"
    print "python tradelog-analyzer.py input_file.txt output_folder"
I have some instructions from the creator but i don't want to be rude and pester the guy...

I have opened the terminal and tried "python ibtos.py tradelog.txt tostrades"

I have tried renameing the files to the names in the script..


Im sorry if this is painfully obvious of what i should do....

I am planning on learning Python but obviously i havent gotten there yet....

Thanks for any help in advance
this script expects 2 arguments - input_file and output_folder
if you run it like this
python ibtos.py tradelog.txt tostrades
it should work as long as the script name is ibtos.py (according to last line it is tradelog-analyzer.py) and file tredelog.txt is in the same folder as the script and there is subfolder tostrades
the author should of used the argparse module to handle arguments. Especially if the file requires arguments to even work. In that way you could of just done
python ibtos.py -h
to get the help doc for arguments, what arguments are possible, and detailed info regarding all arguments.

Quote:I have tried renameing the files to the names in the script..
This is not required. In fact you can possibly break it by renaming it something the file is importing, such as "operator" if its a python file.

What is the error you are getting or the unexpected results you are having? I cant run it as i dont have the required files it loads.
On the items you have tried (you may have to re-try), please include all error output.
Your number of arguments is correct (program looks for three, 1st one is always the program name)
The order is input file name, output file name
You could place print statements in various strategic locations to see if data looks appropriate,
for example:
  • After line 15 add
    print('line: {}'.format(line))
  • After line number 19
    print('tokens: {}'.format(tokens))
  • etc.
Copy all penitent data (only small sample of large data, please) and report your findings.
Error:
Nothing to do with the post for you information...
This reminds me of the good old days years ago when someone posts and within 10 minutes there are a few responses that overlap each other.
Yea, old people are slow! I was last!
Wonder what I'll be like while coding in my 90's??
WOW... so much help!!! thanks guys

Josephs-Mac-Pro:~ Joseph$ python ibtosconvert.py IBtrades.txt TOSimports
/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python: can't open file 'ibtosconver.py': [Errno 2] No such file or directory
Josephs-Mac-Pro:~ Joseph$ 
Here is the error