angelorcc

Untitled

Mar 11th, 2020
718
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.80 KB | None | 0 0
  1. from datetime import datetime
  2. import lxml
  3. from lxml import html
  4. import requests
  5. import numpy as np
  6. import pandas as pd
  7. from iexfinance.stocks import Stock
  8. from iexfinance.refdata import get_symbols
  9.  
  10.  
  11. def get_page(url):
  12.     # Set up the request headers that we're going to use, to simulate
  13.     # a request by the Chrome browser. Simulating a request from a browser
  14.     # is generally good practice when building a scraper
  15.     headers = {
  16.         'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
  17.         'Accept-Encoding': 'gzip, deflate, br',
  18.         'Accept-Language': 'en-US,en;q=0.9',
  19.         'Cache-Control': 'max-age=0',
  20.         'Pragma': 'no-cache',
  21.         'Referrer': 'https://google.com',
  22.         'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'
  23.     }
  24.  
  25.     return requests.get(url, headers=headers)
  26.  
  27. def parse_rows(table_rows):
  28.     parsed_rows = []
  29.  
  30.     for table_row in table_rows:
  31.         parsed_row = []
  32.         el = table_row.xpath("./div")
  33.  
  34.         none_count = 0
  35.  
  36.         for rs in el:
  37.             try:
  38.                 (text,) = rs.xpath('.//span/text()[1]')
  39.                 parsed_row.append(text)
  40.             except ValueError:
  41.                 parsed_row.append(np.NaN)
  42.                 none_count += 1
  43.  
  44.         if (none_count < 4):
  45.             parsed_rows.append(parsed_row)
  46.            
  47.     return pd.DataFrame(parsed_rows)
  48.  
  49. def clean_data(df):
  50.     df = df.set_index(0) # Set the index to the first column: 'Period Ending'.
  51.     df = df.transpose() # Transpose the DataFrame, so that our header contains the account names
  52.    
  53.     # Rename the "Breakdown" column to "Date"
  54.     cols = list(df.columns)
  55.     cols[0] = 'Date'
  56.     df = df.set_axis(cols, axis='columns', inplace=False)
  57.    
  58.     numeric_columns = list(df.columns)[1::] # Take all columns, except the first (which is the 'Date' column)
  59.  
  60.     for column_name in numeric_columns:
  61.         df[column_name] = df[column_name].str.replace(',', '') # Remove the thousands separator
  62.  
  63.         df[column_name] = df[column_name].astype(np.float64) # Convert the column to
  64.        
  65.     return df
  66.  
  67. def scrape_table(url):
  68.     # Fetch the page that we're going to parse
  69.     page = get_page(url);
  70.  
  71.     # Parse the page with LXML, so that we can start doing some XPATH queries
  72.     # to extract the data that we want
  73.     tree = html.fromstring(page.content)
  74.  
  75.     # Fetch all div elements which have class 'D(tbr)'
  76.     table_rows = tree.xpath("//div[contains(@class, 'D(tbr)')]")
  77.    
  78.     # Ensure that some table rows are found; if none are found, then it's possible
  79.     # that Yahoo Finance has changed their page layout, or have detected
  80.     # that you're scraping the page.
  81.     assert len(table_rows) > 0
  82.    
  83.     df = parse_rows(table_rows)
  84.     df = clean_data(df)
  85.        
  86.     return df
  87.  
  88.  
  89.    
  90.    
  91.  
  92. symbol = get_symbols(output_format='pandas', token="pk_ddd55731690643d58498aec948695195")
  93. symbol=symbol['symbol']
  94. balance_sheet_url = 'https://finance.yahoo.com/quote/' + symbol + '/balance-sheet?p=' + symbol
  95.  
  96. df_balance_sheet = scrape_table(balance_sheet_url)
  97.  
  98.  
  99. df_income_statement = scrape_table('https://finance.yahoo.com/quote/' + symbol + '/financials?p=' + symbol)
  100. df_income_statement
  101.  
  102.  
  103. df_cash_flow = scrape_table('https://finance.yahoo.com/quote/' + symbol + '/cash-flow?p=' + symbol)
  104. df=df_balance_sheet
  105. df_balance_sheet.to_csv('balance_sheet.csv')
  106.  
  107.  
  108. def get_balance_sheet(symbol):
  109.    
  110.    
  111.    
  112.     balance_sheet_url = 'https://finance.yahoo.com/quote/' + symbol + '/balance-sheet?p=' + symbol
  113.     df_balance_sheet = scrape_table(balance_sheet_url)
  114.     for s in symbol:
  115.         print (df_balance_sheet)
  116.  
  117. get_balance_sheet('AAPL')
Advertisement
Add Comment
Please, Sign In to add comment