AdityaSriram

stock.py

Jan 27th, 2013
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.68 KB | None | 0 0
  1. #-------------------------------------------------------------------------------
  2. # Name:        Stock Watch
  3. # Purpose:     Helps monitoring stocks/equities in  BSE.
  4. #              Currently it employs CUI, but updates can be expected.
  5. #              Currently it only allows one profile, but it can be easily
  6. #              extended.
  7. #
  8. # Version:     1.0
  9. #
  10. # Author:      ADMIN
  11. #
  12. # Created:     25/01/2013
  13. # Copyright:   (c) ADMIN 2013
  14. # Licence:     <your licence>
  15. #-------------------------------------------------------------------------------
  16. #!/usr/bin/env python
  17.  
  18. #-------------------------------------------------------------------------------
  19.  
  20. from bs4 import BeautifulSoup
  21. from urllib2 import urlopen
  22. import os, re, pickle, csv, copy, sys, time
  23.  
  24. #-------------------------------------------------------------------------------
  25.  
  26. __version__ = '1.0'
  27. root = os.getcwd()
  28. codes = []
  29. baseUrl = "http://in.finance.yahoo.com/q?s={}.BO"
  30. attributes = ['Code','Name','Scrip Name','Price', 'Change', 'Percentage change']
  31. record = dict(zip(attributes,[None]*6))
  32. outFile = root +  r"\out.csv"
  33. profile = root + r"\default.pro"
  34.  
  35. #-------------------------------------------------------------------------------
  36.  
  37. def updateProfile():
  38.     with open(profile, 'w') as f:
  39.         pickle.dump(codes, f)
  40.  
  41. def addToCodes(element):
  42.     if not element in codes:
  43.         codes.append(element)
  44.         codes.sort()
  45.     updateProfile()
  46.  
  47. def removeFromCodes(element):
  48.     if element in codes:
  49.         codes.remove(element)
  50.     updateProfile()
  51.  
  52. #-------------------------------------------------------------------------------
  53.  
  54. def display():
  55.     f = open(outFile, 'w')
  56.     writer = csv.DictWriter(f, ['Code','Name','Scrip Name','Price', 'Change', 'Percentage change'])
  57.     writer.writeheader()
  58.     for code in codes:
  59.         try:
  60.             stock = BeautifulSoup(urlopen(baseUrl.format(code)))
  61.         except URLError:
  62.             print "Failed to retrieve any data from the servers, \nplese check \
  63.                   your Internet connection and try again"
  64.             break
  65.         print "Processing code {}".format(code)
  66.         record['Code'] = code
  67.         t = str(stock.find('div', {'class':'title'}).text).replace('-BSE','')
  68.         record['Name'] = t[:t.find(' (')]
  69.         record['Scrip Name'] = t[t.find(' (')+2:t.find(')')].replace('.BO','')
  70.         record['Price'] = str(stock.find('span', {'class':'time_rtq_ticker'}).text)
  71.         t = str(stock.find('span', {'class':'time_rtq_content'}).text)
  72.         e = re.search(r'(\d*\.?\d+)\((\d*\.?\d+%)\)', t)
  73.         record['Change'] = e.group(1)
  74.         record['Percentage change'] = e.group(2)
  75.         writer.writerow(record)
  76.     f.close()
  77.     print "\nPlease wait while your Excel file is being opened"
  78.     print "Thank You for using Stock Watch"
  79.     time.sleep(2)
  80.     os.startfile(outFile)
  81.     sys.exit()
  82.  
  83. #-------------------------------------------------------------------------------
  84.  
  85. def main():
  86.     choice = ""
  87.     while choice != 5:
  88.         choice = input("""What do you want to do
  89. Display current rates (1)
  90. Add to existing stocks (2)
  91. Remove from existing stocks (3)
  92. Show existing stocks (4)
  93. Leave the program(5)\n--> """)
  94.         if choice == 1:
  95.             display()
  96.         elif choice == 2:
  97.             addToCodes(input("\nEnter stock Code you want to add: "))
  98.         elif choice == 3:
  99.             removeFromCodes(input("\nEnter stock Code you want to remove: "))
  100.         elif choice == 4:
  101.             print '\n', codes
  102.         else:
  103.             print "\n\n\nThank You for using Stock Watch v{}.".format(__version__)
  104.  
  105. with open(profile) as f:
  106.     codes = pickle.load(f)
  107.  
  108. if __name__ == '__main__':
  109.     main()
Advertisement
Add Comment
Please, Sign In to add comment