股票分析AI工具开发教程

你是否曾被大量的股票市场数据所淹没?希望有一个私人助理来筛选噪音并为您提供清晰、可操作的见解?好吧,你可以自己构建一个,而且由于 Python 的强大功能、随时可用的 API 和 AI 的帮助,它出奇地容易(而且免费!)。

重要免责声明:该项目仅用于教育和信息目的。它旨在演示如何集成各种 API 和 AI 模型。股票市场本质上是复杂且有风险的。请勿将此应用程序生成的“买入”或“卖出”信号用于实际交易决策。在做出任何投资决策之前,彻底了解金融市场、风险管理和独立研究是必不可少的。

该项目可以作为那些有兴趣探索人工智能与金融交集的人的基础,但它不能替代专业的财务建议。

在本教程中,我们将创建一个简单但有效的股票分析器:

  • 获取历史股票数据:使用免费的 Alpha Vantage API。
  • 可视化数据:使用 Matplotlib 创建交互式图表。
  • 提供人工智能分析:利用 Google 的 Gemini Flash 模型获取见解。
  • 在用户友好的 Web 应用程序中呈现所有内容:使用 Streamlit 构建。

该项目非常适合想要了解 API 集成、数据可视化和人工智能实际应用的初学者。无需任何金融或人工智能经验!

1、收集你的工具(和 API 密钥)

在深入研究代码之前,让我们确保你拥有必要的工具:

Python:确保已安装 Python 3.7 或更高版本。

库:我们将使用以下 Python 库。您可以使用 pip 安装它们:

pip install pandas matplotlib requests pytz google-generativeai streamlit

Streamlit:使用命令  pip install streamlit 进行安装

API 密钥:这就是“免费”魔法发生的地方!

  • Alpha Vantage:前往 alpha vantage并注册一个免费的 API 密钥。此密钥允许我们访问他们的库存数据。请将此密钥安全且保密!
  • Google AI Studio API 密钥:转到 Google AI Studio。单击“获取 API 密钥”。这将允许你使用 Gemini Flash 模型。也请将此密钥保密!
重要提示:免费 API 密钥通常有使用限制(例如,每分钟或每天的请求数量)。请注意这些限制以避免中断。Alpha Vantage 的免费套餐通常足以满足个人项目的需求。

让我们开始编码吧!

2、获取股票数据

首先,我们创建一个名为 stock_utility_handler.py 的文件。此文件将负责获取和处理股票数据。

import pandas as pd
import json
from datetime import datetime
import pytz
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.widgets as widgets
import requests


class StockAPI:
    def __init__(self,api_key):
        self.api_key = api_key
        
    def get_stock_info(self,stock,market):
        if market == 'NASDAQ':
            url = f'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={stock}&outputsize=compact&apikey={self.api_key}'
        else:
            url = f'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={stock}.{market}&outputsize=compact&apikey={self.api_key}'
        r = requests.get(url)
        data = r.json()
        return data 
    
class StockAnalyzer:
    def __init__(self):
        pass

    def json_to_dataframe(self,json_data,stock_symbol,market):
        print(json_data)
        time_series_data = json_data['Time Series (Daily)']
        df_data = []

        for date_str, values in time_series_data.items():
            data_row = {'date': date_str}
            for key, value in values.items():
                new_key = key.split('. ')[1]  # Correctly extract the key
                data_row[new_key] = float(value)
            df_data.append(data_row)

        df = pd.DataFrame(df_data)
        df['date'] = pd.to_datetime(df['date'])

        eastern = pytz.timezone('US/Eastern')
        ist = pytz.timezone('Asia/Kolkata')

        df['date'] = df['date'].dt.tz_localize(eastern).dt.tz_convert(ist)
        df['date'] = df['date'].dt.strftime('%Y-%m-%d %H:%M:%S')
        df['stock']=stock_symbol
        df['market']=market

        df = df.set_index('date')
        return df

    def plot_stock_data(self,df, stock_symbol, market,image_path):
        plt.figure(figsize=(16, 10))

        # Plotting Closing Price
        plt.subplot(3, 1, 1)
        plt.plot(pd.to_datetime(df.index), df['close'], label=f'{stock_symbol} Closing Price ({market})', color='blue')
        plt.title(f'{stock_symbol} Stock Performance ({market})')
        plt.xlabel('Date (IST)')
        plt.ylabel('Price')
        plt.legend()
        plt.grid(True)

        # Plotting Volume
        plt.subplot(3, 1, 2)
        plt.bar(pd.to_datetime(df.index), df['volume'], label=f'{stock_symbol} Volume ({market})', color='green', width=2)
        plt.xlabel('Date (IST)')
        plt.ylabel('Volume')
        plt.legend()
        plt.grid(True)

        # Plotting Moving Averages
        plt.subplot(3, 1, 3)
        df['MA_7'] = df['close'].rolling(window=7).mean()
        df['MA_20'] = df['close'].rolling(window=20).mean()
        plt.plot(pd.to_datetime(df.index), df['close'], label=f'{stock_symbol} Closing Price ({market})', color='blue', alpha=0.7)
        plt.plot(pd.to_datetime(df.index), df['MA_7'], label='7-Day MA', color='orange')
        plt.plot(pd.to_datetime(df.index), df['MA_20'], label='20-Day MA', color='red')
        plt.xlabel('Date Month(IST)')
        plt.ylabel('Price')
        plt.legend()
        plt.grid(True)

        # Enhanced Date Formatting for All Subplots
        for ax in plt.gcf().axes:
            # Major ticks every month, minor ticks every week
            ax.xaxis.set_major_locator(mdates.MonthLocator())
            ax.xaxis.set_minor_locator(mdates.WeekdayLocator(byweekday=[0]))  # Monday

            # Formatter for major ticks
            ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))

            # Formatter for minor ticks (hover tooltip will provide more detail)
            #ax.xaxis.set_minor_formatter(mdates.DateFormatter('%Y-%m-%d'))

            # Auto-rotate labels if needed
            plt.gcf().autofmt_xdate()

        # Add hover tooltip
        cursor = widgets.Cursor(plt.gca(), color='red', linewidth=1)

        plt.tight_layout()
        plt.savefig(image_path) 
        plt.show()

代码说明

get_stock_info():此函数根据股票代码和市场构建 API 请求 URL。它处理 BSE 和 NASDAQ 市场(您可以在项目中添加更多市场 :) )。它使用请求库进行 API 调用并返回 JSON 响应。

json_to_dataframe():此函数从 Alpha Vantage 获取原始 JSON 数据并将其转换为 Pandas DataFrame。这对于数据分析和可视化至关重要。它处理:

  • 提取“时间序列(每日)”数据。
  • 清理键(删除“1. “前缀)。
  • 将日期字符串转换为 datetime 对象。
  • 将日期从美国/东部转换为亚洲/加尔各答 (IST) 时区,并格式化日期。
  • 将“日期”列设置为索引。

plot_stock_data():此函数生成一个包含三个子图的综合图:

  • 收盘价:显示股票的每日收盘价。
  • 交易量:以条形图显示交易量。
  • 移动平均线:计算并绘制 7 天和 20 天移动平均线,这是常见的技术指标。

将图形保存到指定的 image_path。

3、添加 AI 洞察

现在,让我们创建 ai_insights_handler.py 以集成 Gemini Flash 模型进行 AI 驱动的分析。

import google.generativeai as genai
import PIL.Image

class AIInsights:
    def __init__(self,api_key):
        self.api_key=api_key
        genai.configure(api_key=self.api_key)
        self.model = genai.GenerativeModel(model_name = "gemini-2.0-flash")
        
    def get_ai_insights(self,image_path,stock,market):
        image = PIL.Image.open(image_path)
        prompt = f"This is an image of stock performance of stock : '{stock}' for the last 100 days on market : '{market}', on the basis of volume traded, closing prices and 7,20 day moving averages provide some analysis and suggestion abot this stock. This Stock should be purchased or not."
        response = self.model.generate_content([prompt, image])
        return response

