<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          用python采集50W基金貼吧帖子,分析一下投資者情緒

          共 4459字,需瀏覽 9分鐘

           ·

          2021-11-27 10:02

          大家好,歡迎來(lái)到 Crossin的編程教室 !

          最近金融市場(chǎng)輾轉(zhuǎn)波動(dòng),年初入場(chǎng)的小伙伴也許還在等待市場(chǎng)的回暖。面對(duì)錯(cuò)綜復(fù)雜的市場(chǎng)環(huán)境,如何才能通過(guò)技術(shù)手段,更快更好判斷市場(chǎng)的變化,提前行動(dòng),是每一個(gè)會(huì)編程或想學(xué)編程的基民共同追求的目標(biāo)。

          本文利用Python語(yǔ)言及相關(guān)庫(kù),嘗試采集天天基金貼吧50W+帖子數(shù)據(jù)并分析投資者情緒,讓你更快洞察金融市場(chǎng)變化。


          01

          網(wǎng)頁(yè)分析



          我們首先挑選一只白酒基金,看看這只基金貼吧的數(shù)據(jù),網(wǎng)址及網(wǎng)頁(yè)內(nèi)容如下:


          http://guba.eastmoney.com/list,of161725.html


          由上圖可知,該基金共有6371頁(yè)合計(jì)509669條討論記錄,且還在不斷更新。數(shù)據(jù)字段包括閱讀、評(píng)論、標(biāo)題、作者、最后更新(評(píng)論時(shí)間)。點(diǎn)擊下一頁(yè),URL變?yōu)椋?/span>

          http://guba.eastmoney.com/list,of161725_2.html

          這個(gè)URL規(guī)則比較簡(jiǎn)單,只需設(shè)置基金代碼參數(shù)和頁(yè)碼參數(shù)來(lái)拼接URL,即可爬取任意基金貼吧數(shù)據(jù)。


          02

          數(shù)據(jù)爬取


          本文爬蟲主要使用的requests庫(kù),首先導(dǎo)入爬蟲相關(guān)包:

          import?csv
          import?time
          import?random
          import?requests
          import?traceback
          from?time?import?sleep
          from?fake_useragent?import?UserAgent
          from?lxml?import?etree


          嘗試請(qǐng)求一頁(yè)數(shù)據(jù),盡量設(shè)置隨機(jī)睡眠時(shí)間和使用隨機(jī)生成的headers,這是爬蟲人最基本的道德修養(yǎng),也是最簡(jiǎn)單的防反爬措施:

          page?=?1??#設(shè)置爬取的頁(yè)數(shù)
          fundcode?=?161725????#可替換任意基金代碼
          sleep(random.uniform(1,?2))??#隨機(jī)出現(xiàn)1-2之間的數(shù),包含小數(shù)
          headers?=?{"User-Agent":UserAgent(verify_ssl=False).random}
          url?=?f'http://guba.eastmoney.com/list,of{fundcode}_{page}.html'
          response?=?requests.get(url,?headers=headers,?timeout=10)
          print(reponse)


          F12看下網(wǎng)頁(yè)源代碼:


          網(wǎng)頁(yè)結(jié)構(gòu)還是很簡(jiǎn)單的,數(shù)據(jù)存放在id為articlelistnew的div下,該div下的第一個(gè)div為標(biāo)題行,因此從第二個(gè)div解析數(shù)據(jù)即可。本文采用xpath解析,其他解析方式也很簡(jiǎn)單。

          parse?=?etree.HTML(response.text)??#?解析網(wǎng)頁(yè)
          items?=?parse.xpath('//*[@id="articlelistnew"]/div')[1:91]
          for?item?in?items:
          ????item?=?{
          ?????????????'閱讀':?''.join(item.xpath('./span[1]/text()')).strip(),
          ?????????????'評(píng)論':?''.join(item.xpath('./span[2]/text()')).strip(),
          ?????????????'標(biāo)題':?''.join(item.xpath('./span[3]/a/text()')).strip(),
          ?????????????'作者':?''.join(item.xpath('./span[4]/a/font/text()')).strip(),
          ?????????????'時(shí)間':?''.join(item.xpath('./span[5]/text()')).strip()
          ????????????}
          ????print(item)


          數(shù)據(jù)爬取下來(lái),我們將其存儲(chǔ)為csv格式:


          with?open(f'./{fundcode}.csv',?'a',?encoding='utf_8_sig',?newline='')?as?fp:
          ????fieldnames?=?['閱讀',?'評(píng)論',?'標(biāo)題',?'作者',?'時(shí)間']
          ????writer?=?csv.DictWriter(fp,?fieldnames)
          ????writer.writerow(item)


          爬取多頁(yè)數(shù)據(jù)并將爬蟲代碼封裝成函數(shù),另外,建議在各代碼段加入異常處理,以防程序中途退出:

          #?主函數(shù)
          def?main(page):
          ????fundcode?=?161725????#可替換任意基金代碼
          ????url?=?f'http://guba.eastmoney.com/list,of{fundcode}_{page}.html'
          ????html?=?get_fund(url)
          ????parse_fund(html,fundcode)


          if?__name__?==?'__main__':
          ????for?page?in?range(1,6372):???#爬取多頁(yè)(共6371頁(yè))
          ????????main(page)
          ????????time.sleep(random.uniform(1,?2))
          ????????print(f"第{page}頁(yè)提取完成")


          OK,數(shù)據(jù)采集完成。


          03

          投資者情緒


          本文數(shù)據(jù)處理分析部分主要使用pandas庫(kù)。數(shù)據(jù)爬取完成后,我們就可以開始分析數(shù)據(jù)了,首先導(dǎo)入數(shù)據(jù):

          import?pandas?as?pd
          import?numpy?as?np

          df?=?pd.read_csv("/菜J學(xué)Python/金融/天天基金/161725.csv",
          ?????????????????names=['閱讀',?'評(píng)論',?'標(biāo)題',?'作者',?'時(shí)間'])


          做一些基本的數(shù)據(jù)清洗:

          #重復(fù)和缺失數(shù)據(jù)
          df?=?df.drop_duplicates()
          df?=?df.dropna()

          #數(shù)據(jù)類型轉(zhuǎn)換
          df['閱讀']?=?df['閱讀'].str.replace('萬(wàn)','').astype('float')
          df['時(shí)間']?=?pd.to_datetime(df['時(shí)間'],errors='ignore')?

          #機(jī)械壓縮去重
          def?yasuo(st):
          ????for?i?in?range(1,int(len(st)/2)+1):
          ????????for?j?in?range(len(st)):
          ????????????if?st[j:j+i]?==?st[j+i:j+2*i]:
          ????????????????k?=?j?+?i
          ????????????????while?st[k:k+i]?==?st[k+i:k+2*i]?and?k????????????????????k?=?k?+?i
          ????????????????st?=?st[:j]?+?st[k:]????
          ????return?st
          yasuo(st="J哥J哥J哥J哥J哥")
          df["標(biāo)題"]?=?df["標(biāo)題"].apply(yasuo)

          #過(guò)濾表情
          df['標(biāo)題']?=?df['標(biāo)題'].str.extract(r"([\u4e00-\u9fa5]+)")
          df?=?df.dropna()??#純表情直接刪除

          #過(guò)濾短句
          df?=?df[df["標(biāo)題"].apply(len)>=3]
          df?=?df.dropna()


          先制作一個(gè)詞云圖,看看大家對(duì)于這只基金的看法:


          import?jieba
          import?stylecloud
          from?IPython.display?import?Image?

          #?繪制詞云圖
          text1?=?get_cut_words(content_series=df['標(biāo)題'])
          stylecloud.gen_stylecloud(text='?'.join(text1),?max_words=200,
          ??????????????????????????collocations=False,
          ??????????????????????????font_path='simhei.ttf',
          ??????????????????????????icon_name='fas?fa-heart',
          ??????????????????????????size=653,
          ??????????????????????????#palette='matplotlib.Inferno_9',
          ??????????????????????????output_name='./基金.png')
          Image(filename='./基金.png')?



          好像很難明顯看出基民們的情緒......


          于是,繼續(xù)用更為量化的方法,計(jì)算出每個(gè)評(píng)論的情感評(píng)分:


          import?paddlehub?as?hub
          senta?=?hub.Module(name="senta_bilstm")
          texts?=?df['標(biāo)題'].tolist()
          input_data?=?{'text':texts}
          res?=?senta.sentiment_classify(data=input_data)
          df['投資者情緒']?=?[x['positive_probs']?for?x?in?res]


          對(duì)數(shù)據(jù)進(jìn)行重采樣


          #重采樣至15分鐘
          df['時(shí)間']?=?pd.to_datetime(df['時(shí)間'])?
          df.index?=?df['時(shí)間']
          data?=?df.resample('15min').mean().reset_index()


          通過(guò)AkShare這一開源API接口獲取上證指數(shù)分時(shí)數(shù)據(jù),AkShare是基于Python的財(cái)經(jīng)數(shù)據(jù)接口庫(kù),可以實(shí)現(xiàn)對(duì)股票、期貨、期權(quán)、基金、外匯、債券、指數(shù)、數(shù)字貨幣等金融產(chǎn)品的基本面數(shù)據(jù)、歷史行情數(shù)據(jù)的快速采集和清洗。


          import?akshare?as?ak
          import?matplotlib.pyplot?as?plt

          sz_index?=?ak.stock_zh_a_minute(symbol='sh000001',?period='15',?adjust="qfq")
          sz_index['日期']?=?pd.to_datetime(sz_index['day'])
          sz_index['收盤價(jià)']?=?sz_index['close'].astype('float')
          data?=?data.merge(sz_index,left_on='時(shí)間',right_on='日期',how='inner')
          matplotlib.use('Qt5Agg')
          data.index?=?data['時(shí)間']
          data[['投資者情緒','收盤價(jià)']].plot(secondary_y=['close'])
          plt.show()



          可以看出,投資者情緒相對(duì)于上證指數(shù)存在一個(gè)滯后效應(yīng)。


          以上就是我們對(duì)基金貼吧里帖子數(shù)據(jù)進(jìn)行處理并進(jìn)行分析的全過(guò)程。


          如果文章對(duì)你有幫助,歡迎轉(zhuǎn)發(fā)/點(diǎn)贊/收藏~


          作者:J哥

          來(lái)源:菜J學(xué)Python


          _往期文章推薦_

          python統(tǒng)計(jì)分析基金定投選星期幾更劃算?




          如需了解付費(fèi)精品課程教學(xué)答疑服務(wù)
          請(qǐng)?jiān)?strong style="max-width: 100%;overflow-wrap: break-word !important;box-sizing: border-box !important;">Crossin的編程教室內(nèi)回復(fù): 666

          瀏覽 38
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  大香蕉伊人精品 | 人人插人人操人人射 | 亚洲精品三级 | 日日撸色丁香五月 | 91久久精品夜夜躁日日躁欧美 |