Skip to content

Instantly share code, notes, and snippets.

@Owez
Created February 23, 2021 21:13
Show Gist options
  • Save Owez/4a9724fc3be721eccad8b9abd3fbede6 to your computer and use it in GitHub Desktop.
Save Owez/4a9724fc3be721eccad8b9abd3fbede6 to your computer and use it in GitHub Desktop.
A simple and quite terrible trading bot made in an hour or so to learn some mpl
import os
import discord
import matplotlib.pyplot as plt
import mplfinance
import numpy as np
import pandas as pd
import yfinance as yf
from discord.ext.commands import Bot
PATH_HISTORIC = "historic.png"
client = Bot(command_prefix=";")
class Stock:
"""A single stock being tracked inside of trado instance"""
original = "Unknown stock"
name = "UNKNOWN"
def __init__(self, name: str):
self.original = name
self.name = "".join(i for i in name if ord(i) < 128).upper()
def __repr__(self):
return f"`{self.name}`"
@property
def ticker(self):
try:
return self._ticker
except AttributeError:
self._ticker = yf.Ticker(self.name)
return self._ticker
@property
def info(self):
try:
return self._info
except AttributeError:
self._info = self.ticker.info
return self._info
def graph(self, df, title: str):
"""Generates a matplotlib graph"""
mplfinance.plot(
df,
title=title,
type="candle",
style="charles",
volume=True,
mav=(3, 6, 9),
ylabel="Price ($)",
ylabel_lower="Shares \nTraded",
savefig=PATH_HISTORIC,
)
def gen_title(short_name: str, period: str) -> str:
return f"{short_name} for {period}"
@client.event
async def on_ready():
print(f"Trado logged in as {client.user.id}")
@client.command(aliases=["h", "historic"])
async def history(ctx, name: str, period: str = "max"):
"""Searches and returns stock graph"""
stock = Stock(name)
await ctx.send(f":blue_circle: Searching for historic {stock} stock")
try:
title = gen_title(stock.info["shortName"], period)
df = stock.ticker.history(period=period)
except:
await ctx.send(f":red_circle: Historic stock {stock} not listed")
return
await ctx.send(f":blue_circle: Generating graph for {stock} stock")
try:
stock.graph(df, title)
except:
await ctx.send(
f":red_circle: Error whilst generating graph for historic {stock} stock"
)
await ctx.send(":green_circle: Generated graph", file=discord.File(PATH_HISTORIC))
if __name__ == "__main__":
client.run(os.environ["CLIENT_TOKEN"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment