Untitled

 avatar
unknown
plain_text
2 years ago
1.6 kB
10
Indexable
@bot.command(name='stock_trend')
async def stock_trend(ctx, symbol):
    """Get stock information and plot last year's data."""
    URL = f"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol={symbol}&apikey=ROKREWF5N63OKVU4"
    r = requests.get(URL)
    
    if r.status_code == 200:
        data = r.json()
        if 'Time Series (Daily)' in data:
            time_series = data['Time Series (Daily)']
            
            # Extracting data for the last year
            last_year_dates = list(time_series.keys())[:252]  # Assuming data is available for each business day
            last_year_close_prices = [float(time_series[date]['4. close']) for date in last_year_dates]
            
            # Plotting the data
            plt.figure(figsize=(10, 6))
            plt.plot(last_year_dates, last_year_close_prices, label='Closing Price')
            plt.title(f"Stock Data for {symbol} - Last Year")
            plt.xlabel("Date")
            plt.ylabel("Closing Price")
            plt.xticks(rotation=45)
            plt.legend()
            
            # Save the plot to a BytesIO object
            image_stream = BytesIO()
            plt.savefig(image_stream, format='png')
            plt.close()
            
            # Send the plot as an image
            image_stream.seek(0)
            await ctx.send(file=discord.File(image_stream, filename='stock_plot.png'))
        else:
            await ctx.send("Error: Time Series (Daily) not found in the API response.")
    else:
        await ctx.send(f"Error: Unable to fetch data. Status code: {r.status_code}")
Editor is loading...
Leave a Comment