Advertisement
Guest User

Untitled

a guest
Feb 19th, 2017
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.71 KB | None | 0 0
  1. from __future__ import print_function
  2. import datetime
  3. import warnings
  4. import MySQLdb as mdb
  5. import requests
  6. # Obtain a database connection to the MySQL instance
  7. db_host = 'matthews-macbook-Pro.local'
  8. db_user = 'sec_user'
  9. db_pass = 'Nokiaone1'
  10. db_name = 'securities_master'
  11. con = mdb.connect(db_host, db_user, db_pass, db_name)
  12.  
  13. def obtain_list_of_db_tickers():
  14.     """
  15.    Obtains a list of the ticker symbols in the database.
  16.    """
  17.     with con:
  18.         cur = con.cursor()
  19.         cur.execute("SELECT id, ticker FROM symbol")
  20.         data = cur.fetchall()
  21.         return [(d[0], d[1]) for d in data]
  22.  
  23. def get_daily_historic_data_yahoo(ticker, start_date=(2000,1,1),
  24. end_date=datetime.date.today().timetuple()[0:3] ):
  25.     """
  26.    Obtains data from Yahoo Finance returns and a list of tuples.
  27.    ticker: Yahoo Finance ticker symbol, e.g. "GOOG" for Google, Inc.
  28.    start_date: Start date in (YYYY, M, D) format
  29.    end_date: End date in (YYYY, M, D) format
  30.    """
  31.     # Construct the Yahoo URL with the correct integer query parameters
  32.     # for start and end dates. Note that some parameters are zero-based!
  33.     ticker_tup = (
  34.     ticker, start_date[1]-1, start_date[2],
  35.     start_date[0], end_date[1]-1, end_date[2],
  36.     end_date[0]
  37.     )
  38.     yahoo_url = "http://ichart.finance.yahoo.com/table.csv"
  39.     yahoo_url += "?s=%s&a=%s&b=%s&c=%s&d=%s&e=%s&f=%s"
  40.     yahoo_url = yahoo_url % ticker_tup
  41.     # Try connecting to Yahoo Finance and obtaining the data
  42.     # On failure, print an error message.
  43.     try:
  44.         yf_data = requests.get(yahoo_url).text.split("\n")[1:-1]
  45.         prices = []
  46.         for y in yf_data:
  47.             p = y.strip().split(',')
  48.             prices.append(
  49.             (datetime.datetime.strptime(p[0], '%Y-%m-%d'),
  50.             p[1], p[2], p[3], p[4], p[5], p[6])
  51.             )
  52.     except Exception as e:
  53.         print("Could not download Yahoo data: %s" % e)
  54.         return prices
  55.  
  56. def insert_daily_data_into_db(data_vendor_id, symbol_id, daily_data):
  57.     """
  58.    Takes a list of tuples of daily data and adds it to the
  59.    MySQL database. Appends the vendor ID and symbol ID to the data.
  60.    daily_data: List of tuples of the OHLC data (with adj_close and volume)
  61.    """
  62.     # Create the time now
  63.     now = datetime.datetime.utcnow()
  64.  
  65.     # Amend the data to include the vendor ID and symbol ID
  66.     daily_data = [(data_vendor_id, symbol_id, d[0], now, now,
  67.                   d[1], d[2], d[3], d[4], d[5], d[6]) for d in daily_data]
  68.  
  69. # Create the insert strings
  70.     column_str = """data_vendor_id, symbol_id, price_date, created_date,
  71.                    last_updated_date, open_price, high_price, low_price,
  72.                    close_price, volume, adj_close_price"""
  73.     insert_str = ("%s, " * 11)[:-2]
  74.     final_str = "INSERT INTO daily_price (%s) VALUES (%s)" % \
  75.     (column_str, insert_str)
  76.  
  77. # Using the MySQL connection, carry out an INSERT INTO for every symbol
  78.     with con:
  79.         cur = con.cursor()
  80.         cur.executemany(final_str, daily_data)
  81.  
  82. if __name__ == "__main__":
  83.    
  84.     # This ignores the warnings regarding Data Truncation
  85.     # from the Yahoo precision to Decimal(19,4) datatypes
  86.     warnings.filterwarnings('ignore')
  87.    
  88.     # Loop over the tickers and insert the daily historical
  89.     # data into the database
  90.     tickers = obtain_list_of_db_tickers()
  91.     lentickers = len(tickers)
  92.  
  93.     # Print Adding data for Ticker
  94.     for i, t in enumerate(tickers):
  95.         print("Adding data for %s: %s out of %s" %
  96.         (t[1], i+1, lentickers))
  97.  
  98.     yf_data = get_daily_historic_data_yahoo(t[1])
  99.  
  100.     insert_daily_data_into_db('1', t[0], yf_data)
  101.  
  102.     print("Successfully added Yahoo Finance pricing data to DB.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement