Python Forum
Beginner trying to run simple code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Beginner trying to run simple code
#1
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
Reply
#2
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
Reply
#3
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.
Recommended Tutorials:
Reply
#4
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.
Reply
#5
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.
Recommended Tutorials:
Reply
#6
Yea, old people are slow! I was last!
Wonder what I'll be like while coding in my 90's??
Reply
#7
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with simple code JacobSkinner 1 227 Mar-18-2024, 08:08 PM
Last Post: deanhystad
  I have a code which is very simple but still I cannot detect what's wrong with it max22 1 440 Nov-07-2023, 04:32 PM
Last Post: snippsat
  Beginner: Code not work when longer list raiviscoding 2 765 May-19-2023, 11:19 AM
Last Post: deanhystad
  help me simple code result min and max number abrahimusmaximus 2 870 Nov-12-2022, 07:52 AM
Last Post: buran
  A simple "If...Else" question from a beginner Serena2022 6 1,638 Jul-11-2022, 05:59 AM
Last Post: Serena2022
  Simple encoding code ebolisa 3 1,400 Jun-18-2022, 10:59 AM
Last Post: deanhystad
  How would you (as an python expert) make this code more efficient/simple coder_sw99 3 1,751 Feb-21-2022, 10:52 AM
Last Post: Gribouillis
  Simple code question about lambda and tuples JasPyt 7 3,238 Oct-04-2021, 05:18 PM
Last Post: snippsat
  My simple code don't works !! Nabi666 1 1,576 Sep-06-2021, 12:10 PM
Last Post: jefsummers
Sad SyntaxError: from simple python example file from mind-monitor code (muse 2) warmcupoftea 4 2,750 Jul-16-2021, 02:51 PM
Last Post: warmcupoftea

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020