Workspace

Send Slack messages with Python (template)

0
Beta
Spinner

Send Slack messages with Python

Business Logic

Let's write some Python code that tracks the total value of an imaginary portfolio of tech stocks. Feel free to swap this out with Python code for your project!

# package imports
import pandas as pd
import yfinance as yf
from datetime import datetime, timedelta
import plotly.graph_objs as go
import plotly.express as px
my_portfolio = {
    'AAPL': 18,
    'AMZN': 15,
    'MSFT': 7,
    'META': 10,
}
end_date = datetime.today().strftime('%Y-%m-%d')
start_date = (datetime.today() - timedelta(days=180)).strftime('%Y-%m-%d')

def get_historical_data(ticker, start_date, end_date, quantity):
    historical_data = yf.download(ticker, start=start_date, end=end_date, progress=False)*quantity
    historical_data.rename(columns={'Close': ticker}, inplace=True)  # Corrected line
    return historical_data[ticker]  # Corrected line

series = [ get_historical_data(stock, start_date, end_date, quantity) for stock, quantity in my_portfolio.items() ]

# Combine all data in one data frame
portfolio_df = pd.concat(series, axis=1)
portfolio_df
traces = [ go.Scatter(x=portfolio_df.index, y=portfolio_df[stock], mode='lines', name=stock) for stock in portfolio_df.columns]
layout = go.Layout(title='My stock portfolio over time', xaxis=dict(title='Date'), yaxis=dict(title='Stock Value'))
go.Figure(data=traces, layout=layout)
portfolio_df['Total'] = portfolio_df.sum(axis=1)
px.line(portfolio_df, x=portfolio_df.index, y='Total', title='Total Portfolio Value Over Time')
# Calculate the latest total value of the portfolio
latest_total = portfolio_df['Total'].iloc[-1]

# Calculate the percentage change compared to last week
last_week_total = portfolio_df['Total'].iloc[-8]
percentage_change_week = ((latest_total - last_week_total) / last_week_total) * 100

# Calculate the percentage change compared to last month
last_month_total = portfolio_df['Total'].iloc[-30]
percentage_change_month = ((latest_total - last_month_total) / last_month_total) * 100

# Print the f-string with the information
message = "\n".join([
    f"Total value of my portfolio on {portfolio_df.index[-1]:%B %d, %Y} is ${latest_total:,.2f}.",
    f"It's {'up' if percentage_change_week >= 0 else 'down'} {percentage_change_week:.2f}% compared to last week.",
    f"It's {'up' if percentage_change_month >= 0 else 'down'} {percentage_change_month:.2f}% compared to last month.",
])

print(message)

Sending the Slack message

import os
from slack_sdk import WebClient

# Append a link to the workspace
message += f"\nFor the full analysis, check <https://app.datacamp.com/workspace/w/{os.environ.get('DC_WORKSPACE_ID', 'invalid')}/edit|this workspace> (updates daily)"

# Send the Slack message
client = WebClient(token=os.environ["SLACK_TOKEN"])
client.chat_postMessage(channel="bot-updates", 
                        text=message, 
                        username="Bot User")
  • AI Chat
  • Code