使用 Python 制作股市分析仪表板

写在前面

大家好,今天我将介绍一个基于Python快速构建应用程序的库 Streamlit,而为了更好的学习,我会带领大家编写一个的股票市场分析仪表盘。

Streamlit是一个用于构建数据科学和机器学习应用程序的开源Python库。它旨在使应用程序的创建过程变得简单而快速,无需繁琐的前端开发知识。使用Streamlit,您可以通过简单的Python脚本创建交互式应用程序,并实时预览结果。

印度股市在这几年里增长了很多,因为越来越多的人意识到储蓄和投资的重要性。这是一个可以帮助您在最初几天跟踪股票市场的工具。

准备工作

下载并安装python3.8+

依赖包:

yfinance
plotly
streamlit

安装方法:

pip install 包名
例如
pip install yfinance

编写代码

新建app.py文件,并输入以下内容。

from math import floor
import streamlit as st
import pandas as pd
import datetime
import yfinance as yf
import plotly.graph_objects as go
from plotly.subplots import make_subplots

st.title("Stock Price Screener and Analysis")"Stock Price Screener and Analysis")
pd.set_option('max_colwidth'400)
df = pd.DataFrame()

st.header("S&P BSE SENSEX")
today = datetime.date.today()
sensex = yf.download("^BSESN",start=today, interval="5m")
sensex_current = floor(sensex['Close'].iloc[-1])

if datetime.datetime.today().weekday()!=5 or datetime.datetime.today().weekday()!=6 :
    if datetime.datetime.now().hour > 16:
        st.write(f"Closing Price: {sensex_current}")
    else:
        st.write(f"Current Price: {sensex_current}")

if datetime.datetime.today().weekday() == 5 or datetime.datetime.today().weekday() == 6:
    sensex_current = floor(sensex['Close'].iloc[-2])
    st.write(f"Closing Price: {sensex_current}")
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.03, row_heights=[
                            0.70.3], specs=[[{"type""candlestick"}], [{"type""bar"}]])
fig.update_xaxes(rangeslider_visible=False)
fig.add_trace(go.Candlestick(x=sensex.index, open=sensex['Open'], high=sensex['High'],
                        low=sensex['Low'], close=sensex['Close'], name='market data'), row=1, col=1)
st.plotly_chart(fig, use_container_width=True)


st.header("NIFTY 50")
nifty = yf.download("^NSEI",start=today, interval="5m")
nifty_current = floor(nifty['Close'].iloc[-1])

if datetime.datetime.today().weekday()!=5 or datetime.datetime.today().weekday()!=6 :
    if datetime.datetime.now().hour > 16:
        st.write(f"Closing Price: {nifty_current}")
    else:
        st.write(f"Current Price: {nifty_current}")

if datetime.datetime.today().weekday() == 5 or datetime.datetime.today().weekday() == 6:
    nifty_current = floor(sensex['Close'].iloc[-2])
    st.write(f"Closing Price: {nifty_current}")
    
fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.03, row_heights=[
                            0.70.3], specs=[[{"type""candlestick"}], [{"type""bar"}]])
fig.update_xaxes(rangeslider_visible=False)
fig.add_trace(go.Candlestick(x=nifty.index, open=nifty['Open'], high=nifty['High'],
                        low=nifty['Low'], close=nifty['Close'], name='market data'), row=1, col=1)  
st.plotly_chart(fig, use_container_width=True)

todays_stock, stocks, indicators = st.tabs(
    ["Stock price for Today ""Historical Price of Stock""Indicators"])

with todays_stock:
    st.title("Today's Price of Stock")
    stock = st.text_input("Enter a stock ticker symbol""LT")
    Today_stock = st.button("Get Today's Price")
    today = datetime.date.today()
    if Today_stock:
        start_date = today
        df = yf.download(f"{stock}.NS", start=start_date, interval="2m")
        df['% Change'] = df['Close'].pct_change()*100
        df['% Change'] = df['% Change'].round(2)
        st.write(df)
        fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.03, row_heights=[
                            0.70.3], specs=[[{"type""candlestick"}], [{"type""bar"}]])
        fig.update_xaxes(rangeslider_visible=False)
        fig.add_trace(go.Candlestick(x=df.index, open=df['Open'], high=df['High'],
                      low=df['Low'], close=df['Close'], name='market data'), row=1, col=1)
        fig.add_trace(
            go.Bar(x=df.index, y=df['Volume'], name='Volume'), row=2, col=1)

        st.plotly_chart(fig, use_container_width=True)


with stocks:
    st.title("Stocks")
    stock_name = st.text_input("Enter a stock ticker symbol")
    start_date = st.date_input("Start date")
    goto_today = st.button("Get Price from start date till today")
    end_date = st.date_input("End date")
    get_stock = st.button("Get Stock Price")
    today_date = datetime.date.today() + datetime.timedelta(days=1)
    if end_date < start_date:
        st.error("Error: End date must fall after start date.")
    elif goto_today:
        end_date = today_date
        df = yf.download(f"{stock}.NS", start=start_date,
                         end=end_date, interval="15m")
        df.style.set_properties(**{'text-align''left'})
        st.write(df)
        fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.03, row_heights=[
                            0.70.3], specs=[[{"type""candlestick"}], [{"type""bar"}]])
        fig.update_xaxes(rangeslider_visible=False)
        fig.update_xaxes(
            rangebreaks=[
                dict(bounds=["sat""mon"]),
                dict(pattern='hour', bounds=[169])
            ]
        )

        fig.add_trace(go.Candlestick(x=df.index, open=df['Open'], high=df['High'],
                      low=df['Low'], close=df['Close'], name='market data'), row=1, col=1)
        fig.add_trace(
            go.Bar(x=df.index, y=df['Volume'], name='Volume'), row=2, col=1)

        st.plotly_chart(fig, use_container_width=True)
    elif get_stock:
        df = yf.download(f"{stock}.NS", start=start_date,
                         end=end_date+datetime.timedelta(days=1), interval="15m")
        df.style.set_properties(**{'text-align''left'})
        st.write(df)
        fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.03, row_heights=[
                            0.70.3], specs=[[{"type""candlestick"}], [{"type""bar"}]])
        fig.update_xaxes(rangeslider_visible=False)
        fig.update_xaxes(
            rangebreaks=[
                dict(bounds=["sat""mon"]),
                dict(pattern='hour', bounds=[169])
            ]
        )

        fig.add_trace(go.Candlestick(x=df.index, open=df['Open'], high=df['High'],
                      low=df['Low'], close=df['Close'], name='market data'), row=1, col=1)
        # bar chart
        fig.add_trace(
            go.Bar(x=df.index, y=df['Volume'], name='Volume'), row=2, col=1)

        st.plotly_chart(fig, use_container_width=True)

运行效果

现在,在终端中只需运行以下命令启动服务。

streamlit run app.py

然后在浏览器中输入以下地址,进入应在端口端口 8501。

localhost:8501

使用 Python 制作股市分析仪表板

写在最后

1. 为什么不用大A股的数据?

A股股民们很受伤了,还是多看看别人的数据。


2. Streamlit的代码我看不太懂。

这里只是一个示例,让你能够运行Streamlit,并对其有一个直观的认识。具体的编码规则还需要你去官网学习。


原文始发于微信公众号(harvey的网络日志):使用 Python 制作股市分析仪表板

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/196657.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!