Как построить фрейм данных из очищенной таблицы - PullRequest
0 голосов
/ 03 октября 2018

Я снова пытаюсь попытать удачи.На этот раз я использую python-3.6, чтобы попытаться преобразовать таблицу с https://www.reuters.com/finance/stocks/financial-highlights/KEPL3.SA в информационный фрейм, чтобы построить рейтинг Пиотроски F для компаний, зарегистрированных на бразильской фондовой бирже BOVESPA.Хотя я посмотрел в Интернете и нашел решения Quantopian и Quandl (готовые и бесплатные), они, похоже, не работают с бразильскими активами, поэтому я намерен хотя бы начать строить что-то подобное.Я начинаю с python и красивого супа, так что не берите в голову мой тупой код.

Это то, что я сделал до сих пор:

import requests, bs4
res = requests.get("https://www.reuters.com/finance/stocks/financial-highlights/KEPL3.SA")
res.raise_for_status()

rawsoup = bs4.BeautifulSoup(res.text, "lxml")

for row in rawsoup.find_all('tr'):
    cols = row.find_all('td')
    print(cols)

Что дает мне следующий результат:

$ python3 reuters_data.py 
[]
[]
[<td>P/E Ratio (TTM)</td>, <td class="data">--</td>, <td class="data">15.32</td>, <td class="data">24.24</td>]
[<td>
           P/E High - Last 5 Yrs.</td>, <td class="data">67.86</td>, <td class="data">36.54</td>, <td class="data">39.87</td>]
[<td>              
          P/E Low - Last 5 Yrs.</td>, <td class="data">9.48</td>, <td class="data">8.71</td>, <td class="data">15.24</td>]
[<td colspan="5"></td>]
[<td>
          Beta</td>, <td class="data">0.64</td>, <td class="data">1.33</td>, <td class="data">1.01</td>]
[<td colspan="5"></td>]
[<td>
          Price to Sales (TTM)</td>, <td class="data">0.43</td>, <td class="data">1.29</td>, <td class="data">2.27</td>]
[<td>
          Price to Book (MRQ)</td>, <td class="data">0.58</td>, <td class="data">2.13</td>, <td class="data">2.70</td>]
[<td>
          Price to Tangible Book (MRQ)</td>, <td class="data">0.65</td>, <td class="data">2.74</td>, <td class="data">5.41</td>]
[<td>
          Price to Cash Flow (TTM)</td>, <td class="data">--</td>, <td class="data">9.83</td>, <td class="data">15.03</td>]
.
.
.
[<td><strong># Net Buyers:</strong></td>, <td class="data"> <span class="changeUp">1</span> </td>]

(в середине я опустил часть результатов, но все это есть)

Теперь я достиг стены и не знаю, как правильно преобразовать этов кадре данных, так что я действительно могу сделать математику с этими числами в таблице.

Любая помощь приветствуется, и если мой источник плохой или есть лучший, пожалуйста, не стесняйтесь указать мне.

Большое спасибо.Ждем ответов.

1 Ответ

0 голосов
/ 04 октября 2018

Вы можете использовать свой скрипт следующим образом:

import requests, bs4
import pandas as pd

res = requests.get("https://www.reuters.com/finance/stocks/financial-highlights/KEPL3.SA")
res.raise_for_status()

soup = bs4.BeautifulSoup(res.content, features="lxml")
# find all 'table' tags in the html document
data_table = soup.findAll('table', {"class": "dataTable"})
i = 0
# Create an empty dictionary to be used later with pandas
Dict = {}
current_header = ""
# only second table matters that's why the index starts with 1
# then find every tr tag with the class= stripe according to the url you gave
for row in data_table[1].findAll('tr', {"class": "stripe"}):
    # find every td tag inside the 'tr' tags
    for cells in row.findAll('td'):
        # on your case every 4th row is a header so we use this as a dictionary key
        if i % 4 == 0:
            current_header = str(cells.find(text=True)).strip()
            # add some sanitization at the header title and add to the Dictionary
            Dict[str(cells.find(text=True)).strip()] = []
        else:
            data = cells.find(text=True)
            # try to parse the data as a float, othewise is a '--' 
            # and we should use the 0 to better represent the value as a number
            try:
                data = float(data)
            except:
                data = 0
            # append the values into the dictionary key(header)                
            Dict[current_header].append(data)
        i += 1

# Now you have a data similar to Dict= {'P/E Ratio (TTM)': [0, 15.32, 24.24], ...}
# using pandas we create a data frame from the dictionary
df = pd.DataFrame(Dict)
print(df.head)
...