Advertisement
retrocombine

stock-ta

Oct 28th, 2013
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.75 KB | None | 0 0
  1. # TA-Py
  2. # Perform Technical Analysis on a given set of Yahoo! Finance data.
  3.  
  4. import datetime
  5. import matplotlib.finance as fin
  6. import urllib2
  7. import matplotlib.pyplot as plt
  8. import talib
  9.  
  10. # Define "asking for a symbol" function.
  11.  
  12. def ask_symbol():
  13.     symbol = raw_input('Look up which symbol?\n>')
  14.     print '\nFetching data for ' + symbol + '...' + '\n'
  15.     return symbol
  16.  
  17. # Define "asking for a timeframe" function.
  18.  
  19. def ask_timeframe():
  20.     while True:
  21.         timeframe = raw_input('What timeframe? \n a: 1 Year \n b: 3 Months \n c: Daily \n>')
  22.         if timeframe == 'a':
  23.             past_date = datetime.date.today() - datetime.timedelta(days=365) # One year ago.
  24.             print '\nBeginning from ' + str(past_date) + '...\n'
  25.             return past_date
  26.         elif timeframe == 'b':
  27.             past_date = datetime.date.today() - datetime.timedelta(days=31*3) # One month ago.
  28.             print '\nBeginning from ' + str(past_date) + '...\n'
  29.             return past_date
  30.         elif timeframe == 'c':
  31.             # past_date = current_date - datetime.timedelta(days=1) # One day ago.
  32.             # return past_date
  33.             # break
  34.             print '\nYahoo doesn\'t have enough data for that. Try a different timeframe.\n'
  35.         else:
  36.             print '\nInvalid option!\n'
  37.  
  38.  
  39. # Define "getting the stock data" function.
  40.  
  41. def get_data(symbol, past_date):
  42.     while True:
  43.         try:
  44.             data = fin.quotes_historical_yahoo(symbol, (past_date.year, past_date.month, past_date.day), (datetime.date.today().year, datetime.date.today().month, datetime.date.today().day), asobject=None)
  45.             return data
  46.         except urllib2.HTTPError:
  47.             print 'Symbol not found!\n'
  48.             symbol = ask_symbol()
  49.  
  50.  
  51. # Define "process the raw data into closing price" function.
  52.  
  53. def process_data(data):
  54.     date = data[:,0]
  55.     close = data[:,2]
  56.     sma = talib.SMA(close)
  57.     rsi = talib.RSI(close)
  58.     macd = talib.MACD(close)
  59.     return (date, close, sma, rsi, macd)
  60.  
  61. # TODO: Define "determine if RSI is above 70 or below 30" function.
  62.  
  63. # TODO: Define "determine if MACD histogram is zero" function.
  64.  
  65. # Define "plot the stock data over time" function.
  66.  
  67. def plot_data(date, close, sma, rsi, macd):
  68.     plt.figure(1)
  69.  
  70.     plt.subplot(311)
  71.     plt.plot_date(x = date, y = close, fmt = 'r-')
  72.     plt.plot_date(x = date, y = sma, fmt = 'b-')
  73.     plt.ylabel("Closing price ($)")
  74.     plt.title("Stock price to date")
  75.  
  76.     plt.subplot(312)
  77.     plt.plot_date(x = date, y = rsi, fmt = 'g-')
  78.     plt.axhline(y=70, xmin=0, xmax=1)
  79.     plt.axhline(y=30, xmin=0, xmax=1)
  80.     plt.ylabel("Percent (%)")
  81.  
  82.     plt.subplot(313)
  83.     plt.plot_date(x = date, y = macd[0], fmt = 'k-')
  84.     plt.plot_date(x = date, y = macd[1], fmt = 'r-')
  85.     plt.axhline(y=0, xmin = 0, xmax = 1)
  86.     plt.fill_between(date, macd[0]-macd[1], 0, alpha=0.5, facecolor='darkslategrey', edgecolor = 'darkslategrey')
  87.  
  88.     plt.show()
  89.  
  90. def menu():
  91.     choice = raw_input("What would you like to do?\n\na: Lookup a symbol\nq: Quit\n\n>")
  92.     if choice == "a":
  93.         lookup()
  94.     elif choice == "q":
  95.         print "Goodbye!"
  96.         quit()
  97.     else:
  98.         print "Invalid option!\n"
  99.         menu()
  100.  
  101.  
  102. def lookup():
  103.     # Take stock symbol input.
  104.     symbol = ask_symbol()
  105.     # Establish the beginning date and timeframe.
  106.     past_date = ask_timeframe()
  107.     # Download date and price data from Yahoo. Ask the user to reinput the symbol if it doesn't exist.
  108.     data = get_data(symbol, past_date)
  109.     # Process the raw data.
  110.     date, close, sma, rsi, macd = process_data(data)
  111.     # Plot data.
  112.     plot_data(date, close, sma, rsi, macd)
  113.     # Return to main menu.
  114.     menu()
  115.  
  116.  
  117. if __name__ == "__main__":
  118.     print "Welcome to TA-Py!"
  119.     menu()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement