Streamlining Stock Market Analysis with Lyzr’s DataAnalyzr Agent
Tags: beginners, tutorial, ai, datascience
Published: 2024-03-20 04:05:12

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. 

---

{% embed https://docs.lyzr.ai/lyzr-sdk/opensource/data-analyzr/ %}
---


Powered by [Lyzr’s DataAnalyzr](https://www.lyzr.ai/) 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](https://github.com/PrajjwalLyzr/Lyzr-MarketInsight)

---


## Setting Up the Environment

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

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

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

```python
OPENAI_API_KEY="Paste your OpenAI API key here"

```

## Project Structure

The Market Insight project is structured as follows

```bash
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

```
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
{% embed https://youtu.be/weWXhyBdQNI %}

## Initialization and Data Retrieval

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

```python
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)

```
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.

```python
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)

```
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.

```python
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

```
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.

```python
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

```
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.

```python
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')

```
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/](https://www.lyzr.ai/)
Book a Demo: [https://www.lyzr.ai/book-demo/](https://www.lyzr.ai/book-demo/)
Lyzr Community Channels: [Discord](https://discord.gg/nm7zSyEFA2), [Slack](https://join.slack.com/t/genaiforenterprise/shared_invite/zt-2a7fr38f7-_QDOY1W1WSlSiYNAEncLGw)