Skip to content

This workbook is making an API connection to OpenAI and using the AI to help me label company stock into sectors.

Then I will create a live chat where I can ask it continuous questions about the data itself, and ask for any investment recommendations.

import os
import pandas as pd
from openai import OpenAI

# Instantiate an API client
# If you named your environment variable differently 
# then change "OPENAI_API_KEY" to reflect the variable name
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

# Continue coding here
# Use as many cells as you like
data = pd.read_csv("nasdaq100.csv")

data.head()
data_change = pd.read_csv("nasdaq100_price_change.csv")

data_change.head()
data2 = data.merge(data_change[["symbol", "ytd"]], left_on="symbol", right_on="symbol", how="left")

data2.head()

For each company, ask the AI what sector it should belong to. Add that sector data as a new column to the master dataset.

for company in data["symbol"]:
    #create a prompt to generate the sector for each company symbol
    prompt = f"""Cassify company {company} into one of the following sectors. Answer only with the sector name: Technology, Consumer Cyclical, Industrials, Utilities, Healthcare, Communication, Energy, Consumer Defensive, Real Estate, or Financial."""
    
    #create the response from the api
    response = client.chat.completions.create(
    model='gpt-4o-mini',
        messages=[{"role":"user", "content": prompt}],
        temperature=0
    )
    
    #store the output as a variable called sector
    sector = response.choices[0].message.content
    
    #add the sector for the corresponding company
    data.loc[data["symbol"] == company, "Sector"] = sector
data
#Count the number of sectors
data["Sector"].value_counts()
#write a prompt to get stock recommendations
prompt = f"""Provide summary information about the Nasdaq-100 stock performance year to date (ytd), recommending the three best sectors and three best companies in each sector. Company data: {data}
"""
#create the response from the api
response = client.chat.completions.create(
    model='gpt-4o-mini',
    messages=[{"role":"user", "content": prompt}],
    temperature=0
)
    
#store the output as a variable called sector
recommendation = response.choices[0].message.content
print(recommendation) 
# create json string so user can pass the dataframe into the chatbot with the input() bar.
df_str = data.to_json()
print(df_str)

The above response is pretty detailed and I would like to ask the AI some followup questions. I need to build a function that displays a prompt and stores my questions and responses to give the AI some context around the questions I am asking.

I will repose the question above (directing it to give me a shorter reposne) and then ask followups.

def chat_with_openai():
    print("Hello! Welcome to the ChatGPT simple investment advisor. Do you have a question for me today? Type 'exit' to end the session.")
    print(" ") #formatting the terminal
    
    # Initialize the conversation with a system message
    messages = [
        {"role": "system", "content": "You are a investment advisor who provides short, simple answers."}
    ]
    
    while True:
        
        # Prompt the user for input
        user_input = input(f"""User: """)
        
        # Exit the chat if the user types 'exit'
        if user_input.lower() == 'exit':
            print("Exiting the chat. Goodbye!")
            break
        
        # Append the user's input to the conversation
        messages.append({"role": "user", "content": user_input})
        
        # Send the conversation to OpenAI's API
        try:
            response = client.chat.completions.create(
                model="gpt-4o-mini",
                messages=messages
            )
            
            # Extract and print the assistant's response
            assistant_response = response.choices[0].message.content
            print(" ")#formatting the terminal
            print(f"Assistant: {assistant_response}")
            print(" ")#formatting the terminal
            
            # Append the assistant's response to the conversation
            messages.append({"role": "assistant", "content": assistant_response})
        except Exception as e:
            print(f"An error occurred: {e}")