How to structure my code?

This is the place for queries that don't fit in any of the other categories.

How to structure my code?

Postby runawaykinms » Tue Dec 24, 2013 11:25 pm

I am new to programming and at times most of my struggle comes from how to best organize my code. Should I use functions, classes, etc. I was hoping to get some guidance with my current project.

What I am trying to do: I am trying to write a module that collects stock symbols from the internet and stores them as csv files on my computer so I can access them later with another program. Here is how I was structuring my file thus far:

Code: Select all
import urllib
import csv

def get_symbols(index):
    if index == 'nyse' or 'NYSE' or 'Nyse':
        return urllib.urlretrieve('link to download stock symbols', 'file path of where to save file')
    if inded == 'snp500' or 'SNP500':
        return urllib.urlretrieve('link to download stock symbols','file path of where to save file')


That seems messy and with lots and lots of 'list of stocks' it could get really long. I then thought about having a function for each list. For example:

Code: Select all
import urllib
import csv

def get_nyse():
    return urllib.urlretrieve('link to download stock symbols', 'file path of where to save file')

def get_snp500():
    return urllib.urlretrieve('link to download stock symbols', 'file path of where to save file')


Finally, I thought about using a class but I am not really comfortable with that and unsure how it would look.

In the end I would like to run get_symbols('nyse') or get_symbols('all') and have it return the requested symbols to the requested file paths. Am I on the right track? What would be the best, and most efficient way to structure this problem?
Last edited by Mekire on Wed Dec 25, 2013 2:30 am, edited 1 time in total.
Reason: First post lock.
runawaykinms
 
Posts: 7
Joined: Tue Dec 24, 2013 9:57 am

Re: How to structure my code?

Postby stranac » Wed Dec 25, 2013 3:37 pm

I would just use a dict. Something like this should work:
Code: Select all
SYMBOL_DATA = {'nyse': ('nyse link', 'nyse filename'),
               'snp500': ('snp500 link', 'snp500 filename'),
               # ...
              }

def get_symbols(name):
    link, filename = SYMBOL_DATA[name.lower()]
    # ...
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1242
Joined: Thu Feb 07, 2013 3:42 pm

Re: How to structure my code?

Postby runawaykinms » Wed Dec 25, 2013 8:55 pm

stranac,

That actually looks like it would help organize them all in one place. Thanks! The more I learn to program the more I am amazed by how many different ways things can be done.
runawaykinms
 
Posts: 7
Joined: Tue Dec 24, 2013 9:57 am


Return to General Coding Help

Who is online

Users browsing this forum: No registered users and 2 guests