代码说明

get_ai_insights():

  • 使用 PIL.Image.open() 打开保存的图像。
  • 为 Gemini 模型构建提示。提示清楚地描述了图像和所需的分析(基于成交量、收盘价和移动平均线的买入/卖出建议)。清晰的提示对于获得良好的结果至关重要。
  • 调用 model.generate_content(),传入提示和图像。这是多模式交互的核心。
  • 返回来自模型的响应。

4、构建 Streamlit Web 应用程序

收集在初始步骤中为 Google AI Studio 和 Alpha Vantage API 生成的 API 密钥。

最后,让我们创建 marketapp.py 以使用 Streamlit 构建用户友好的界面。

from stock_utility_handler import StockAPI, StockAnalyzer
from ai_insights_handler import AIInsights

import streamlit as st
    
if 'page' not in st.session_state:
    st.session_state.page = "page1"  
    st.session_state.ticker = "RELIANCE"  
    st.session_state.market = "BSE" 
    st.session_state.image_path = ""
    st.session_state.ai_insights = ""
    st.session_state.internal_results_available = False



def page1():
    st.title('Stock AI Agent')

    
    col1, col2 = st.columns(2)
    with col1:
        st.session_state.ticker = st.text_input("Enter Stock Ticker Symbol", value=st.session_state.ticker, key="ticker_input")  #Use key for unique input.
    with col2:
        st.session_state.market = st.selectbox("Select Market", ["BSE", "NASDAQ"], index=["BSE", "NASDAQ"].index(st.session_state.market), key="market_input") #Use key, corrected index.

    
    st.sidebar.header("About")
    st.sidebar.write("This is a stock analysis platform.")

    
    st.markdown("---")

    if st.button('Submit'):
        st.session_state.page = "page2"  # Go to the next page
        st.session_state.internal_results_available = False
        st.rerun() 

def page2():


    st.title(f"Analysis for {st.session_state.ticker} ({st.session_state.market})")  # Use stored inputs
    stock=st.session_state.ticker
    market=st.session_state.market
    if not st.session_state.internal_results_available:
        with st.spinner('Analyzing... Please wait...'):
            image_path=f"<your_image_path>/{market}_{stock}.png"
            st.session_state.image_path=image_path
            
            stock_api_obj = StockAPI("<your-alpha-vantage-api-key>>")

            market_data=stock_api_obj.get_stock_info(stock,market)

            stock_analyzer_obj=StockAnalyzer()

            df=stock_analyzer_obj.json_to_dataframe(market_data,stock, market)

            stock_analyzer_obj.plot_stock_data(df,stock, market,image_path)

            ai_insights_obj=AIInsights("<<your-google-api-key>>")

            response=ai_insights_obj.get_ai_insights(image_path,stock,market)

            candidates = response.candidates  
            for candidate in candidates:
                text_parts = candidate.content.parts
                for part in text_parts:
                    print(part.text)
                    st.session_state.ai_insights += part.text   
            st.session_state.internal_results_available = True
        
    if  st.session_state.internal_results_available:
        st.subheader("Chart Analysis")
        st.image(st.session_state.image_path, caption=f"{st.session_state.ticker} Chart",use_column_width=True)  # Example image

        st.subheader("Analysis Results")
        st.write(st.session_state.ai_insights)
        
        if st.button("Back"): #Back button
            st.session_state.page = "page1"
            st.session_state.internal_results_available = False
            st.rerun()


if st.session_state.page == "page1":
    page1()
elif st.session_state.page == "page2":
    page2()

最后,使用 streamlit run 运行 marketapp.py

streamlit run marketapp.py

以下是 UI 的一些屏幕截图

输入股票代码并选择市场。(这里我选择 HDFCBANK 仅作为示例)

你应该会看到一个屏幕,其中显示正在进行的 API 调用和数据分析。以下是结果图表和 AI 见解。


原文链接:Build Your Own AI-Powered Stock Analyzer (for Free!)

汇智网翻译整理,转载请标明出处