Files
OpenBB/discordbot/stocks/technical_analysis/sma.py
Didier Rodrigues Lopes a0a22ee2cf Discordbot Technical Analysis (#1089)
* fix bug with window size on discordbot

* pylint and black fixes

* black linter
2021-12-23 19:25:18 +03:00

127 lines
3.9 KiB
Python

import os
from datetime import datetime, timedelta
import discord
from matplotlib import pyplot as plt
import pandas as pd
from gamestonk_terminal.helper_funcs import plot_autoscale
from gamestonk_terminal.common.technical_analysis import overlap_model
from gamestonk_terminal.config_plot import PLOT_DPI
import discordbot.config_discordbot as cfg
from discordbot.run_discordbot import gst_imgur
import discordbot.helpers
async def sma_command(ctx, ticker="", window="", offset="", start="", end=""):
"""Displays chart with simple moving average [Yahoo Finance]"""
try:
# Debug
if cfg.DEBUG:
print(f"!stocks.ta.sma {ticker} {window} {offset} {start} {end}")
# Check for argument
if ticker == "":
raise Exception("Stock ticker is required")
if start == "":
start = datetime.now() - timedelta(days=365)
else:
start = datetime.strptime(start, cfg.DATE_FORMAT)
if end == "":
end = datetime.now()
else:
end = datetime.strptime(end, cfg.DATE_FORMAT)
l_legend = [ticker]
if window == "":
window = [20, 50]
else:
window_temp = list()
for wind in window.split(","):
try:
window_temp.append(float(wind))
except Exception as e:
raise Exception("Window needs to be a float") from e
window = window_temp
if offset == "":
offset = 0
else:
if not offset.lstrip("-").isnumeric():
raise Exception("Number has to be an integer")
offset = float(offset)
ticker = ticker.upper()
stock = discordbot.helpers.load(ticker, start)
if stock.empty:
raise Exception("Stock ticker is invalid")
# Retrieve Data
price_df = pd.DataFrame(
stock["Adj Close"].values, columns=["Price"], index=stock.index
)
i = 1
for win in window:
sma_data = overlap_model.sma(
s_interval="1440min", df_stock=stock, length=win, offset=offset
)
price_df = price_df.join(sma_data)
l_legend.append(f"SMA {win}")
i += 1
# Output Data
start = start.strftime("%Y-%m-%d")
end = end.strftime("%Y-%m-%d")
price_df = price_df.loc[(price_df.index >= start) & (price_df.index < end)]
fig, ax = plt.subplots(figsize=plot_autoscale(), dpi=PLOT_DPI)
ax.set_title(f"{ticker} SMA")
ax.plot(price_df.index, price_df["Price"], lw=3, c="k")
ax.set_xlabel("Time")
ax.set_xlim([price_df.index[0], price_df.index[-1]])
ax.set_ylabel(f"{ticker} Price")
for idx in range(1, price_df.shape[1]):
ax.plot(price_df.iloc[:, idx])
ax.legend(l_legend)
ax.grid(b=True, which="major", color="#666666", linestyle="-")
plt.gcf().autofmt_xdate()
fig.tight_layout(pad=1)
plt.savefig("ta_sma.png")
uploaded_image = gst_imgur.upload_image("ta_sma.png", title="something")
image_link = uploaded_image.link
if cfg.DEBUG:
print(f"Image URL: {image_link}")
title = "Stocks: Simple-Moving-Average " + ticker
embed = discord.Embed(title=title, colour=cfg.COLOR)
embed.set_author(
name=cfg.AUTHOR_NAME,
icon_url=cfg.AUTHOR_ICON_URL,
)
embed.set_image(url=image_link)
os.remove("ta_sma.png")
await ctx.send(embed=embed)
except Exception as e:
embed = discord.Embed(
title="ERROR Stocks: Simple-Moving-Average",
colour=cfg.COLOR,
description=e,
)
embed.set_author(
name=cfg.AUTHOR_NAME,
icon_url=cfg.AUTHOR_ICON_URL,
)
await ctx.send(embed=embed)