2017-07-01 29 views
-1

我有以下谷歌金融股票指數(NSE:NIFTY50)的數據here。我想下載上面的數據爲csv,以便我可以對它做一些分析。我如何下載它?如果可以的話,我寧願使用python。下載歷史股指數據

+1

我很驚訝你代表一個用戶不知道如何在這裏提出一個正確的,完整的問題。你有什麼嘗試? (我沒有downvote) –

回答

1

您應該能夠使用下面的代碼下載股票數據。

import requests 
from bs4 import BeautifulSoup 
import pandas as pd 

url = "https://www.google.com/finance/historical?cid=207437&startdate=Jan%201%2C%201971&enddate=Jul%201%2C%202017&start={0}&num=30" 
#change this to 138 
how_many_pages=3 
start=0 

for i in range(how_many_pages): 
    new_url = url.format(start) 
    page = requests.get(new_url) 
    soup = BeautifulSoup(page.content, "html5lib") 
    table = soup.find_all('table', class_='gf-table historical_price')[0] 

    columns_header = [th.getText() for th in table.findAll('tr')[0].findAll('th')] 
    data_rows=table.findAll('tr')[1:] 
    data=[[td.getText() for td in data_rows[i].findAll(['td'])] for i in range(len(data_rows))] 

    if (start == 0): 
     final_df = pd.DataFrame(data, columns=columns_header) 
    else: 
     df=pd.DataFrame(data, columns=columns_header) 
     final_df = pd.concat([final_df, df],axis=0) 
    start += 30 
#write your code to save final_df to csv 

請不要忘記標記爲答案,如果它有助於:)

+0

如果我增加頁數到4110我得到'文件nse_data.py「,第14行,在 table = soup.find_all('table',class _ ='gf-table historical_price ')[0] IndexError:列表索引超出範圍' – liv2hak

+0

更改爲138(= 4110/30 +1) – Prem