mirror of
https://gitlab.com/simple-stock-bots/simple-discord-stock-bot.git
synced 2025-06-16 15:17:29 +00:00
Compare commits
41 Commits
Author | SHA1 | Date | |
---|---|---|---|
3d453115fe | |||
c0a6e268a6 | |||
eb48ab74c2 | |||
342392b604 | |||
7e05e2dbec | |||
a7fb09e341 | |||
c6db51a5cc | |||
f434fa7c6f | |||
1e64deeff5 | |||
5e90bf9eab | |||
45f0ee0091 | |||
389ed77883 | |||
282ec27869 | |||
032be64495 | |||
f34ce45549 | |||
ca33627af0 | |||
e658bc3af6 | |||
4fe5547118 | |||
78bacf3869 | |||
6e9e98e069 | |||
f54f0cc04e | |||
77c618aef2 | |||
fb13517a7d | |||
c3735f3945 | |||
5629a294df | |||
af8f8b7a0a | |||
4b8edfac37 | |||
e2b2a61bb2 | |||
ad0abb07be | |||
9c37f5360c | |||
5f3fcb4074 | |||
f225c3b2d1 | |||
58aed131ef | |||
c7cfd59860 | |||
fe7584dfa3 | |||
10554c6f64 | |||
141abd6f76 | |||
2dbcf97f37 | |||
819343e440 | |||
9e02d692f4 | |||
|
cd5d09ccf0 |
22
.devcontainer/Dockerfile
Normal file
22
.devcontainer/Dockerfile
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
FROM python:3.11-buster AS builder
|
||||||
|
|
||||||
|
|
||||||
|
COPY requirements.txt /requirements.txt
|
||||||
|
COPY dev-reqs.txt /dev-reqs.txt
|
||||||
|
RUN pip install --user -r dev-reqs.txt
|
||||||
|
|
||||||
|
|
||||||
|
FROM python:3.11-slim
|
||||||
|
|
||||||
|
|
||||||
|
COPY --from=builder /root/.local /root/.local
|
||||||
|
|
||||||
|
|
||||||
|
ENV MPLBACKEND=Agg
|
||||||
|
|
||||||
|
ENV DISCORD=NTMyMDQ1MjAwODIzMDI1NjY2.XDQftA.Px-arL5wDMB4XKcoPOS1r4gCGmA
|
||||||
|
ENV MARKETDATA=a01mVUZ4cW1sUUFOVWlEZ3NNTHFNeHYzS2diUUhTUVJZbzNxVVEwTUxVMD0
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# CMD [ "python", "./bot.py" ]
|
26
.devcontainer/devcontainer.json
Normal file
26
.devcontainer/devcontainer.json
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
// For format details, see https://aka.ms/devcontainer.json. For config options, see the README at:
|
||||||
|
// https://github.com/microsoft/vscode-dev-containers/tree/v0.191.0/containers/docker-existing-dockerfile
|
||||||
|
{
|
||||||
|
"name": "DockerDev",
|
||||||
|
// Sets the run context to one level up instead of the .devcontainer folder.
|
||||||
|
"context": "..",
|
||||||
|
// Update the 'dockerFile' property if you aren't using the standard 'Dockerfile' filename.
|
||||||
|
"dockerFile": "Dockerfile",
|
||||||
|
// Set *default* container specific settings.json values on container create.
|
||||||
|
"settings": {},
|
||||||
|
// Add the IDs of extensions you want installed when the container is created.
|
||||||
|
"extensions": [
|
||||||
|
"ms-python.python",
|
||||||
|
"ms-azuretools.vscode-docker"
|
||||||
|
]
|
||||||
|
// Use 'forwardPorts' to make a list of ports inside the container available locally.
|
||||||
|
// "forwardPorts": [],
|
||||||
|
// Uncomment the next line to run commands after the container is created - for example installing curl.
|
||||||
|
// "postCreateCommand": "apt-get update && apt-get install -y curl",
|
||||||
|
// Uncomment when using a ptrace-based debugger like C++, Go, and Rust
|
||||||
|
// "runArgs": [ "--cap-add=SYS_PTRACE", "--security-opt", "seccomp=unconfined" ],
|
||||||
|
// Uncomment to use the Docker CLI from inside the container. See https://aka.ms/vscode-remote/samples/docker-from-docker.
|
||||||
|
// "mounts": [ "source=/var/run/docker.sock,target=/var/run/docker.sock,type=bind" ],
|
||||||
|
// Uncomment to connect as a non-root user if you've added one. See https://aka.ms/vscode-remote/containers/non-root.
|
||||||
|
// "remoteUser": "vscode"
|
||||||
|
}
|
5
.gitignore
vendored
5
.gitignore
vendored
@ -1,2 +1,3 @@
|
|||||||
.vscode/settings.json
|
__pycache__
|
||||||
__pycache__/functions.cpython-38.pyc
|
.mypy_cache
|
||||||
|
nextcord.log
|
34
.gitlab-ci.yml
Normal file
34
.gitlab-ci.yml
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
black:
|
||||||
|
stage: .pre
|
||||||
|
image: registry.gitlab.com/pipeline-components/black:latest
|
||||||
|
script:
|
||||||
|
- black --check --verbose -- .
|
||||||
|
|
||||||
|
|
||||||
|
build:master:
|
||||||
|
stage: build
|
||||||
|
image:
|
||||||
|
name: gcr.io/kaniko-project/executor:v1.9.0-debug
|
||||||
|
entrypoint: [""]
|
||||||
|
script:
|
||||||
|
- /kaniko/executor
|
||||||
|
--context "${CI_PROJECT_DIR}"
|
||||||
|
--dockerfile "${CI_PROJECT_DIR}/Dockerfile"
|
||||||
|
--destination "${CI_REGISTRY_IMAGE}:latest"
|
||||||
|
rules:
|
||||||
|
- if: '$CI_COMMIT_BRANCH == "master"'
|
||||||
|
|
||||||
|
|
||||||
|
build:branch:
|
||||||
|
stage: build
|
||||||
|
image:
|
||||||
|
name: gcr.io/kaniko-project/executor:v1.9.0-debug
|
||||||
|
entrypoint: [""]
|
||||||
|
script:
|
||||||
|
- /kaniko/executor
|
||||||
|
--context "${CI_PROJECT_DIR}"
|
||||||
|
--dockerfile "${CI_PROJECT_DIR}/Dockerfile"
|
||||||
|
--destination "${CI_REGISTRY_IMAGE}:${CI_COMMIT_SHORT_SHA}"
|
||||||
|
--destination "${CI_REGISTRY_IMAGE}:${CI_COMMIT_BRANCH}"
|
||||||
|
rules:
|
||||||
|
- if: '$CI_COMMIT_BRANCH != "master"'
|
12
.vscode/launch.json
vendored
Normal file
12
.vscode/launch.json
vendored
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
{
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"name": "Discord Bot",
|
||||||
|
"type": "python",
|
||||||
|
"request": "launch",
|
||||||
|
"program": "bot.py",
|
||||||
|
"console": "integratedTerminal",
|
||||||
|
"python": "python3.11"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
5
.vscode/settings.json
vendored
Normal file
5
.vscode/settings.json
vendored
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"python.formatting.provider": "black",
|
||||||
|
"python.linting.mypyEnabled": true,
|
||||||
|
"python.linting.flake8Enabled": true,
|
||||||
|
}
|
65
D_info.py
Normal file
65
D_info.py
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
"""Functions and Info specific to the discord Bot
|
||||||
|
"""
|
||||||
|
|
||||||
|
import re
|
||||||
|
|
||||||
|
import requests as r
|
||||||
|
|
||||||
|
|
||||||
|
class D_info:
|
||||||
|
license = re.sub(
|
||||||
|
r"\b\n",
|
||||||
|
" ",
|
||||||
|
r.get("https://gitlab.com/simple-stock-bots/simple-discord-stock-bot/-/raw/master/LICENSE").text,
|
||||||
|
)
|
||||||
|
|
||||||
|
help_text = """
|
||||||
|
Thanks for using this bot, consider supporting it by [buying me a beer.](https://www.buymeacoffee.com/Anson)
|
||||||
|
|
||||||
|
If you are interested in stock market data, or want to host your own bot, be sure to use my affiliate link so that the bot can stay free: [marketdata.app](https://dashboard.marketdata.app/marketdata/aff/go/misterbiggs?keyword=discord)
|
||||||
|
|
||||||
|
Keep up with the latest news for the bot in its discord Channel: https://t.me/simplestockbotnews
|
||||||
|
|
||||||
|
Full documentation on using and running your own stock bot can be found on the bots [docs.](https://docs.simplestockbot.com)
|
||||||
|
|
||||||
|
The bot detects _"Symbols"_ using either one `$` or two `$$` dollar signs before the symbol. One dollar sign is for a stock market ticker, while two is for a cryptocurrency coin. `/chart $$eth` would return a chart of the past month of data for Ethereum, while `/dividend $psec` returns dividend information for Prospect Capital stock.
|
||||||
|
|
||||||
|
Simply calling a symbol in any message that the bot can see will also return the price. So a message like: `I wonder if $$btc will go to the Moon now that $tsla accepts it as payment` would return the current price for both Bitcoin and Tesla.
|
||||||
|
|
||||||
|
**Commands**
|
||||||
|
- `/donate [amount in USD]` to donate. 🎗️
|
||||||
|
- `/intra $[symbol]` Plot of the stocks movement since the last market open. 📈
|
||||||
|
- `/chart $[symbol]` Plot of the stocks movement for the past 1 month. 📊
|
||||||
|
- `/trending` Trending Stocks and Cryptos. 💬
|
||||||
|
- `/help` Get some help using the bot. 🆘
|
||||||
|
|
||||||
|
**Inline Features**
|
||||||
|
You can type @SimpleStockBot `[search]` in any chat or direct message to search for the stock bots full list of stock and crypto symbols and return the price. Then once you select the ticker want the bot will send a message as you in that chat with the latest stock price. Prices may be delayed by up to an hour.
|
||||||
|
|
||||||
|
Market data is provided by [marketdata.app](https://dashboard.marketdata.app/marketdata/aff/go/misterbiggs?keyword=discord)
|
||||||
|
|
||||||
|
If you believe the bot is not behaving properly run `/status` or [get in touch](https://docs.simplestockbot.com/contact).
|
||||||
|
"""
|
||||||
|
|
||||||
|
donate_text = """
|
||||||
|
Simple Stock Bot is run entirely on donations[.](https://www.buymeacoffee.com/Anson)
|
||||||
|
All donations go directly towards paying for servers, and market data is provided by
|
||||||
|
[marketdata.app](https://dashboard.marketdata.app/marketdata/aff/go/misterbiggs?keyword=discord).
|
||||||
|
|
||||||
|
The easiest way to donate is to run the `/donate [amount in USD]` command with US dollars you would like to donate.
|
||||||
|
|
||||||
|
Example: `/donate 2` would donate 2 USD.
|
||||||
|
|
||||||
|
An alternative way to donate is through https://www.buymeacoffee.com/Anson which requires no account and accepts Paypal or Credit card.
|
||||||
|
If you have any questions see the [website](https://docs.simplestockbot.com)
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
commands = """ # Not used by the bot but for updating commands with BotFather
|
||||||
|
donate - Donate to the bot 🎗️
|
||||||
|
help - Get some help using the bot. 🆘
|
||||||
|
trending - Trending Stocks and Cryptos. 💬
|
||||||
|
intra - $[symbol] Plot since the last market open. 📈
|
||||||
|
chart - $[chart] Plot of the past month. 📊
|
||||||
|
"""
|
17
Dockerfile
17
Dockerfile
@ -1,8 +1,17 @@
|
|||||||
FROM python:3.8-buster
|
FROM python:3.11-buster AS builder
|
||||||
|
|
||||||
|
|
||||||
|
COPY requirements.txt /requirements.txt
|
||||||
|
RUN pip install --user -r requirements.txt
|
||||||
|
|
||||||
|
|
||||||
|
FROM python:3.11-slim
|
||||||
|
|
||||||
|
ENV MPLBACKEND=Agg
|
||||||
|
|
||||||
|
COPY --from=builder /root/.local /root/.local
|
||||||
|
|
||||||
COPY requirements.txt ./
|
|
||||||
RUN pip install --no-cache-dir -r requirements.txt
|
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
CMD [ "python", "./bot.py" ]
|
CMD [ "python", "./bot.py" ]
|
194
LICENSE
194
LICENSE
@ -1,173 +1,21 @@
|
|||||||
## creative commons
|
MIT License
|
||||||
|
|
||||||
# Attribution-ShareAlike 4.0 International
|
Copyright (c) 2019 Anson Biggs
|
||||||
|
|
||||||
Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
### Using Creative Commons Public Licenses
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
* __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors).
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
* __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees).
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
## Creative Commons Attribution-ShareAlike 4.0 International Public License
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
### Section 1 – Definitions.
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
|
SOFTWARE.
|
||||||
|
|
||||||
b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
|
|
||||||
|
|
||||||
c. __BY-SA Compatible License__ means a license listed at [creativecommons.org/compatiblelicenses](http://creativecommons.org/compatiblelicenses), approved by Creative Commons as essentially the equivalent of this Public License.
|
|
||||||
|
|
||||||
d. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
|
|
||||||
|
|
||||||
e. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
|
|
||||||
|
|
||||||
f. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
|
|
||||||
|
|
||||||
g. __License Elements__ means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution and ShareAlike.
|
|
||||||
|
|
||||||
h. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
|
|
||||||
|
|
||||||
i. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
|
|
||||||
|
|
||||||
j. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
|
|
||||||
|
|
||||||
k. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
|
|
||||||
|
|
||||||
l. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
|
|
||||||
|
|
||||||
m. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
|
|
||||||
|
|
||||||
### Section 2 – Scope.
|
|
||||||
|
|
||||||
a. ___License grant.___
|
|
||||||
|
|
||||||
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
|
|
||||||
|
|
||||||
A. reproduce and Share the Licensed Material, in whole or in part; and
|
|
||||||
|
|
||||||
B. produce, reproduce, and Share Adapted Material.
|
|
||||||
|
|
||||||
2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
|
|
||||||
|
|
||||||
3. __Term.__ The term of this Public License is specified in Section 6(a).
|
|
||||||
|
|
||||||
4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
|
|
||||||
|
|
||||||
5. __Downstream recipients.__
|
|
||||||
|
|
||||||
A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
|
|
||||||
|
|
||||||
B. __Additional offer from the Licensor – Adapted Material.__ Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply.
|
|
||||||
|
|
||||||
C. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
|
|
||||||
|
|
||||||
6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
|
|
||||||
|
|
||||||
b. ___Other rights.___
|
|
||||||
|
|
||||||
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
|
|
||||||
|
|
||||||
2. Patent and trademark rights are not licensed under this Public License.
|
|
||||||
|
|
||||||
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties.
|
|
||||||
|
|
||||||
### Section 3 – License Conditions.
|
|
||||||
|
|
||||||
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
|
|
||||||
|
|
||||||
a. ___Attribution.___
|
|
||||||
|
|
||||||
1. If You Share the Licensed Material (including in modified form), You must:
|
|
||||||
|
|
||||||
A. retain the following if it is supplied by the Licensor with the Licensed Material:
|
|
||||||
|
|
||||||
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
|
|
||||||
|
|
||||||
ii. a copyright notice;
|
|
||||||
|
|
||||||
iii. a notice that refers to this Public License;
|
|
||||||
|
|
||||||
iv. a notice that refers to the disclaimer of warranties;
|
|
||||||
|
|
||||||
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
|
|
||||||
|
|
||||||
B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
|
|
||||||
|
|
||||||
C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
|
|
||||||
|
|
||||||
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
|
|
||||||
|
|
||||||
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
|
|
||||||
|
|
||||||
b. ___ShareAlike.___
|
|
||||||
|
|
||||||
In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.
|
|
||||||
|
|
||||||
1. The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License.
|
|
||||||
|
|
||||||
2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.
|
|
||||||
|
|
||||||
3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.
|
|
||||||
|
|
||||||
### Section 4 – Sui Generis Database Rights.
|
|
||||||
|
|
||||||
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
|
|
||||||
|
|
||||||
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database;
|
|
||||||
|
|
||||||
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and
|
|
||||||
|
|
||||||
c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
|
|
||||||
|
|
||||||
For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
|
|
||||||
|
|
||||||
### Section 5 – Disclaimer of Warranties and Limitation of Liability.
|
|
||||||
|
|
||||||
a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__
|
|
||||||
|
|
||||||
b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__
|
|
||||||
|
|
||||||
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
|
|
||||||
|
|
||||||
### Section 6 – Term and Termination.
|
|
||||||
|
|
||||||
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
|
|
||||||
|
|
||||||
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
|
|
||||||
|
|
||||||
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
|
|
||||||
|
|
||||||
2. upon express reinstatement by the Licensor.
|
|
||||||
|
|
||||||
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
|
|
||||||
|
|
||||||
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
|
|
||||||
|
|
||||||
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
|
|
||||||
|
|
||||||
### Section 7 – Other Terms and Conditions.
|
|
||||||
|
|
||||||
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
|
|
||||||
|
|
||||||
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
|
|
||||||
|
|
||||||
### Section 8 – Interpretation.
|
|
||||||
|
|
||||||
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
|
|
||||||
|
|
||||||
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
|
|
||||||
|
|
||||||
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
|
|
||||||
|
|
||||||
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
|
|
||||||
|
|
||||||
> Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” The text of the Creative Commons public licenses is dedicated to the public domain under the [CC0 Public Domain Dedication](https://creativecommons.org/publicdomain/zero/1.0/legalcode). Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
|
|
||||||
>
|
|
||||||
> Creative Commons may be contacted at creativecommons.org.
|
|
||||||
|
263
MarketData.py
Normal file
263
MarketData.py
Normal file
@ -0,0 +1,263 @@
|
|||||||
|
import datetime as dt
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from typing import Dict
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
import pytz
|
||||||
|
import requests as r
|
||||||
|
import schedule
|
||||||
|
|
||||||
|
from Symbol import Stock
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class MarketData:
|
||||||
|
"""
|
||||||
|
Functions for finding stock market information about symbols from MarkData.app
|
||||||
|
"""
|
||||||
|
|
||||||
|
SYMBOL_REGEX = "[$]([a-zA-Z]{1,4})"
|
||||||
|
|
||||||
|
charts: Dict[Stock, pd.DataFrame] = {}
|
||||||
|
|
||||||
|
openTime = dt.time(hour=9, minute=30, second=0)
|
||||||
|
marketTimeZone = pytz.timezone("US/Eastern")
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
"""Creates a Symbol Object
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
MARKETDATA_TOKEN : str
|
||||||
|
MarketData.app API Token
|
||||||
|
"""
|
||||||
|
|
||||||
|
try:
|
||||||
|
self.MARKETDATA_TOKEN = os.environ["MARKETDATA"]
|
||||||
|
|
||||||
|
if self.MARKETDATA_TOKEN == "TOKEN":
|
||||||
|
self.MARKETDATA_TOKEN = ""
|
||||||
|
except KeyError:
|
||||||
|
self.MARKETDATA_TOKEN = ""
|
||||||
|
log.warning("Starting without an MarketData.app Token will not allow you to get market data!")
|
||||||
|
log.warning("Use this affiliate link so that the bot can stay free:")
|
||||||
|
log.warning("https://dashboard.marketdata.app/marketdata/aff/go/misterbiggs?keyword=repo")
|
||||||
|
|
||||||
|
if self.MARKETDATA_TOKEN != "":
|
||||||
|
schedule.every().day.do(self.clear_charts)
|
||||||
|
|
||||||
|
def get(self, endpoint, params: dict = {}, timeout=10) -> dict:
|
||||||
|
url = "https://api.marketdata.app/v1/" + endpoint
|
||||||
|
|
||||||
|
# set token param if it wasn't passed.
|
||||||
|
params["token"] = self.MARKETDATA_TOKEN
|
||||||
|
|
||||||
|
# Undocumented query variable that ensures bot usage can be
|
||||||
|
# monitored even if someone doesn't make it through an affiliate link.
|
||||||
|
params["application"] = "simplestockbot"
|
||||||
|
|
||||||
|
resp = r.get(url, params=params, timeout=timeout)
|
||||||
|
|
||||||
|
# Make sure API returned a proper status code
|
||||||
|
try:
|
||||||
|
resp.raise_for_status()
|
||||||
|
except r.exceptions.HTTPError as e:
|
||||||
|
logging.error(e)
|
||||||
|
return {}
|
||||||
|
|
||||||
|
# Make sure API returned valid JSON
|
||||||
|
try:
|
||||||
|
resp_json = resp.json()
|
||||||
|
|
||||||
|
match resp_json["s"]:
|
||||||
|
case "ok":
|
||||||
|
return resp_json
|
||||||
|
case "no_data":
|
||||||
|
return resp_json
|
||||||
|
case "error":
|
||||||
|
logging.error("MarketData Error:\n" + resp_json["errmsg"])
|
||||||
|
return {}
|
||||||
|
|
||||||
|
except r.exceptions.JSONDecodeError as e:
|
||||||
|
logging.error(e)
|
||||||
|
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def clear_charts(self) -> None:
|
||||||
|
"""
|
||||||
|
Clears cache of chart data.
|
||||||
|
Charts are cached so that only 1 API call per 24 hours is needed since the
|
||||||
|
chart data is expensive and a large download.
|
||||||
|
"""
|
||||||
|
self.charts = {}
|
||||||
|
|
||||||
|
def status(self) -> str:
|
||||||
|
# TODO: At the moment this API is poorly documented, this function likely needs to be revisited later.
|
||||||
|
|
||||||
|
try:
|
||||||
|
status = r.get(
|
||||||
|
"https://stats.uptimerobot.com/api/getMonitorList/6Kv3zIow0A",
|
||||||
|
timeout=5,
|
||||||
|
)
|
||||||
|
status.raise_for_status()
|
||||||
|
except r.HTTPError:
|
||||||
|
return f"API returned an HTTP error code {status.status_code} in {status.elapsed.total_seconds()} Seconds."
|
||||||
|
except r.Timeout:
|
||||||
|
return "API timed out before it was able to give status. This is likely due to a surge in usage or a complete outage."
|
||||||
|
|
||||||
|
statusJSON = status.json()
|
||||||
|
|
||||||
|
if statusJSON["status"] == "ok":
|
||||||
|
return (
|
||||||
|
f"CoinGecko API responded that it was OK with a {status.status_code} in {status.elapsed.total_seconds()} Seconds."
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
return f"MarketData.app is currently reporting the following status: {statusJSON['status']}"
|
||||||
|
|
||||||
|
def price_reply(self, symbol: Stock) -> str:
|
||||||
|
"""Returns price movement of Stock for the last market day, or after hours.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
symbol : Stock
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
str
|
||||||
|
Formatted markdown
|
||||||
|
"""
|
||||||
|
|
||||||
|
if quoteResp := self.get(f"stocks/quotes/{symbol}/"):
|
||||||
|
price = round(quoteResp["last"][0], 2)
|
||||||
|
changePercent = round(quoteResp["changepct"][0], 2)
|
||||||
|
|
||||||
|
message = f"The current price of {symbol.name} is ${price} and "
|
||||||
|
|
||||||
|
if changePercent > 0.0:
|
||||||
|
message += f"is currently up {changePercent}% for the day."
|
||||||
|
elif changePercent < 0.0:
|
||||||
|
message += f"is currently down {changePercent}% for the day."
|
||||||
|
else:
|
||||||
|
message += "hasn't shown any movement for the day."
|
||||||
|
|
||||||
|
return message
|
||||||
|
else:
|
||||||
|
return f"Getting a quote for {symbol} encountered an error."
|
||||||
|
|
||||||
|
def spark_reply(self, symbol: Stock) -> str:
|
||||||
|
if quoteResp := self.get(f"stocks/quotes/{symbol}/"):
|
||||||
|
changePercent = round(quoteResp["changepct"][0], 2)
|
||||||
|
return f"`{symbol.tag}`: {changePercent}%"
|
||||||
|
else:
|
||||||
|
logging.warning(f"{symbol} did not have 'changepct' field.")
|
||||||
|
return f"`{symbol.tag}`"
|
||||||
|
|
||||||
|
def intra_reply(self, symbol: Stock) -> pd.DataFrame:
|
||||||
|
"""Returns price data for a symbol of the past month up until the previous trading days close.
|
||||||
|
Also caches multiple requests made in the same day.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
symbol : str
|
||||||
|
Stock symbol.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
pd.DataFrame
|
||||||
|
Returns a timeseries dataframe with high, low, and volume data if its available. Otherwise returns empty pd.DataFrame.
|
||||||
|
"""
|
||||||
|
schedule.run_pending()
|
||||||
|
|
||||||
|
try:
|
||||||
|
return self.charts[symbol.id.upper()]
|
||||||
|
except KeyError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
resolution = "15" # minutes
|
||||||
|
now = dt.datetime.now(self.marketTimeZone)
|
||||||
|
|
||||||
|
if self.openTime < now.time():
|
||||||
|
startTime = now.replace(hour=9, minute=30)
|
||||||
|
else:
|
||||||
|
startTime = now - dt.timedelta(days=1)
|
||||||
|
|
||||||
|
if data := self.get(
|
||||||
|
f"stocks/candles/{resolution}/{symbol}",
|
||||||
|
params={"from": startTime.timestamp(), "to": now.timestamp(), "extended": True},
|
||||||
|
):
|
||||||
|
data.pop("s")
|
||||||
|
df = pd.DataFrame(data)
|
||||||
|
df["t"] = pd.to_datetime(df["t"], unit="s", utc=True)
|
||||||
|
df.set_index("t", inplace=True)
|
||||||
|
|
||||||
|
df.rename(
|
||||||
|
columns={
|
||||||
|
"o": "Open",
|
||||||
|
"h": "High",
|
||||||
|
"l": "Low",
|
||||||
|
"c": "Close",
|
||||||
|
"v": "Volume",
|
||||||
|
},
|
||||||
|
inplace=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.charts[symbol.id.upper()] = df
|
||||||
|
return df
|
||||||
|
|
||||||
|
return pd.DataFrame()
|
||||||
|
|
||||||
|
def chart_reply(self, symbol: Stock) -> pd.DataFrame:
|
||||||
|
"""Returns price data for a symbol of the past month up until the previous trading days close.
|
||||||
|
Also caches multiple requests made in the same day.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
symbol : str
|
||||||
|
Stock symbol.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
pd.DataFrame
|
||||||
|
Returns a timeseries dataframe with high, low, and volume data if its available. Otherwise returns empty pd.DataFrame.
|
||||||
|
"""
|
||||||
|
schedule.run_pending()
|
||||||
|
|
||||||
|
try:
|
||||||
|
return self.charts[symbol.id.upper()]
|
||||||
|
except KeyError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
to_date = dt.datetime.today().strftime("%Y-%m-%d")
|
||||||
|
from_date = (dt.datetime.today() - dt.timedelta(days=30)).strftime("%Y-%m-%d")
|
||||||
|
resultion = "daily"
|
||||||
|
|
||||||
|
if data := self.get(
|
||||||
|
f"stocks/candles/{resultion}/{symbol}",
|
||||||
|
params={
|
||||||
|
"from": from_date,
|
||||||
|
"to": to_date,
|
||||||
|
},
|
||||||
|
):
|
||||||
|
data.pop("s")
|
||||||
|
|
||||||
|
df = pd.DataFrame(data)
|
||||||
|
df["t"] = pd.to_datetime(df["t"], unit="s")
|
||||||
|
df.set_index("t", inplace=True)
|
||||||
|
|
||||||
|
df.rename(
|
||||||
|
columns={
|
||||||
|
"o": "Open",
|
||||||
|
"h": "High",
|
||||||
|
"l": "Low",
|
||||||
|
"c": "Close",
|
||||||
|
"v": "Volume",
|
||||||
|
},
|
||||||
|
inplace=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.charts[symbol.id.upper()] = df
|
||||||
|
return df
|
||||||
|
|
||||||
|
return pd.DataFrame()
|
175
README.md
175
README.md
@ -1,176 +1,33 @@
|
|||||||
<div align="center">
|
# Simple Discord Stock Bot
|
||||||
<p align="center">
|
|
||||||
<a href="" rel="noopener">
|
|
||||||
<img width=200px height=200px src="https://assets.gitlab-static.net/uploads/-/system/project/avatar/10273693/logo.jpg" alt="Simple Discord Stock Bot"></a>
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<h3 align="center">Simple Discord Stock Bot</h3>
|
|
||||||
|
|
||||||
<a href="https://www.buymeacoffee.com/Anson" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Beer" style="height: 51px !important;width: 217px !important;" ></a>
|
<a href="https://www.buymeacoffee.com/Anson" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Beer" style="height: 51px !important;width: 217px !important;" ></a>
|
||||||
|
|
||||||
[]()
|
[]()
|
||||||
[]()
|
[]()
|
||||||
[](/LICENSE)
|
[](/LICENSE)
|
||||||
|
[](https://ansonbiggs.com)
|
||||||
|
|
||||||
</div>
|
## Docs
|
||||||
|
|
||||||
---
|
https://docs.simplestockbot.com/
|
||||||
|
|
||||||
<p align="center"> Discord Bot 🤖 that provides Stock Market information.
|
## Usage
|
||||||
<br>
|
|
||||||
</p>
|
|
||||||
|
|
||||||
## 📝 Table of Contents
|
https://docs.simplestockbot.com/commands/
|
||||||
|
|
||||||
- [About](#about)
|
## Donate
|
||||||
- [How it works](#working)
|
|
||||||
- [Usage](#usage)
|
|
||||||
- [Getting Started](#getting_started)
|
|
||||||
- [Deploying your own bot](#deployment)
|
|
||||||
- [Built Using](#built_using)
|
|
||||||
- [Contributing](../CONTRIBUTING.md)
|
|
||||||
- [author](#author)
|
|
||||||
- [Acknowledgments](#acknowledgement)
|
|
||||||
|
|
||||||
## 🧐 About <a name = "about"></a>
|
Simple Stock Bot is run entirely on donations, and costs about $420 a year to run. All donations go directly towards paying for servers, and premium market data provided by [marketdata.app](https://dashboard.marketdata.app/marketdata/aff/go/misterbiggs?keyword=repo).
|
||||||
|
|
||||||
This bot aims to be as simple as possible while providing all the information you need on the stock market. The motivation of this bot is to provide similar stock market functionality that the Google Assistant provided in [Google Allo](https://gcemetery.co/google-allo/) before the project was sunset.
|
The best way to donate is through [Buy Me A Coffee](https://www.buymeacoffee.com/Anson) which accepts Paypal or Credit card.
|
||||||
|
|
||||||
## 💭 How it works <a name = "working"></a>
|
If you have any questions get in [touch.](contact.md)
|
||||||
|
|
||||||
This bot works by using the [IEX API 2.0](https://iexcloud.io/docs/api/). Using various endpoints provided by the API, the bot can take either take commands from users or check any messages for stock symbols as detailed in [Usage](#usage).
|
## Other Ways to Help:
|
||||||
|
|
||||||
## 🎈 Usage <a name = "usage"></a>
|
- Follow me on [twitter](https://twitter.com/AnsonBiggs)
|
||||||
|
- Contribute to the project on [GitLab](https://gitlab.com/simple-stock-bots) or just leave a star
|
||||||
### Basic Usage
|
- Using my referral links to host your own Bot
|
||||||
|
- [DigitalOcean](https://m.do.co/c/6b5df7ef55b6)
|
||||||
The simplest way to use the bot is just by sending a message either as a direct message or in a group chat with the bot active. The bot will search every message for text with a dollar sign followed by a stock symbol, and it will return the full name of the company and the current trading price.
|
- [marketdata.app](https://dashboard.marketdata.app/marketdata/aff/go/misterbiggs?keyword=repo)
|
||||||
|
|
||||||
```
|
|
||||||
$tsla
|
|
||||||
```
|
|
||||||
|
|
||||||
The symbols can be anywhere in the message, and you can post as many as you like so commands such as:
|
|
||||||
|
|
||||||
```
|
|
||||||
I wonder if $aapl is down as much as $msft is today.
|
|
||||||
```
|
|
||||||
|
|
||||||
would return the stock price of both Apple and Microsoft like so:
|
|
||||||
|
|
||||||
```
|
|
||||||
The current stock price of Microsoft Corp. is $131.4, the stock is currently up 2.8%
|
|
||||||
|
|
||||||
The current stock price of Apple, Inc. is $190.15, the stock is currently up 2.66%
|
|
||||||
```
|
|
||||||
|
|
||||||
### /search `query`
|
|
||||||
|
|
||||||
This command takes any query and searches all tickers and company names that the bot supports and returns matches. The bot uses IEX Cloud so market information is limited to what they support, which is still about ~15,000 tickers so anything in a United States exchange should have support.
|
|
||||||
|
|
||||||
### /dividend \$ticker
|
|
||||||
|
|
||||||
To get information about the dividend of a stock type `/dividend` followed by any text that has symbols with a dollar sign in front of them. So, the following command:
|
|
||||||
|
|
||||||
```
|
|
||||||
/dividend $psec
|
|
||||||
```
|
|
||||||
|
|
||||||
Would return information about Prospect Capitals dividend:
|
|
||||||
|
|
||||||
```
|
|
||||||
Prospect Capital Corp. Declares June 2019 Dividend of $0.06 Per Share
|
|
||||||
The dividend is in: 38 Days 3 Hours 53 Minutes 22 Seconds.
|
|
||||||
```
|
|
||||||
|
|
||||||
💡 you can also call the dividend command using /div
|
|
||||||
|
|
||||||
### /news \$ticker
|
|
||||||
|
|
||||||
To get the latest news about a stock symbol use `/news` followed by any text that has symbols with a dollar sign in front of them. So, the following command:
|
|
||||||
|
|
||||||
```
|
|
||||||
/news $psec
|
|
||||||
```
|
|
||||||
|
|
||||||
Would return news for Prospect Capital:
|
|
||||||
|
|
||||||
News for PSEC:
|
|
||||||
|
|
||||||
[Yield-Starved Investors Still Accumulating BDCs Paying More Than 10% Annually](https://cloud.iexapis.com/v1/news/article/d994b8b5-9fbf-4ceb-afbe-e6defcfc6352)
|
|
||||||
|
|
||||||
[Assessing Main Street Capital's Results For Q1 2019 (Includes Updated Price Target And Investment Ratings Analysis)](https://cloud.iexapis.com/v1/news/article/e60899bc-5230-4388-a609-fc2b8736a7d4)
|
|
||||||
|
|
||||||
[Fully Assessing Prospect Capital's Fiscal Q3 2019 (Includes Current Recommendation And Price Target)](https://cloud.iexapis.com/v1/news/article/08881160-72c5-4f5d-885b-1751187d24eb)
|
|
||||||
|
|
||||||
### /info \$ticker
|
|
||||||
|
|
||||||
To get information about a stock type `/info` followed by any text that has symbols with a dollar sign in front of them. So, the following command:
|
|
||||||
|
|
||||||
```
|
|
||||||
/info $psec
|
|
||||||
```
|
|
||||||
|
|
||||||
Would return information about Prospect Capitals:
|
|
||||||
|
|
||||||
Company Name: [Prospect Capital Corp.](http://www.prospectstreet.com/)
|
|
||||||
Industry: Investment Managers
|
|
||||||
Sector: Finance
|
|
||||||
CEO: John Francis Barry
|
|
||||||
Description: Prospect Capital Corp. is a business development company, which engages in lending to and investing in private businesses. It also involves in generating current income and long-term capital appreciation through debt and equity investments. The company was founded on April 13, 2004 and is headquartered in New York, NY.
|
|
||||||
|
|
||||||
## 🏁 Getting Started <a name = "getting_started"></a>
|
|
||||||
|
|
||||||
You can either choose to use the hosted version of the bot by [clicking here](https://discordapp.com/oauth2/authorize?client_id=532045200823025666&permissions=2048&scope=bot) or you can host your own bot with the instructions below.
|
|
||||||
|
|
||||||
### Self Hosted Bot
|
|
||||||
|
|
||||||
These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See [deployment](#deployment) for notes on how to deploy the project on a live system.
|
|
||||||
|
|
||||||
### Prerequisites
|
|
||||||
|
|
||||||
This project runs neatly in a docker container, so all that you need to run it yourself is [Docker](https://hub.docker.com/?overlay=onboarding) installed on your system.
|
|
||||||
|
|
||||||
You will also need a Discord API key which can be obtained [here.](https://discordapp.com/developers/)
|
|
||||||
|
|
||||||
Finally, you will need and IEX Cloud API key. They offer a free tier that should be enough for any private groups, more details [here.](https://iexcloud.io/)
|
|
||||||
|
|
||||||
### Installing
|
|
||||||
|
|
||||||
Once Docker is installed and you have your API keys for Discord and IEX Cloud getting the bot running on any platform is extremely easy.
|
|
||||||
|
|
||||||
Download or clone the repository to your machine and open a terminal in the project and build the Docker container.
|
|
||||||
|
|
||||||
```
|
|
||||||
docker build -t simple-discord-bot .
|
|
||||||
```
|
|
||||||
|
|
||||||
Then run the bot using your API keys.
|
|
||||||
|
|
||||||
```
|
|
||||||
docker run --detach \
|
|
||||||
-e discord=DISCORD_TOKEN \
|
|
||||||
-e IEX=IEX_TOKEN \
|
|
||||||
simple-discord-bot
|
|
||||||
```
|
|
||||||
|
|
||||||
Your bot should be running! If you are new to Docker, I would recommend checking out its documentation for full control over your bot.
|
|
||||||
|
|
||||||
## 🚀 Deploying your own bot <a name = "deployment"></a>
|
|
||||||
|
|
||||||
I recommend Digital Ocean for small projects like this because it is straightforward to use and affordable. [Sign up with my referral code, and we both get some free hosting.](https://m.do.co/c/6b5df7ef55b6)
|
|
||||||
|
|
||||||
## ⛏️ Built Using <a name = "built_using"></a>
|
|
||||||
|
|
||||||
- [discord.py](https://github.com/Rapptz/discord.py) - Python Discord API Wrapper
|
|
||||||
- [Digital Ocean](https://www.digitalocean.com/) - IaaS hosting platform
|
|
||||||
|
|
||||||
## ✍️ author <a name = "author"></a>
|
|
||||||
|
|
||||||
- [Anson Biggs](https://blog.ansonbiggs.com/author/anson/) - The one and only
|
|
||||||
|
|
||||||
## 🎉 Acknowledgements <a name = "acknowledgement"></a>
|
|
||||||
|
|
||||||
- Discord for having a great bot API
|
|
||||||
- IEX Cloud for offering a free tier
|
|
||||||
- Viewers like you ♥
|
|
||||||
|
50
Symbol.py
Normal file
50
Symbol.py
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
import pandas as pd
|
||||||
|
import logging
|
||||||
|
|
||||||
|
|
||||||
|
class Symbol:
|
||||||
|
"""
|
||||||
|
symbol: What the user calls it. ie tsla or btc
|
||||||
|
id: What the api expects. ie tsla or bitcoin
|
||||||
|
name: Human readable. ie Tesla or Bitcoin
|
||||||
|
tag: Uppercase tag to call the symbol. ie $TSLA or $$BTC
|
||||||
|
"""
|
||||||
|
|
||||||
|
currency = "usd"
|
||||||
|
pass
|
||||||
|
|
||||||
|
def __init__(self, symbol) -> None:
|
||||||
|
self.symbol = symbol
|
||||||
|
self.id = symbol
|
||||||
|
self.name = symbol
|
||||||
|
self.tag = "$" + symbol
|
||||||
|
|
||||||
|
def __repr__(self) -> str:
|
||||||
|
return f"<{self.__class__.__name__} instance of {self.id} at {id(self)}>"
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return self.id
|
||||||
|
|
||||||
|
|
||||||
|
class Stock(Symbol):
|
||||||
|
"""Stock Market Object. Gets data from MarketData"""
|
||||||
|
|
||||||
|
def __init__(self, symbol: str) -> None:
|
||||||
|
self.symbol = symbol
|
||||||
|
self.id = symbol
|
||||||
|
self.name = "$" + symbol.upper()
|
||||||
|
self.tag = "$" + symbol.lower()
|
||||||
|
|
||||||
|
|
||||||
|
class Coin(Symbol):
|
||||||
|
"""Cryptocurrency Object. Gets data from CoinGecko."""
|
||||||
|
|
||||||
|
def __init__(self, symbol: pd.DataFrame) -> None:
|
||||||
|
if len(symbol) > 1:
|
||||||
|
logging.info(f"Crypto with shared id:\n\t{symbol.id}")
|
||||||
|
symbol = symbol.head(1)
|
||||||
|
|
||||||
|
self.symbol = symbol.symbol.values[0]
|
||||||
|
self.id = symbol.id.values[0]
|
||||||
|
self.name = symbol.name.values[0]
|
||||||
|
self.tag = symbol.type_id.values[0].upper()
|
242
bot.py
242
bot.py
@ -1,78 +1,202 @@
|
|||||||
import discord
|
import datetime
|
||||||
from functions import Symbol
|
import io
|
||||||
|
import logging
|
||||||
import os
|
import os
|
||||||
|
|
||||||
client = discord.Client()
|
import mplfinance as mpf
|
||||||
s = Symbol(os.environ["IEX"])
|
import nextcord
|
||||||
|
from nextcord.ext import commands
|
||||||
|
|
||||||
|
from D_info import D_info
|
||||||
|
from symbol_router import Router
|
||||||
|
|
||||||
|
DISCORD_TOKEN = os.environ["DISCORD"]
|
||||||
|
|
||||||
|
s = Router()
|
||||||
|
d = D_info()
|
||||||
|
|
||||||
|
|
||||||
@client.event
|
intents = nextcord.Intents.default()
|
||||||
|
|
||||||
|
|
||||||
|
client = nextcord.Client(intents=intents)
|
||||||
|
bot = commands.Bot(command_prefix="/", description=d.help_text, intents=intents)
|
||||||
|
|
||||||
|
logger = logging.getLogger("nextcord")
|
||||||
|
logger.setLevel(logging.INFO)
|
||||||
|
handler = logging.FileHandler(filename="nextcord.log", encoding="utf-8", mode="w")
|
||||||
|
handler.setFormatter(logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(message)s"))
|
||||||
|
logger.addHandler(handler)
|
||||||
|
|
||||||
|
|
||||||
|
@bot.event
|
||||||
async def on_ready():
|
async def on_ready():
|
||||||
print("We have logged in as {0.user}".format(client))
|
logging.info("Starting Simple Stock Bot")
|
||||||
|
logging.info(f"Logged in as {bot.user.name} {bot.user.id}")
|
||||||
|
|
||||||
|
|
||||||
@client.event
|
@bot.command()
|
||||||
async def on_message(message):
|
async def status(ctx: commands):
|
||||||
if message.author == client.user:
|
"""Debug command for diagnosing if the bot is experiencing any issues."""
|
||||||
|
logging.warning(f"Status command ran by {ctx.message.author}")
|
||||||
|
message = ""
|
||||||
|
try:
|
||||||
|
message = "Contact MisterBiggs#0465 if you need help.\n"
|
||||||
|
message += s.status(f"Bot recieved your message in: {bot.latency*1000:.4f}ms") + "\n"
|
||||||
|
|
||||||
|
except Exception as ex:
|
||||||
|
logging.critical(ex)
|
||||||
|
message += (
|
||||||
|
f"*\n\nERROR ENCOUNTERED:*\n{ex}\n\n"
|
||||||
|
+ "*The bot encountered an error while attempting to find errors. Please contact the bot admin.*"
|
||||||
|
)
|
||||||
|
await ctx.send(message)
|
||||||
|
|
||||||
|
|
||||||
|
@bot.command()
|
||||||
|
async def license(ctx: commands):
|
||||||
|
"""Returns the bots license agreement."""
|
||||||
|
await ctx.send(d.license)
|
||||||
|
|
||||||
|
|
||||||
|
@bot.command()
|
||||||
|
async def donate(ctx: commands):
|
||||||
|
"""Details on how to support the development and hosting of the bot."""
|
||||||
|
await ctx.send(d.donate_text)
|
||||||
|
|
||||||
|
|
||||||
|
@bot.command()
|
||||||
|
async def search(ctx: commands, *, query: str):
|
||||||
|
"""Search for a stock symbol using either symbol of company name."""
|
||||||
|
results = s.search_symbols(query)
|
||||||
|
if results:
|
||||||
|
reply = "*Search Results:*\n`$ticker: Company Name`\n"
|
||||||
|
for query in results:
|
||||||
|
reply += "`" + query[1] + "`\n"
|
||||||
|
await ctx.send(reply)
|
||||||
|
|
||||||
|
|
||||||
|
@bot.command()
|
||||||
|
async def crypto(ctx: commands, _: str):
|
||||||
|
"""Get the price of a cryptocurrency using in USD."""
|
||||||
|
await ctx.send("Crypto now has native support. Any crypto can be called using two dollar signs: `$$eth` `$$btc` `$$doge`")
|
||||||
|
|
||||||
|
|
||||||
|
@bot.command()
|
||||||
|
async def intra(ctx: commands, sym: str):
|
||||||
|
"""Get a chart for the stocks movement since market open."""
|
||||||
|
symbols = s.find_symbols(sym)
|
||||||
|
|
||||||
|
if len(symbols):
|
||||||
|
symbol = symbols[0]
|
||||||
|
else:
|
||||||
|
await ctx.send("No symbols or coins found.")
|
||||||
return
|
return
|
||||||
|
|
||||||
# Check for dividend command
|
df = s.intra_reply(symbol)
|
||||||
if message.content.startswith("/dividend"):
|
if df.empty:
|
||||||
replies = s.dividend_reply(s.find_symbols(message.content))
|
await ctx.send("Invalid symbol please see `/help` for usage details.")
|
||||||
if replies:
|
return
|
||||||
for reply in replies.items():
|
with ctx.channel.typing():
|
||||||
await message.channel.send(reply[1])
|
buf = io.BytesIO()
|
||||||
else:
|
mpf.plot(
|
||||||
|
df,
|
||||||
|
type="renko",
|
||||||
|
title=f"\n{symbol.name}",
|
||||||
|
volume="volume" in df.keys(),
|
||||||
|
style="yahoo",
|
||||||
|
savefig=dict(fname=buf, dpi=400, bbox_inches="tight"),
|
||||||
|
)
|
||||||
|
|
||||||
await message.channel.send(
|
buf.seek(0)
|
||||||
"Command requires a ticker. See /help for more information."
|
|
||||||
)
|
|
||||||
|
|
||||||
elif message.content.startswith("/news"):
|
# Get price so theres no request lag after the image is sent
|
||||||
replies = s.news_reply(s.find_symbols(message.content))
|
price_reply = s.price_reply([symbol])[0]
|
||||||
if replies:
|
await ctx.send(
|
||||||
for reply in replies.items():
|
file=nextcord.File(
|
||||||
await message.channel.send(reply[1])
|
buf,
|
||||||
else:
|
filename=f"{symbol.name}:intra{datetime.date.today().strftime('%S%M%d%b%Y')}.png",
|
||||||
await message.channel.send(
|
),
|
||||||
"Command requires a ticker. See /help for more information."
|
content=f"\nIntraday chart for {symbol.name} from {df.first_valid_index().strftime('%d %b at %H:%M')} to"
|
||||||
)
|
+ f" {df.last_valid_index().strftime('%d %b at %H:%M')}",
|
||||||
|
)
|
||||||
|
await ctx.send(price_reply)
|
||||||
|
|
||||||
elif message.content.startswith("/info"):
|
|
||||||
replies = s.info_reply(s.find_symbols(message.content))
|
|
||||||
if replies:
|
|
||||||
for reply in replies.items():
|
|
||||||
await message.channel.send(reply[1])
|
|
||||||
else:
|
|
||||||
await message.channel.send(
|
|
||||||
"Command requires a ticker. See /help for more information."
|
|
||||||
)
|
|
||||||
|
|
||||||
elif message.content.startswith("/search"):
|
@bot.command()
|
||||||
queries = s.search_symbols(message.content[7:])[:6]
|
async def chart(ctx: commands, sym: str):
|
||||||
if queries:
|
"""returns a chart of the past month of data for a symbol"""
|
||||||
reply = "*Search Results:*\n`$ticker: Company Name`\n"
|
|
||||||
for query in queries:
|
|
||||||
reply += "`" + query[1] + "`\n"
|
|
||||||
await message.channel.send(reply)
|
|
||||||
|
|
||||||
else:
|
symbols = s.find_symbols(sym)
|
||||||
await message.channel.send(
|
|
||||||
"Command requires a query. See /help for more information."
|
|
||||||
)
|
|
||||||
|
|
||||||
elif message.content.startswith("/help"):
|
if len(symbols):
|
||||||
"""Send link to docs when the command /help is issued."""
|
symbol = symbols[0]
|
||||||
await message.channel.send(s.help_text)
|
|
||||||
|
|
||||||
# If no commands, check for any tickers.
|
|
||||||
else:
|
else:
|
||||||
replies = s.price_reply(s.find_symbols(message.content))
|
await ctx.send("No symbols or coins found.")
|
||||||
if replies:
|
return
|
||||||
for reply in replies.items():
|
|
||||||
await message.channel.send(reply[1])
|
df = s.chart_reply(symbol)
|
||||||
else:
|
if df.empty:
|
||||||
|
await ctx.send("Invalid symbol please see `/help` for usage details.")
|
||||||
|
return
|
||||||
|
with ctx.channel.typing():
|
||||||
|
buf = io.BytesIO()
|
||||||
|
mpf.plot(
|
||||||
|
df,
|
||||||
|
type="candle",
|
||||||
|
title=f"\n{symbol.name}",
|
||||||
|
volume="volume" in df.keys(),
|
||||||
|
style="yahoo",
|
||||||
|
savefig=dict(fname=buf, dpi=400, bbox_inches="tight"),
|
||||||
|
)
|
||||||
|
buf.seek(0)
|
||||||
|
|
||||||
|
# Get price so theres no request lag after the image is sent
|
||||||
|
price_reply = s.price_reply([symbol])[0]
|
||||||
|
await ctx.send(
|
||||||
|
file=nextcord.File(
|
||||||
|
buf,
|
||||||
|
filename=f"{symbol.name}:1M{datetime.date.today().strftime('%d%b%Y')}.png",
|
||||||
|
),
|
||||||
|
content=f"\n1 Month chart for {symbol.name} from {df.first_valid_index().strftime('%d, %b %Y')}"
|
||||||
|
+ f" to {df.last_valid_index().strftime('%d, %b %Y')}",
|
||||||
|
)
|
||||||
|
await ctx.send(price_reply)
|
||||||
|
|
||||||
|
|
||||||
|
@bot.command()
|
||||||
|
async def cap(ctx: commands, sym: str):
|
||||||
|
"""Get the market cap of a symbol"""
|
||||||
|
symbols = s.find_symbols(sym)
|
||||||
|
if symbols:
|
||||||
|
with ctx.channel.typing():
|
||||||
|
for reply in s.cap_reply(symbols):
|
||||||
|
await ctx.send(reply)
|
||||||
|
|
||||||
|
|
||||||
|
@bot.command()
|
||||||
|
async def trending(ctx: commands):
|
||||||
|
"""Get a list of Trending Stocks and Coins"""
|
||||||
|
with ctx.channel.typing():
|
||||||
|
await ctx.send(s.trending())
|
||||||
|
|
||||||
|
|
||||||
|
@bot.event
|
||||||
|
async def on_message(message):
|
||||||
|
if message.author.id == bot.user.id:
|
||||||
|
return
|
||||||
|
if message.content:
|
||||||
|
if message.content[0] == "/":
|
||||||
|
await bot.process_commands(message)
|
||||||
return
|
return
|
||||||
|
|
||||||
|
if "$" in message.content:
|
||||||
|
symbols = s.find_symbols(message.content)
|
||||||
|
|
||||||
client.run(os.environ["DISCORD"])
|
if symbols:
|
||||||
|
for reply in s.price_reply(symbols):
|
||||||
|
await message.channel.send(reply)
|
||||||
|
return
|
||||||
|
|
||||||
|
|
||||||
|
bot.run(DISCORD_TOKEN)
|
||||||
|
367
cg_Crypto.py
Normal file
367
cg_Crypto.py
Normal file
@ -0,0 +1,367 @@
|
|||||||
|
import logging
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
import requests as r
|
||||||
|
import schedule
|
||||||
|
from markdownify import markdownify
|
||||||
|
|
||||||
|
from Symbol import Coin
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class cg_Crypto:
|
||||||
|
"""
|
||||||
|
Functions for finding crypto info
|
||||||
|
"""
|
||||||
|
|
||||||
|
vs_currency = "usd" # simple/supported_vs_currencies for list of options
|
||||||
|
|
||||||
|
trending_cache: List[str] = []
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self.get_symbol_list()
|
||||||
|
schedule.every().day.do(self.get_symbol_list)
|
||||||
|
|
||||||
|
def get(self, endpoint, params: dict = {}, timeout=10) -> dict:
|
||||||
|
url = "https://api.coingecko.com/api/v3" + endpoint
|
||||||
|
resp = r.get(url, params=params, timeout=timeout)
|
||||||
|
# Make sure API returned a proper status code
|
||||||
|
try:
|
||||||
|
resp.raise_for_status()
|
||||||
|
except r.exceptions.HTTPError as e:
|
||||||
|
log.error(e)
|
||||||
|
return {}
|
||||||
|
|
||||||
|
# Make sure API returned valid JSON
|
||||||
|
try:
|
||||||
|
resp_json = resp.json()
|
||||||
|
return resp_json
|
||||||
|
except r.exceptions.JSONDecodeError as e:
|
||||||
|
log.error(e)
|
||||||
|
return {}
|
||||||
|
|
||||||
|
def symbol_id(self, symbol) -> str:
|
||||||
|
try:
|
||||||
|
return self.symbol_list[self.symbol_list["symbol"] == symbol]["id"].values[0]
|
||||||
|
except KeyError:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
def get_symbol_list(self):
|
||||||
|
raw_symbols = self.get("/coins/list")
|
||||||
|
symbols = pd.DataFrame(data=raw_symbols)
|
||||||
|
|
||||||
|
# Removes all binance-peg symbols
|
||||||
|
symbols = symbols[~symbols["id"].str.contains("binance-peg")]
|
||||||
|
|
||||||
|
symbols["description"] = "$$" + symbols["symbol"].str.upper() + ": " + symbols["name"]
|
||||||
|
symbols = symbols[["id", "symbol", "name", "description"]]
|
||||||
|
symbols["type_id"] = "$$" + symbols["symbol"]
|
||||||
|
|
||||||
|
self.symbol_list = symbols
|
||||||
|
|
||||||
|
def status(self) -> str:
|
||||||
|
"""Checks CoinGecko /ping endpoint for API issues.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
str
|
||||||
|
Human readable text on status of CoinGecko API
|
||||||
|
"""
|
||||||
|
status = r.get(
|
||||||
|
"https://api.coingecko.com/api/v3/ping",
|
||||||
|
timeout=5,
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
status.raise_for_status()
|
||||||
|
return (
|
||||||
|
f"CoinGecko API responded that it was OK with a {status.status_code} in {status.elapsed.total_seconds()} Seconds."
|
||||||
|
)
|
||||||
|
except r.HTTPError:
|
||||||
|
return f"CoinGecko API returned an error code {status.status_code} in {status.elapsed.total_seconds()} Seconds."
|
||||||
|
|
||||||
|
def price_reply(self, coin: Coin) -> str:
|
||||||
|
"""Returns current market price or after hours if its available for a given coin symbol.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
symbols : list
|
||||||
|
List of coin symbols.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
Dict[str, str]
|
||||||
|
Each symbol passed in is a key with its value being a human readable
|
||||||
|
markdown formatted string of the symbols price and movement.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if resp := self.get(
|
||||||
|
"/simple/price",
|
||||||
|
params={
|
||||||
|
"ids": coin.id,
|
||||||
|
"vs_currencies": self.vs_currency,
|
||||||
|
"include_24hr_change": "true",
|
||||||
|
},
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
data = resp[coin.id]
|
||||||
|
|
||||||
|
price = data[self.vs_currency]
|
||||||
|
change = data[self.vs_currency + "_24h_change"]
|
||||||
|
if change is None:
|
||||||
|
change = 0
|
||||||
|
except KeyError:
|
||||||
|
return f"{coin.id} returned an error."
|
||||||
|
|
||||||
|
message = f"The current price of {coin.name} is $**{price:,}**"
|
||||||
|
|
||||||
|
# Determine wording of change text
|
||||||
|
if change > 0:
|
||||||
|
message += f", the coin is currently **up {change:.3f}%** for today"
|
||||||
|
elif change < 0:
|
||||||
|
message += f", the coin is currently **down {change:.3f}%** for today"
|
||||||
|
else:
|
||||||
|
message += ", the coin hasn't shown any movement today."
|
||||||
|
|
||||||
|
else:
|
||||||
|
message = f"The price for {coin.name} is not available. If you suspect this is an error run `/status`"
|
||||||
|
|
||||||
|
return message
|
||||||
|
|
||||||
|
def intra_reply(self, symbol: Coin) -> pd.DataFrame:
|
||||||
|
"""Returns price data for a symbol since the last market open.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
symbol : str
|
||||||
|
Stock symbol.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
pd.DataFrame
|
||||||
|
Returns a timeseries dataframe with high, low, and volume data if its available. Otherwise returns empty pd.DataFrame.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if resp := self.get(
|
||||||
|
f"/coins/{symbol.id}/ohlc",
|
||||||
|
params={"vs_currency": self.vs_currency, "days": 1},
|
||||||
|
):
|
||||||
|
df = pd.DataFrame(resp, columns=["Date", "Open", "High", "Low", "Close"]).dropna()
|
||||||
|
df["Date"] = pd.to_datetime(df["Date"], unit="ms")
|
||||||
|
df = df.set_index("Date")
|
||||||
|
return df
|
||||||
|
|
||||||
|
return pd.DataFrame()
|
||||||
|
|
||||||
|
def chart_reply(self, symbol: Coin) -> pd.DataFrame:
|
||||||
|
"""Returns price data for a symbol of the past month up until the previous trading days close.
|
||||||
|
Also caches multiple requests made in the same day.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
symbol : str
|
||||||
|
Stock symbol.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
pd.DataFrame
|
||||||
|
Returns a timeseries dataframe with high, low, and volume data if its available. Otherwise returns empty pd.DataFrame.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if resp := self.get(
|
||||||
|
f"/coins/{symbol.id}/ohlc",
|
||||||
|
params={"vs_currency": self.vs_currency, "days": 30},
|
||||||
|
):
|
||||||
|
df = pd.DataFrame(resp, columns=["Date", "Open", "High", "Low", "Close"]).dropna()
|
||||||
|
df["Date"] = pd.to_datetime(df["Date"], unit="ms")
|
||||||
|
df = df.set_index("Date")
|
||||||
|
return df
|
||||||
|
|
||||||
|
return pd.DataFrame()
|
||||||
|
|
||||||
|
def stat_reply(self, symbol: Coin) -> str:
|
||||||
|
"""Gathers key statistics on coin. Mostly just CoinGecko scores.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
symbol : Coin
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
str
|
||||||
|
Preformatted markdown.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if data := self.get(
|
||||||
|
f"/coins/{symbol.id}",
|
||||||
|
params={
|
||||||
|
"localization": "false",
|
||||||
|
},
|
||||||
|
):
|
||||||
|
return f"""
|
||||||
|
[{data['name']}]({data['links']['homepage'][0]}) Statistics:
|
||||||
|
Market Cap: ${data['market_data']['market_cap'][self.vs_currency]:,}
|
||||||
|
Market Cap Ranking: {data.get('market_cap_rank',"Not Available")}
|
||||||
|
CoinGecko Scores:
|
||||||
|
Overall: {data.get('coingecko_score','Not Available')}
|
||||||
|
Development: {data.get('developer_score','Not Available')}
|
||||||
|
Community: {data.get('community_score','Not Available')}
|
||||||
|
Public Interest: {data.get('public_interest_score','Not Available')}
|
||||||
|
"""
|
||||||
|
else:
|
||||||
|
return f"{symbol.symbol} returned an error."
|
||||||
|
|
||||||
|
def cap_reply(self, coin: Coin) -> str:
|
||||||
|
"""Gets market cap for Coin
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
coin : Coin
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
str
|
||||||
|
Preformatted markdown.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if resp := self.get(
|
||||||
|
"/simple/price",
|
||||||
|
params={
|
||||||
|
"ids": coin.id,
|
||||||
|
"vs_currencies": self.vs_currency,
|
||||||
|
"include_market_cap": "true",
|
||||||
|
},
|
||||||
|
):
|
||||||
|
log.debug(resp)
|
||||||
|
try:
|
||||||
|
data = resp[coin.id]
|
||||||
|
|
||||||
|
price = data[self.vs_currency]
|
||||||
|
cap = data[self.vs_currency + "_market_cap"]
|
||||||
|
except KeyError:
|
||||||
|
return f"{coin.id} returned an error."
|
||||||
|
|
||||||
|
if cap == 0:
|
||||||
|
return f"The market cap for {coin.name} is not available for unknown reasons."
|
||||||
|
|
||||||
|
message = (
|
||||||
|
f"The current price of {coin.name} is $**{price:,}** and"
|
||||||
|
+ " its market cap is $**{cap:,.2f}** {self.vs_currency.upper()}"
|
||||||
|
)
|
||||||
|
|
||||||
|
else:
|
||||||
|
message = f"The Coin: {coin.name} was not found or returned and error."
|
||||||
|
|
||||||
|
return message
|
||||||
|
|
||||||
|
def info_reply(self, symbol: Coin) -> str:
|
||||||
|
"""Gets coin description
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
symbol : Coin
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
str
|
||||||
|
Preformatted markdown.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if data := self.get(
|
||||||
|
f"/coins/{symbol.id}",
|
||||||
|
params={"localization": "false"},
|
||||||
|
):
|
||||||
|
try:
|
||||||
|
return markdownify(data["description"]["en"])
|
||||||
|
except KeyError:
|
||||||
|
return f"{symbol} does not have a description available."
|
||||||
|
|
||||||
|
return f"No information found for: {symbol}\nEither today is boring or the symbol does not exist."
|
||||||
|
|
||||||
|
def spark_reply(self, symbol: Coin) -> str:
|
||||||
|
change = self.get(
|
||||||
|
"/simple/price",
|
||||||
|
params={
|
||||||
|
"ids": symbol.id,
|
||||||
|
"vs_currencies": self.vs_currency,
|
||||||
|
"include_24hr_change": "true",
|
||||||
|
},
|
||||||
|
)[symbol.id]["usd_24h_change"]
|
||||||
|
|
||||||
|
return f"`{symbol.tag}`: {symbol.name}, {change:.2f}%"
|
||||||
|
|
||||||
|
def trending(self) -> list[str]:
|
||||||
|
"""Gets current coins trending on coingecko
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
list[str]
|
||||||
|
list of $$ID: NAME, CHANGE%
|
||||||
|
"""
|
||||||
|
|
||||||
|
coins = self.get("/search/trending")
|
||||||
|
try:
|
||||||
|
trending = []
|
||||||
|
for coin in coins["coins"]:
|
||||||
|
c = coin["item"]
|
||||||
|
|
||||||
|
sym = c["symbol"].upper()
|
||||||
|
name = c["name"]
|
||||||
|
change = self.get(
|
||||||
|
"/simple/price",
|
||||||
|
params={
|
||||||
|
"ids": c["id"],
|
||||||
|
"vs_currencies": self.vs_currency,
|
||||||
|
"include_24hr_change": "true",
|
||||||
|
},
|
||||||
|
)[c["id"]]["usd_24h_change"]
|
||||||
|
|
||||||
|
msg = f"`$${sym}`: {name}, {change:.2f}%"
|
||||||
|
|
||||||
|
trending.append(msg)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
log.warning(e)
|
||||||
|
return self.trending_cache
|
||||||
|
|
||||||
|
self.trending_cache = trending
|
||||||
|
return trending
|
||||||
|
|
||||||
|
def batch_price(self, coins: list[Coin]) -> list[str]:
|
||||||
|
"""Gets price of a list of coins all in one API call
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
coins : list[Coin]
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
list[str]
|
||||||
|
returns preformatted list of strings detailing price movement of each coin passed in.
|
||||||
|
"""
|
||||||
|
query = ",".join([c.id for c in coins])
|
||||||
|
|
||||||
|
prices = self.get(
|
||||||
|
"/simple/price",
|
||||||
|
params={
|
||||||
|
"ids": query,
|
||||||
|
"vs_currencies": self.vs_currency,
|
||||||
|
"include_24hr_change": "true",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
replies = []
|
||||||
|
for coin in coins:
|
||||||
|
if coin.id in prices:
|
||||||
|
p = prices[coin.id]
|
||||||
|
|
||||||
|
if p.get("usd_24h_change") is None:
|
||||||
|
p["usd_24h_change"] = 0
|
||||||
|
|
||||||
|
replies.append(
|
||||||
|
f"{coin.name}: ${p.get('usd',0):,} and has moved {p.get('usd_24h_change',0.0):.2f}% in the past 24 hours."
|
||||||
|
)
|
||||||
|
|
||||||
|
return replies
|
8
dev-reqs.txt
Normal file
8
dev-reqs.txt
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
-r requirements.txt
|
||||||
|
black==23.3.0
|
||||||
|
flake8==5.0.4
|
||||||
|
Flake8-pyproject==1.2.3
|
||||||
|
pylama==8.4.1
|
||||||
|
mypy==1.2.0
|
||||||
|
types-cachetools==5.3.0.5
|
||||||
|
types-pytz==2023.3.0.0
|
210
functions.py
210
functions.py
@ -1,210 +0,0 @@
|
|||||||
import json
|
|
||||||
import re
|
|
||||||
from datetime import datetime, timedelta
|
|
||||||
|
|
||||||
import pandas as pd
|
|
||||||
import requests as r
|
|
||||||
from fuzzywuzzy import fuzz
|
|
||||||
import schedule
|
|
||||||
|
|
||||||
|
|
||||||
class Symbol:
|
|
||||||
"""
|
|
||||||
Functions for finding stock market information about symbols.
|
|
||||||
"""
|
|
||||||
|
|
||||||
SYMBOL_REGEX = "[$]([a-zA-Z]{1,4})"
|
|
||||||
|
|
||||||
searched_symbols = {}
|
|
||||||
|
|
||||||
help_text = """
|
|
||||||
Thanks for using this bot, consider supporting it by [buying me a beer.](https://www.buymeacoffee.com/Anson)
|
|
||||||
|
|
||||||
Full documentation can be found [here.](https://simple-stock-bots.gitlab.io/site/)
|
|
||||||
|
|
||||||
**Commands**
|
|
||||||
- /dividend `$[symbol]` will return dividend information for the symbol.
|
|
||||||
- /news `$[symbol]` will return news about the symbol.
|
|
||||||
- /info `$[symbol]` will return general information about the symbol.
|
|
||||||
- /search `query` Takes a search string, whether a company name or ticker and returns a list of companies that are supported by the bot.
|
|
||||||
|
|
||||||
The bot also looks at every message in any chat it is in for stock symbols. Symbols start with a `$` followed by the stock symbol. For example: $tsla would return price information for Tesla Motors.
|
|
||||||
|
|
||||||
`Market data is provided by [IEX Cloud](https://iexcloud.io)`
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, IEX_TOKEN: str):
|
|
||||||
self.IEX_TOKEN = IEX_TOKEN
|
|
||||||
self.get_symbol_list()
|
|
||||||
schedule.every().day.do(self.get_symbol_list)
|
|
||||||
|
|
||||||
def get_symbol_list(self, return_df=False):
|
|
||||||
"""
|
|
||||||
Fetches a list of stock market symbols from FINRA
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
pd.DataFrame -- [DataFrame with columns: Symbol | Issue_Name | Primary_Listing_Mkt
|
|
||||||
datetime -- The time when the list of symbols was fetched. The Symbol list is updated every open and close of every trading day.
|
|
||||||
"""
|
|
||||||
raw_symbols = r.get(
|
|
||||||
f"https://cloud.iexapis.com/stable/ref-data/symbols?token={self.IEX_TOKEN}"
|
|
||||||
).json()
|
|
||||||
symbols = pd.DataFrame(data=raw_symbols)
|
|
||||||
|
|
||||||
symbols["description"] = symbols["symbol"] + ": " + symbols["name"]
|
|
||||||
self.symbol_list = symbols
|
|
||||||
if return_df:
|
|
||||||
return symbols, datetime.now()
|
|
||||||
|
|
||||||
def search_symbols(self, search: str):
|
|
||||||
"""
|
|
||||||
Performs a fuzzy search to find stock symbols closest to a search term.
|
|
||||||
|
|
||||||
Arguments:
|
|
||||||
search {str} -- String used to search, could be a company name or something close to the companies stock ticker.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
List of Tuples -- A list tuples of every stock sorted in order of how well they match. Each tuple contains: (Symbol, Issue Name).
|
|
||||||
"""
|
|
||||||
schedule.run_pending()
|
|
||||||
search = search.lower()
|
|
||||||
try: # https://stackoverflow.com/a/3845776/8774114
|
|
||||||
return self.searched_symbols[search]
|
|
||||||
except KeyError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
symbols = self.symbol_list
|
|
||||||
symbols["Match"] = symbols.apply(
|
|
||||||
lambda x: fuzz.ratio(search, f"{x['symbol']}".lower()), axis=1,
|
|
||||||
)
|
|
||||||
|
|
||||||
symbols.sort_values(by="Match", ascending=False, inplace=True)
|
|
||||||
if symbols["Match"].head().sum() < 300:
|
|
||||||
symbols["Match"] = symbols.apply(
|
|
||||||
lambda x: fuzz.partial_ratio(search, x["name"].lower()), axis=1,
|
|
||||||
)
|
|
||||||
|
|
||||||
symbols.sort_values(by="Match", ascending=False, inplace=True)
|
|
||||||
symbols = symbols.head(10)
|
|
||||||
symbol_list = list(zip(list(symbols["symbol"]), list(symbols["description"])))
|
|
||||||
self.searched_symbols[search] = symbol_list
|
|
||||||
return symbol_list
|
|
||||||
|
|
||||||
def find_symbols(self, text: str):
|
|
||||||
"""
|
|
||||||
Finds stock tickers starting with a dollar sign in a blob of text and returns them in a list. Only returns each match once. Example: Whats the price of $tsla? -> ['tsla']
|
|
||||||
|
|
||||||
Arguments:
|
|
||||||
text {str} -- Blob of text that might contain tickers with the format: $TICKER
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
list -- List of every found match without the dollar sign.
|
|
||||||
"""
|
|
||||||
|
|
||||||
return list(set(re.findall(self.SYMBOL_REGEX, text)))
|
|
||||||
|
|
||||||
def price_reply(self, symbols: list):
|
|
||||||
"""
|
|
||||||
Takes a list of symbols and replies with Markdown formatted text about the symbols price change for the day.
|
|
||||||
|
|
||||||
Arguments:
|
|
||||||
symbols {list} -- List of stock market symbols.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
dict -- Dictionary with keys of symbols and values of markdown formatted text example: {'tsla': 'The current stock price of Tesla Motors is $**420$$, the stock price is currently **up 42%**}
|
|
||||||
"""
|
|
||||||
dataMessages = {}
|
|
||||||
for symbol in symbols:
|
|
||||||
IEXurl = f"https://cloud.iexapis.com/stable/stock/{symbol}/quote?token={self.IEX_TOKEN}"
|
|
||||||
|
|
||||||
response = r.get(IEXurl)
|
|
||||||
if response.status_code == 200:
|
|
||||||
IEXData = response.json()
|
|
||||||
message = f"The current stock price of {IEXData['companyName']} is $**{IEXData['latestPrice']}**"
|
|
||||||
# Determine wording of change text
|
|
||||||
change = round(IEXData["changePercent"] * 100, 2)
|
|
||||||
if change > 0:
|
|
||||||
message += f", the stock is currently **up {change}%**"
|
|
||||||
elif change < 0:
|
|
||||||
message += f", the stock is currently **down {change}%**"
|
|
||||||
else:
|
|
||||||
message += ", the stock hasn't shown any movement today."
|
|
||||||
else:
|
|
||||||
message = f"The symbol: {symbol} was not found."
|
|
||||||
|
|
||||||
dataMessages[symbol] = message
|
|
||||||
|
|
||||||
return dataMessages
|
|
||||||
|
|
||||||
def dividend_reply(self, symbols: list):
|
|
||||||
divMessages = {}
|
|
||||||
|
|
||||||
for symbol in symbols:
|
|
||||||
IEXurl = f"https://cloud.iexapis.com/stable/data-points/{symbol}/NEXTDIVIDENDDATE?token={self.IEX_TOKEN}"
|
|
||||||
response = r.get(IEXurl)
|
|
||||||
if response.status_code == 200:
|
|
||||||
|
|
||||||
# extract date from json
|
|
||||||
date = response.json()
|
|
||||||
# Pattern IEX uses for dividend date.
|
|
||||||
pattern = "%Y-%m-%d"
|
|
||||||
divDate = datetime.strptime(date, pattern)
|
|
||||||
|
|
||||||
daysDelta = (divDate - datetime.now()).days
|
|
||||||
datePretty = divDate.strftime("%A, %B %w")
|
|
||||||
if daysDelta < 0:
|
|
||||||
divMessages[
|
|
||||||
symbol
|
|
||||||
] = f"{symbol.upper()} dividend was on {datePretty} and a new date hasn't been announced yet."
|
|
||||||
elif daysDelta > 0:
|
|
||||||
divMessages[
|
|
||||||
symbol
|
|
||||||
] = f"{symbol.upper()} dividend is on {datePretty} which is in {daysDelta} Days."
|
|
||||||
else:
|
|
||||||
divMessages[symbol] = f"{symbol.upper()} is today."
|
|
||||||
|
|
||||||
else:
|
|
||||||
divMessages[
|
|
||||||
symbol
|
|
||||||
] = f"{symbol} either doesn't exist or pays no dividend."
|
|
||||||
|
|
||||||
return divMessages
|
|
||||||
|
|
||||||
def news_reply(self, symbols: list):
|
|
||||||
newsMessages = {}
|
|
||||||
|
|
||||||
for symbol in symbols:
|
|
||||||
IEXurl = f"https://cloud.iexapis.com/stable/stock/{symbol}/news/last/3?token={self.IEX_TOKEN}"
|
|
||||||
response = r.get(IEXurl)
|
|
||||||
if response.status_code == 200:
|
|
||||||
data = response.json()
|
|
||||||
newsMessages[symbol] = f"News for **{symbol.upper()}**:\n"
|
|
||||||
for news in data:
|
|
||||||
message = f"\t[{news['headline']}]({news['url']})\n\n"
|
|
||||||
newsMessages[symbol] = newsMessages[symbol] + message
|
|
||||||
else:
|
|
||||||
newsMessages[
|
|
||||||
symbol
|
|
||||||
] = f"No news found for: {symbol}\nEither today is boring or the symbol does not exist."
|
|
||||||
|
|
||||||
return newsMessages
|
|
||||||
|
|
||||||
def info_reply(self, symbols: list):
|
|
||||||
infoMessages = {}
|
|
||||||
|
|
||||||
for symbol in symbols:
|
|
||||||
IEXurl = f"https://cloud.iexapis.com/stable/stock/{symbol}/company?token={self.IEX_TOKEN}"
|
|
||||||
response = r.get(IEXurl)
|
|
||||||
|
|
||||||
if response.status_code == 200:
|
|
||||||
data = response.json()
|
|
||||||
infoMessages[
|
|
||||||
symbol
|
|
||||||
] = f"Company Name: [{data['companyName']}]({data['website']})\nIndustry: {data['industry']}\nSector: {data['sector']}\nCEO: {data['CEO']}\nDescription: {data['description']}\n"
|
|
||||||
|
|
||||||
else:
|
|
||||||
infoMessages[
|
|
||||||
symbol
|
|
||||||
] = f"No information found for: {symbol}\nEither today is boring or the symbol does not exist."
|
|
||||||
|
|
||||||
return infoMessages
|
|
8
pyproject.toml
Normal file
8
pyproject.toml
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
[tool.black]
|
||||||
|
line-length = 130
|
||||||
|
|
||||||
|
[tool.flake8]
|
||||||
|
max-line-length = 130
|
||||||
|
|
||||||
|
[tool.pycodestyle]
|
||||||
|
max_line_length = 130
|
@ -1,6 +1,7 @@
|
|||||||
discord.py==1.6
|
nextcord==2.4.2
|
||||||
requests==2.23.0
|
requests==2.25.1
|
||||||
pandas==1.0.3
|
pandas==2.0.0
|
||||||
fuzzywuzzy==0.18.0
|
schedule==1.0.0
|
||||||
python-Levenshtein==0.12.1
|
mplfinance==0.12.7a5
|
||||||
schedule==0.6.0
|
markdownify==0.6.5
|
||||||
|
cachetools==4.2.2
|
393
symbol_router.py
Normal file
393
symbol_router.py
Normal file
@ -0,0 +1,393 @@
|
|||||||
|
"""Function that routes symbols to the correct API provider.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import datetime
|
||||||
|
import logging
|
||||||
|
import random
|
||||||
|
import re
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
import schedule
|
||||||
|
from cachetools import TTLCache, cached
|
||||||
|
|
||||||
|
from cg_Crypto import cg_Crypto
|
||||||
|
from MarketData import MarketData
|
||||||
|
from Symbol import Coin, Stock, Symbol
|
||||||
|
|
||||||
|
from typing import Dict
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class Router:
|
||||||
|
STOCK_REGEX = "(?:^|[^\\$])\\$([a-zA-Z.]{1,6})"
|
||||||
|
CRYPTO_REGEX = "[$]{2}([a-zA-Z]{1,20})"
|
||||||
|
trending_count: Dict[str, float] = {}
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.stock = MarketData()
|
||||||
|
self.crypto = cg_Crypto()
|
||||||
|
|
||||||
|
schedule.every().hour.do(self.trending_decay)
|
||||||
|
|
||||||
|
def trending_decay(self, decay=0.5):
|
||||||
|
"""Decays the value of each trending stock by a multiplier"""
|
||||||
|
t_copy = {}
|
||||||
|
dead_keys = []
|
||||||
|
if self.trending_count:
|
||||||
|
t_copy = self.trending_count.copy()
|
||||||
|
for key in t_copy.keys():
|
||||||
|
if t_copy[key] < 0.01:
|
||||||
|
# This just makes sure were not keeping around keys that havent been called in a very long time.
|
||||||
|
dead_keys.append(key)
|
||||||
|
else:
|
||||||
|
t_copy[key] = t_copy[key] * decay
|
||||||
|
for dead in dead_keys:
|
||||||
|
t_copy.pop(dead)
|
||||||
|
|
||||||
|
self.trending_count = t_copy.copy()
|
||||||
|
log.info("Decayed trending symbols.")
|
||||||
|
|
||||||
|
def find_symbols(self, text: str, *, trending_weight: int = 1) -> list[Stock | Symbol]:
|
||||||
|
"""Finds stock tickers starting with a dollar sign, and cryptocurrencies with two dollar signs
|
||||||
|
in a blob of text and returns them in a list.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
text : str
|
||||||
|
Blob of text.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
list[Symbol]
|
||||||
|
List of stock symbols as Symbol objects
|
||||||
|
"""
|
||||||
|
schedule.run_pending()
|
||||||
|
|
||||||
|
symbols: list[Symbol] = []
|
||||||
|
stocks = set(re.findall(self.STOCK_REGEX, text))
|
||||||
|
for stock in stocks:
|
||||||
|
# Market data lacks tools to check if a symbol is valid.
|
||||||
|
symbols.append(Stock(stock))
|
||||||
|
|
||||||
|
coins = set(re.findall(self.CRYPTO_REGEX, text))
|
||||||
|
for coin in coins:
|
||||||
|
sym = self.crypto.symbol_list[self.crypto.symbol_list["symbol"].str.fullmatch(coin.lower(), case=False)]
|
||||||
|
if sym.empty:
|
||||||
|
log.info(f"{coin} is not in list of coins")
|
||||||
|
else:
|
||||||
|
symbols.append(Coin(sym))
|
||||||
|
if symbols:
|
||||||
|
for symbol in symbols:
|
||||||
|
self.trending_count[symbol.tag] = self.trending_count.get(symbol.tag, 0) + trending_weight
|
||||||
|
log.debug(self.trending_count)
|
||||||
|
|
||||||
|
return symbols
|
||||||
|
|
||||||
|
def status(self, bot_resp) -> str:
|
||||||
|
"""Checks for any issues with APIs.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
str
|
||||||
|
Human readable text on status of the bot and relevant APIs
|
||||||
|
"""
|
||||||
|
|
||||||
|
stats = f"""
|
||||||
|
Bot Status:
|
||||||
|
{bot_resp}
|
||||||
|
|
||||||
|
Stock Market Data:
|
||||||
|
{self.stock.status()}
|
||||||
|
|
||||||
|
Cryptocurrency Data:
|
||||||
|
{self.crypto.status()}
|
||||||
|
"""
|
||||||
|
|
||||||
|
log.warning(stats)
|
||||||
|
|
||||||
|
return stats
|
||||||
|
|
||||||
|
def inline_search(self, search: str, matches: int = 5) -> pd.DataFrame:
|
||||||
|
"""Searches based on the shortest symbol that contains the same string as the search.
|
||||||
|
Should be very fast compared to a fuzzy search.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
search : str
|
||||||
|
String used to match against symbols.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
list[tuple[str, str]]
|
||||||
|
Each tuple contains: (Symbol, Issue Name).
|
||||||
|
"""
|
||||||
|
|
||||||
|
df = pd.concat([self.stock.symbol_list, self.crypto.symbol_list])
|
||||||
|
|
||||||
|
df = df[df["description"].str.contains(search, regex=False, case=False)].sort_values(
|
||||||
|
by="type_id", key=lambda x: x.str.len()
|
||||||
|
)
|
||||||
|
|
||||||
|
symbols = df.head(matches)
|
||||||
|
symbols["price_reply"] = symbols["type_id"].apply(
|
||||||
|
lambda sym: self.price_reply(self.find_symbols(sym, trending_weight=0))[0]
|
||||||
|
)
|
||||||
|
|
||||||
|
return symbols
|
||||||
|
|
||||||
|
def price_reply(self, symbols: list[Symbol]) -> list[str]:
|
||||||
|
"""Returns current market price or after hours if its available for a given stock symbol.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
symbols : list
|
||||||
|
List of stock symbols.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
Dict[str, str]
|
||||||
|
Each symbol passed in is a key with its value being a human readable
|
||||||
|
markdown formatted string of the symbols price and movement.
|
||||||
|
"""
|
||||||
|
replies = []
|
||||||
|
|
||||||
|
for symbol in symbols:
|
||||||
|
log.info(symbol)
|
||||||
|
if isinstance(symbol, Stock):
|
||||||
|
replies.append(self.stock.price_reply(symbol))
|
||||||
|
elif isinstance(symbol, Coin):
|
||||||
|
replies.append(self.crypto.price_reply(symbol))
|
||||||
|
else:
|
||||||
|
log.info(f"{symbol} is not a Stock or Coin")
|
||||||
|
|
||||||
|
return replies
|
||||||
|
|
||||||
|
def info_reply(self, symbols: list) -> list[str]:
|
||||||
|
"""Gets information on stock symbols.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
symbols : list[str]
|
||||||
|
List of stock symbols.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
Dict[str, str]
|
||||||
|
Each symbol passed in is a key with its value being a human readable formatted
|
||||||
|
string of the symbols information.
|
||||||
|
"""
|
||||||
|
replies = []
|
||||||
|
|
||||||
|
for symbol in symbols:
|
||||||
|
if isinstance(symbol, Stock):
|
||||||
|
replies.append(self.stock.info_reply(symbol))
|
||||||
|
elif isinstance(symbol, Coin):
|
||||||
|
replies.append(self.crypto.info_reply(symbol))
|
||||||
|
else:
|
||||||
|
log.debug(f"{symbol} is not a Stock or Coin")
|
||||||
|
|
||||||
|
return replies
|
||||||
|
|
||||||
|
def intra_reply(self, symbol: Symbol) -> pd.DataFrame:
|
||||||
|
"""Returns price data for a symbol since the last market open.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
symbol : str
|
||||||
|
Stock symbol.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
pd.DataFrame
|
||||||
|
Returns a timeseries dataframe with high, low, and volume data if its available.
|
||||||
|
Otherwise returns empty pd.DataFrame.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if isinstance(symbol, Stock):
|
||||||
|
return self.stock.intra_reply(symbol)
|
||||||
|
elif isinstance(symbol, Coin):
|
||||||
|
return self.crypto.intra_reply(symbol)
|
||||||
|
else:
|
||||||
|
log.debug(f"{symbol} is not a Stock or Coin")
|
||||||
|
return pd.DataFrame()
|
||||||
|
|
||||||
|
def chart_reply(self, symbol: Symbol) -> pd.DataFrame:
|
||||||
|
"""Returns price data for a symbol of the past month up until the previous trading days close.
|
||||||
|
Also caches multiple requests made in the same day.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
symbol : str
|
||||||
|
Stock symbol.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
pd.DataFrame
|
||||||
|
Returns a timeseries dataframe with high, low, and volume data if its available.
|
||||||
|
Otherwise returns empty pd.DataFrame.
|
||||||
|
"""
|
||||||
|
if isinstance(symbol, Stock):
|
||||||
|
return self.stock.chart_reply(symbol)
|
||||||
|
elif isinstance(symbol, Coin):
|
||||||
|
return self.crypto.chart_reply(symbol)
|
||||||
|
else:
|
||||||
|
log.debug(f"{symbol} is not a Stock or Coin")
|
||||||
|
return pd.DataFrame()
|
||||||
|
|
||||||
|
def stat_reply(self, symbols: list[Symbol]) -> list[str]:
|
||||||
|
"""Gets key statistics for each symbol in the list
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
symbols : list[str]
|
||||||
|
List of stock symbols
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
Dict[str, str]
|
||||||
|
Each symbol passed in is a key with its value being a human readable
|
||||||
|
formatted string of the symbols statistics.
|
||||||
|
"""
|
||||||
|
replies = []
|
||||||
|
|
||||||
|
for symbol in symbols:
|
||||||
|
if isinstance(symbol, Stock):
|
||||||
|
replies.append(self.stock.stat_reply(symbol))
|
||||||
|
elif isinstance(symbol, Coin):
|
||||||
|
replies.append(self.crypto.stat_reply(symbol))
|
||||||
|
else:
|
||||||
|
log.debug(f"{symbol} is not a Stock or Coin")
|
||||||
|
|
||||||
|
return replies
|
||||||
|
|
||||||
|
def cap_reply(self, symbols: list[Symbol]) -> list[str]:
|
||||||
|
"""Gets market cap for each symbol in the list
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
symbols : list[str]
|
||||||
|
List of stock symbols
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
Dict[str, str]
|
||||||
|
Each symbol passed in is a key with its value being a human readable
|
||||||
|
formatted string of the symbols market cap.
|
||||||
|
"""
|
||||||
|
replies = []
|
||||||
|
|
||||||
|
for symbol in symbols:
|
||||||
|
if isinstance(symbol, Stock):
|
||||||
|
replies.append(self.stock.cap_reply(symbol))
|
||||||
|
elif isinstance(symbol, Coin):
|
||||||
|
replies.append(self.crypto.cap_reply(symbol))
|
||||||
|
else:
|
||||||
|
log.debug(f"{symbol} is not a Stock or Coin")
|
||||||
|
|
||||||
|
return replies
|
||||||
|
|
||||||
|
def spark_reply(self, symbols: list[Symbol]) -> list[str]:
|
||||||
|
"""Gets change for each symbol and returns it in a compact format
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
symbols : list[str]
|
||||||
|
List of stock symbols
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
list[str]
|
||||||
|
List of human readable strings.
|
||||||
|
"""
|
||||||
|
replies = []
|
||||||
|
|
||||||
|
for symbol in symbols:
|
||||||
|
if isinstance(symbol, Stock):
|
||||||
|
replies.append(self.stock.spark_reply(symbol))
|
||||||
|
elif isinstance(symbol, Coin):
|
||||||
|
replies.append(self.crypto.spark_reply(symbol))
|
||||||
|
else:
|
||||||
|
log.debug(f"{symbol} is not a Stock or Coin")
|
||||||
|
|
||||||
|
return replies
|
||||||
|
|
||||||
|
@cached(cache=TTLCache(maxsize=1024, ttl=600))
|
||||||
|
def trending(self) -> str:
|
||||||
|
"""Checks APIs for trending symbols.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
list[str]
|
||||||
|
List of preformatted strings to be sent to user.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# stocks = self.stock.trending()
|
||||||
|
coins = self.crypto.trending()
|
||||||
|
|
||||||
|
reply = ""
|
||||||
|
|
||||||
|
log.warning(self.trending_count)
|
||||||
|
if self.trending_count:
|
||||||
|
reply += "🔥Trending on the Stock Bot:\n`"
|
||||||
|
reply += "━" * len("Trending on the Stock Bot:") + "`\n"
|
||||||
|
|
||||||
|
sorted_trending = [s[0] for s in sorted(self.trending_count.items(), key=lambda item: item[1])][::-1][0:5]
|
||||||
|
log.warning(sorted_trending)
|
||||||
|
for t in sorted_trending:
|
||||||
|
reply += self.spark_reply(self.find_symbols(t))[0] + "\n"
|
||||||
|
|
||||||
|
if coins:
|
||||||
|
reply += "\n\n🦎Trending Crypto:\n`"
|
||||||
|
reply += "━" * len("Trending Crypto:") + "`\n"
|
||||||
|
for coin in coins:
|
||||||
|
reply += coin + "\n"
|
||||||
|
|
||||||
|
if "`$GME" in reply:
|
||||||
|
reply = reply.replace("🔥", "🦍")
|
||||||
|
|
||||||
|
if reply:
|
||||||
|
return reply
|
||||||
|
else:
|
||||||
|
log.warning("Failed to collect trending data.")
|
||||||
|
return "Trending data is not currently available."
|
||||||
|
|
||||||
|
def random_pick(self) -> str:
|
||||||
|
choice = random.choice(list(self.stock.symbol_list["description"]) + list(self.crypto.symbol_list["description"]))
|
||||||
|
hold = (datetime.date.today() + datetime.timedelta(random.randint(1, 365))).strftime("%b %d, %Y")
|
||||||
|
|
||||||
|
return f"{choice}\nBuy and hold until: {hold}"
|
||||||
|
|
||||||
|
def batch_price_reply(self, symbols: list[Symbol]) -> list[str]:
|
||||||
|
"""Returns current market price or after hours if its available for a given stock symbol.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
symbols : list
|
||||||
|
List of stock symbols.
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
Dict[str, str]
|
||||||
|
Each symbol passed in is a key with its value being a human readable
|
||||||
|
markdown formatted string of the symbols price and movement.
|
||||||
|
"""
|
||||||
|
replies = []
|
||||||
|
stocks = []
|
||||||
|
coins = []
|
||||||
|
|
||||||
|
for symbol in symbols:
|
||||||
|
if isinstance(symbol, Stock):
|
||||||
|
stocks.append(symbol)
|
||||||
|
elif isinstance(symbol, Coin):
|
||||||
|
coins.append(symbol)
|
||||||
|
else:
|
||||||
|
log.debug(f"{symbol} is not a Stock or Coin")
|
||||||
|
|
||||||
|
if stocks:
|
||||||
|
for stock in stocks:
|
||||||
|
replies.append(self.stock.price_reply(stock))
|
||||||
|
if coins:
|
||||||
|
replies = replies + self.crypto.batch_price(coins)
|
||||||
|
|
||||||
|
return replies
|
33
tests.py
Normal file
33
tests.py
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
import keyboard
|
||||||
|
import time
|
||||||
|
|
||||||
|
|
||||||
|
tests = """$$xno
|
||||||
|
/info $tsla
|
||||||
|
/info $$btc
|
||||||
|
/news $tsla
|
||||||
|
/news $$btc
|
||||||
|
/stat $tsla
|
||||||
|
/stat $$btc
|
||||||
|
/cap $tsla
|
||||||
|
/cap $$btc
|
||||||
|
/dividend $tsla
|
||||||
|
/dividend $msft
|
||||||
|
/dividend $$btc
|
||||||
|
/intra $tsla
|
||||||
|
/intra $$btc
|
||||||
|
/chart $tsla
|
||||||
|
/chart $$btc
|
||||||
|
/help
|
||||||
|
/trending""".split(
|
||||||
|
"\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
print("press enter to start")
|
||||||
|
keyboard.wait("enter")
|
||||||
|
|
||||||
|
for test in tests:
|
||||||
|
print(test)
|
||||||
|
keyboard.write(test)
|
||||||
|
time.sleep(1)
|
||||||
|
keyboard.press_and_release("enter")
|
Loading…
x
Reference in New Issue
Block a user