DEV Community

Cover image for Streamlining Stock Market Analysis with Lyzr’s DataAnalyzr Agent
Prajjwal Sule
Prajjwal Sule

Posted on

Streamlining Stock Market Analysis with Lyzr’s DataAnalyzr Agent

In the fast-paced world of the stock market, making informed decisions is key to success for investors and traders. To aid in this endeavor, we introduce Market Insight—a sophisticated data analysis application designed to offer users comprehensive insights into historical stock data.


Lyzr DataAnalyzr | Lyzr Documentation

DataAnalyzr empowers advanced data analysis through a conversational interface to derive actionable insights and intuitive visualizations.

favicon docs.lyzr.ai

Powered by Lyzr’s DataAnalyzr agent and leveraging data from Yahoo Finance, Market Insight enables users to explore technical indicators and visualize key metrics for their selected companies.


GitHub: Lyzr-Market-Insight


Setting Up the Environment

Before diving into the development of Market Insight, let’s set up our environment.

python3 -m venv venv
source venv/bin/activate
pip3 install -r requirements.txt

Enter fullscreen mode Exit fullscreen mode

Next, create an environment variable for your OpenAI API key in a .env file

OPENAI_API_KEY="Paste your OpenAI API key here"

Enter fullscreen mode Exit fullscreen mode

Project Structure

The Market Insight project is structured as follows

Lyze-Market-Insight/
│
├── data/
│   └── (CSV files will be uploaded here)
│
├── plot/
│   └── (Generated plot PNG files will be stored here)
│
├── utils/
│   ├── __init__.py
│   └── utils.py
│
├── app.py
│
├── README.md
│
├── .env
│
├── .gitignore
│
└── requirements.txt

Enter fullscreen mode Exit fullscreen mode

The data directory stores CSV files containing historical stock data, while the plot directory holds generated plot images. The utils directory contains utility functions, and app.py serves as the main entry point for the application.

Lyzr - NSE Market Insight app

Initialization and Data Retrieval

Let’s initialize the application and allow users to select a company for analysis.

import os
import yfinance as yf
import pandas as pd
from pathlib import Path
import streamlit as st
from utils import utils
from dotenv import load_dotenv; load_dotenv()
from lyzr import DataConnector, DataAnalyzr

apikey = os.getenv('OPENAI_API_KEY')

data = "data"
plot = 'plot'
os.makedirs(data, exist_ok=True)
os.makedirs(plot, exist_ok=True)

Enter fullscreen mode Exit fullscreen mode

The above code initializes the application environment, retrieves the OpenAI API key from the environment variable, and creates directories to store data files and generated plots. It also imports necessary libraries and modules.

Data Acquisition and Management

Next, we enable users to select a company and save its historical stock data.

def save_option(selected_option):
    dataframe = yf.download(selected_option)
    utils.remove_existing_files(data)
    dataframe.to_csv(f"data/{selected_option}.csv")

def select_company():
    options_list = utils.company_list()
    selected_option = st.selectbox("Select an option", options_list)

    col1, col2 = st.columns(2)

    with col1:
        if st.button("Save Option"):
            save_option(selected_option)
            st.write("You selected:", selected_option)

    with col2:
        if st.button('Clear'):
            utils.remove_existing_files(data)
            utils.remove_existing_files(plot)

Enter fullscreen mode Exit fullscreen mode

The save_option() function downloads historical stock data for the selected company from Yahoo Finance, saves it as a CSV file in the data directory, and clears any existing data files. select_company() presents a dropdown menu of company options, allowing users to save their selected company’s data or clear existing data.

Data Analysis with DataAnalyzr

Once the data is acquired, we leverage Lyzr’s DataAnalyzr agent to perform analysis and generate insights.

def market_analyzr():
    path = utils.get_files_in_directory(data)
    path = path[0]

    dataframe = DataConnector().fetch_dataframe_from_csv(file_path=Path(path))
    analyzr = DataAnalyzr(df=dataframe, api_key=apikey)

    return analyzr

Enter fullscreen mode Exit fullscreen mode

The market_analyzr() function fetches the historical stock data from the CSV file, initializes a DataAnalyzr object, and returns it for further analysis.

Insights Generation and Visualization

Finally, we generate insights and visualize technical indicators based on the historical stock data.

def generating_insights(analyzr):
    description = analyzr.dataset_description()
    analysis = analyzr.analysis_recommendation()
    prompts = ["Create a candlestick chart to visualize the open, high, low, and close prices of the stock for each trading day over a specific period",
               "Plot Bollinger Bands around the closing price chart to visualize volatility and potential reversal points",
               "Plot the RSI indicator to assess the stock's momentum and overbought/oversold conditions. RSI values above 70 indicate overbought conditions, while values below 30 indicate oversold conditions",
               "Plot the MACD indicator to identify trend changes and potential buy/sell signals. MACD consists of a fast line (MACD line), slow line (signal line), and a histogram representing the difference between the two lines",
               "Plot a histogram of daily returns (percentage change in closing price) to visualize the distribution of returns and assess risk",
               "Plot a chart showing the high, low, and closing prices for each trading day over a specific period. This provides a comprehensive view of daily price fluctuations.",
               "Overlay moving average lines (e.g.,44-day moving averages) on the closing price chart to smooth out price fluctuations and identify long-term trends."
                ]

    utils.remove_existing_files(plot)
    for prompt in prompts:
        vis = analyzr.visualizations(user_input=prompt, dir_path=Path('./plot'))

    return description, analysis


def file_checker():
    file = []
    for filename in os.listdir(data):
        file_path = os.path.join(data, filename)
        file.append(file_path)

    return file

Enter fullscreen mode Exit fullscreen mode

The generating_insights() function utilizes the DataAnalyzr object to retrieve dataset descriptions and analysis recommendations. It then iterates through a list of prompts, generating visualizations for each prompt and saving them in the plot directory. The file_checker() function checks for the presence of files in the data directory.

Execution

Finally, we execute the application and display the insights to the user.

if __name__ == "__main__":
    select_company()
    file = file_checker()
    if len(file) > 0:
        analyzr = market_analyzr()
        description, analysis = generating_insights(analyzr)
        if description is not None:
            st.subheader("Description of the Company Data")
            st.write(description)
            plot_files = os.listdir("./plot")
            st.subheader("Technical Indicators for the Company Stock")
            for plot_file in plot_files:
                st.image(f"./plot/{plot_file}")
            st.subheader("Recommended Analysis")
            st.write(analysis)
        else:
            st.error('Error occurred while generating description')

Enter fullscreen mode Exit fullscreen mode

This code snippet executes the application, allowing the user to select a company, save its historical stock data, and generate insights and visualizations. It displays the dataset description, technical indicators' visualizations, and recommended analysis to the user.

Conclusion

Market Insight streamlines the process of stock market analysis, providing users with powerful insights and visualizations to make informed decisions. Leveraging Lyzr’s DataAnalyzr agent, the application offers a seamless and intuitive approach to technical analysis, empowering investors and traders alike to navigate the complexities of the stock market with confidence.

References

For further exploration and engagement, refer to Lyzr's website, book a demo, or join the community channels on Discord and Slack.

Lyzr Website: https://www.lyzr.ai/
Book a Demo: https://www.lyzr.ai/book-demo/
Lyzr Community Channels: Discord, Slack

Top comments (0)