本篇文章,咱们来聊聊如何依据「 行业板块 」辅助咱们进行价值投资

 1. 行业板块

行业板块与概念股在定义上还是有很大区别的

一般来说,概念板块的危险更大,基于某个音讯被短期炒作,很不稳固,因而危险更大

行业板块是按股票行业进行分类,往往重视于长期,稳定性更高

在理论投资上,短期能够依据按「 市场热点 」从概念股进行选股投资,中长期还是倡议按「 行业板块 」选股进行投资

 2. 爬取相干板块及个股列表

指标对象:

aHR0cDovL3N1bW1hcnkuanJqLmNvbS5jbi9oeWJrLw==

2-1  板块列表

首先,咱们应用 「 Toggle JavaScript 」插件发现页面中的行业板块数据来源于上面的申请后果

http://**/?q=cn|bk|17&n=hqa&c=l&o=pl,d&p=1020&_dc=1650680429759

其中,参数为 p 和 _dc 为可变参数,p 代表页码数(从 1 开始),_dc 代表 13 位的工夫戳,其余查问参数都是固定内容

而后,咱们编写代码获取响应数据,应用正则表达式匹配出行业列表的数据

...self.ps_url = 'http://**/?q=cn|bk|17&n=hqa&c=l&o=pl,d&p={}050&_dc={}'....    def __get_timestramp(self):        """        获取13位的工夫戳        :return:        """        return int(round(time.time() * 1000))...    def get_plates_list(self, plate_keyword):        """        获取所有板块        :return:        """        plates = []        index = 0        while True:            url = self.ps_url.format(index + 1, self.__get_timestramp())            # 解析数据            resp = self.session.get(url, headers=self.headers).text            match = re.compile(r'HqData:(.*?)};', re.S)            result = json.loads(re.findall(match, resp)[0].strip().replace("\n", ""))            if not result:                break            # 依据关键字,过滤无效板块            temp_plate_list = [item for item in result if plate_keyword in item[2]]            index += 1            for item in temp_plate_list:                print(item)                plates.append({                    "name": item[2],                    "plate_path": item[1],                    "up_or_down": str(item[10]) + "%",                    "top_stock": item[-6]                })        return plates...

最初,依据关键字对板块进行一次筛选,通过板块名、板块门路 PATH、板块涨跌幅、最大奉献股票名称从新组装成一个列表

留神:通过剖析页面发现,依据板块门路 PATH 能够组装成行业板块个股列表页面 URL

比方,行业板块 PATH 为 400128925,那么行业板块对应个股列表的页面 URL 为

http://summary.**/hybk/400128925.shtml

2-2  行业个股列表

爬取行业个股列表和上一步数据展现逻辑一样,个股列表数据同样来源于上面申请的后果

http://**/?q=cn|s|bk{}&c=m&n=hqa&o=pl,d&p={}020&_dc={}

其中,bk 前面对应行业板块 PATH,p 代表页码数,_dc 代表 13 位的工夫戳

...# 个股self.stock_url = 'http://**/?q=cn|s|bk{}&c=m&n=hqa&o=pl,d&p={}020&_dc={}'....    def get_stock_list(self, plate_path):        """        获取某一个板块下所有的个股信息        蕴含:股票名称、最新价格、涨跌幅、市盈率        :param plate_info:        :return:        """        index = 0        stocks = []        while True:            url = self.stock_url.format(plate_path, index + 1, self.__get_timestramp())            resp = self.session.get(url, headers=self.headers).text            match = re.compile(r'HqData:(.*?)};', re.S)            result = json.loads(re.findall(match, resp)[0].strip().replace("\n", ""))            if not result:                break            index += 1            for item in result:                if item[-1] < 0:                    continue                stocks.append({                    "stock_name": item[2],                    "pe": item[-1],                    "price": item[8],                    "up_or_down": str(item[12]) + "%"                })        # 按pe降序排列        stocks.sort(key=lambda x: x["pe"])        return stocks

通过正则表达式对响应后果进行匹配后,获取个股的名称、PE 市盈率、价格、涨跌幅 4 个要害数据

最初,对个股列表按 PE 进行升序排列后间接返回

 3. 服务化

当然,咱们能够将这部分逻辑服务化供前端应用,以此晋升用户的体验性

比方,应用 FastAPI 能够疾速创立两个服务:依据关键字获取行业板块列表、依据板块门路获取个股列表

from pydantic import BaseModel# 板块class Plate(BaseModel):    content: str  # 关键字# 板块下的个股class PlateStock(BaseModel):    plate_path: str  # 板块门路#===========================================================...# 获取板块列表@app.post("/xag/plate_list")async def get_plate_list(plate: Plate):    pstock = PStock()    try:        result = pstock.get_plates_list(plate.content)        return success(data=result, message="查问胜利!")    except Exception as e:        return fail()    finally:        pstock.teardown()# 获取某一个板块下的所有股票列表@app.post("/xag/plate_stock_list")async def get_plate_list(plateStock: PlateStock):    pstock = PStock()    try:        result = pstock.get_stock_list(plateStock.plate_path)        return success(data=result, message="查问胜利!")    except Exception as e:        return fail()    finally:        pstock.teardown()...

前端以 Uniapp 为例,应用 uni-table 组件展现行业板块列表及个股列表

局部代码如下:

//个股列表 platestock.vue...<view class="box">                <uni-forms ref="baseForm" :modelValue="baseFormData" :rules="rules">                    <uni-forms-item label="关键字" required name="content">                        <uni-easyinput v-model="baseFormData.content" placeholder="板块关键字" />                    </uni-forms-item>                </uni-forms>                <button type="primary" @click="submit('baseForm')">提交</button>                <!-- 后果区域 -->                <view class="result" v-show="result.length>0">                    <uni-table ref="table" border stripe emptyText="暂无数据">                        <uni-tr class="uni-item">                            <uni-th align="center" class="uni-th" width="100%">板块</uni-th>                            <uni-th align="center" class="uni-th" width="100%">涨跌幅</uni-th>                            <uni-th align="center" class="uni-th" width="100%">强势股</uni-th>                        </uni-tr>                        <uni-tr class="uni-item" v-for="(item, index) in result" :key="index" @row-click="rowclick(item)">                            <uni-td class="uni-th" align="center">{{ item.name }}</uni-td>                            <uni-td align="center" class="uni-th">{{ item.up_or_down }}</uni-td>                            <uni-td align="center" class="uni-th">{{ item.top_stock }}</uni-td>                        </uni-tr>                    </uni-table>                </view>            </view>...methods: {            //表单提交数据            submit(ref) {                this.$refs[ref].validate().then(res => {                    this.$http('xag/plate_list', this.baseFormData, {                        hideLoading: false,                        hideMsg: false,                        method: 'POST'                    }).then(res => {                        console.log("内容:", res.data)                        if (res.data && res.data.length > 0) {                            this.$tip.success("查问胜利!")                            this.result = res.data                        } else {                            this.$tip.success("查问后果为空,请换一个关键字查问!")                        }                    }).catch(err => {                        console.log("产生异样,异样信息:", err)                    })                }).catch(err => {                    console.log('err', err);                })            }...

最初部署完我的项目后,在前端页面就能依据板块名抉择适合的个股进行投资了

 4. 总结一下

因为行业板块更实用于中长期投资,咱们只须要依据某一个关键字筛选出一个板块,而后在板块下的个股列表中能够十分直观地看出市盈率较低的个股进行投资即可

如果你感觉文章还不错,欢送关注公众号:Python编程学习圈,或是返回编程学习网,理解更多编程技术常识,还有大量干货学习材料能够支付!