POrtfolio attribution commentary generator app that takes an attribution file as input and creates editable attribution commentary leveraging an LLM call
To upload files, please first save the app
import streamlit as st
import pandas as pd
import openai
from dotenv import load_dotenv
import os
# Load environment variables
load_dotenv()
# Configure OpenAI
openai.api_key = os.getenv("OPENAI_API_KEY")
def generate_commentary(attribution_data):
"""Generate commentary using OpenAI API based on attribution data"""
prompt = f"""
Based on the following portfolio attribution data:
{attribution_data}
Generate a detailed investment commentary that:
1. Explains the main drivers of performance
2. Highlights notable sector/stock contributions
3. Provides context for the attribution results
4. Uses professional investment language
Format the commentary in clear paragraphs.
"""
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are an expert investment portfolio manager skilled at writing attribution commentary."},
{"role": "user", "content": prompt}
]
)
return response.choices[0].message.content
except Exception as e:
return f"Error generating commentary: {str(e)}"
# App title
st.title("Portfolio Attribution Commentary Generator")
# API Key input
api_key = st.text_input("Enter your OpenAI API Key", type="password")
if api_key:
openai.api_key = api_key
# File upload
uploaded_file = st.file_uploader("Upload attribution data (CSV)", type="csv")
if uploaded_file is not None:
try:
# Read the CSV file
df = pd.read_csv(uploaded_file)
# Display the attribution data
st.subheader("Attribution Data")
st.dataframe(df)
# Generate commentary button
if st.button("Generate Commentary"):
if not openai.api_key:
st.error("Please enter your OpenAI API key")
else:
with st.spinner("Generating commentary..."):
# Convert DataFrame to string for the prompt
attribution_text = df.to_string()
commentary = generate_commentary(attribution_text)
# Display generated commentary in an editable text area
st.subheader("Generated Commentary")
edited_commentary = st.text_area(
"Edit the commentary as needed:",
value=commentary,
height=400
)
# Add download button for the commentary
if st.button("Download Commentary"):
st.download_button(
label="Download Commentary as Text",
data=edited_commentary,
file_name="attribution_commentary.txt",
mime="text/plain"
)
except Exception as e:
st.error(f"Error processing file: {str(e)}")
# Instructions
with st.expander("How to use"):
st.markdown("""
1. Enter your OpenAI API key
2. Upload a CSV file containing portfolio attribution data
3. Click 'Generate Commentary' to create an AI-generated investment commentary
4. Edit the generated commentary as needed
5. Download the final commentary using the download button
Expected CSV format:
- The file should contain attribution data with columns like Security, Sector, Weight, Return, Contribution, etc.
- Make sure the data is clean and properly formatted
""")
# Add footer with disclaimer
st.markdown("---")
st.caption("Disclaimer: This tool uses AI to generate commentary. Please review and edit all generated content before use.")
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?