DEV Community

Cover image for AlphaVantage Action Bot - renders realtime chart of a stock/cryptocurrency inside Readme
Manoj Naidu
Manoj Naidu

Posted on • Edited on

1 2

AlphaVantage Action Bot - renders realtime chart of a stock/cryptocurrency inside Readme

Hello programmers, hope you are all doing fantastic!🥳 .We all know that Readme file is crucial for any repository, it serves as a user manual and helps us in getting started.

This action makes the best use of Readme file to show the trajectory of stock prices in order to gauge your company’s general health.

What I Built?

AlphaVantage Action Bot is a Github action that renders the realtime chart of a stock/cryptocurrency inside the readme file. We will be using the Alpha Vantage Public Stock APIs to build the action bot. You may also check out this finance API guide that surveys some of the popular stock and crypto data APIs in the market.

Submission Category:

Wacky Wildcards

Screenshots

  • BITCOIN open price trajectory

Bitcoin open trajectory

  • close price trajectory of APPLE

Apple close trajectory

  • Market Capital(USD) of BTC

BTC market capital

How to Setup?

This action could be adopted easily into your project in just 3 steps...

Step 1 - Adding script file into your repo.

This step is pretty simple, all you need to do is..

  • Create folder named alphavantage in the root of your repo.
  • Inside alphavantage folder, add a new python script file with name alphavantage-bot.py and paste the complete code below
import pandas, os, random
import matplotlib.pyplot as plt
from datetime import datetime
from alpha_vantage.timeseries import TimeSeries
from alpha_vantage.cryptocurrencies import CryptoCurrencies
####### Values could be customized (Right now we are choosing random values) ############
CHARTDOMAIN = random.choice(['stock', 'cryptocurrency'])
REQ_TYPE = random.choice(['intraday', 'daily', 'weekly', 'monthly'])
SYMBOL = random.choice(['MSFT', 'AAPL', 'AMZN', 'GOOGL', 'FB', 'INTC', 'CSCO', 'CMCSA', 'PEP', 'ADBE', 'NVDA', 'NFLX', 'PYPL', 'COST', 'SBUX', 'QCOM', 'INTU', 'TMUS'])
# Stock Symbol
INTERVAL = random.choice([1, 5, 15, 30, 60])
OUTPUTSIZE = 'full'
#['compact', 'full'] are the other options.
PATHTOCHART = './alphavantage'
GRIDVIEW = True
PLOT = random.choice(['close', 'open', 'high', 'low'])
COLOR = random.choice(['blue', 'green', 'cyan', 'magenta', 'black', 'yellow', 'orange'])
RENDERLINE = 4
# Line inside Readme at which the chart to be rendered.
################### If CHARTDOMAIN is set to 'cryptocurrency' then edit these below (Right now we are choosing random values) ####################################
CRYPTOSYMBOL = random.choice(['BTC', 'ETH'])
# Cryptocurrency symbol
CRYPTOMARKET = random.choice(['USD', 'CNY'])
CRYPTOINTERVAL = random.choice(['daily', 'weekly', 'monthly'])
CRYPTOPLOT = random.choice(['close', 'open', 'high', 'low', 'marketcapital'])
############# Value customization end #################
API_KEY = os.environ['ALPHA_VANTAGE_KEY']
def setup_request_object(request, symbol, interval):
if CHARTDOMAIN == 'stock':
try:
ts = TimeSeries(API_KEY, output_format='pandas', indexing_type='date')
except:
print("Error occurred/ Number of API calls exhausted")
return [False, False]
if request == 'intraday': return ['intraday', ts]
if request == 'daily': return ['daily', ts]
if request == 'weekly': return ['weekly', ts]
if request == 'monthly': return ['monthly', ts]
return [False, False]
if CHARTDOMAIN == 'cryptocurrency':
try:
cc = CryptoCurrencies(key=API_KEY, output_format='pandas')
except:
print("Error occurred/ Number of API calls exhausted")
return [False, False]
if CRYPTOINTERVAL == 'daily': return ['daily', cc]
if CRYPTOINTERVAL == 'weekly': return ['weekly', cc]
if CRYPTOINTERVAL == 'monthly': return ['monthly', cc]
return [False, False]
def make_request(type, object):
if CHARTDOMAIN == 'stock':
if type == 'intraday':
interval = str(INTERVAL)+'min'
return object.get_intraday(symbol=SYMBOL, interval=interval, outputsize=OUTPUTSIZE)
if type == 'daily':
return object.get_daily(symbol=SYMBOL)
if type == 'weekly':
return object.get_weekly(symbol=SYMBOL)
if type == 'monthly':
return object.get_monthly(symbol=SYMBOL)
if CHARTDOMAIN == 'cryptocurrency':
if type == 'daily':
return object.get_digital_currency_daily(symbol=CRYPTOSYMBOL, market=CRYPTOMARKET)
if type == 'weekly':
return object.get_digital_currency_weekly(symbol=CRYPTOSYMBOL, market=CRYPTOMARKET)
if type == 'monthly':
return object.get_digital_currency_monthly(symbol=CRYPTOSYMBOL, market=CRYPTOMARKET)
def save_chart(values, crypto_market):
chart_save_path = PATHTOCHART + '/chart.png'
# Clear previous chart
if os.path.exists(chart_save_path):
os.remove(chart_save_path)
print("Old chart removed")
#Get Timestamps
now = datetime.now().strftime("%b %d, %Y(%H:%M:%S)")
# Set plot dimensions
fig = plt.figure(num=None, figsize=(12, 8))
ax = fig.add_subplot()
# Save new chart
if CHARTDOMAIN == 'stock':
if PLOT == 'open': plot = '1. open'
if PLOT == 'high': plot = '2. high'
if PLOT == 'low': plot = '3. low'
if PLOT == 'close': plot = '4. close'
ax.set_title(
"Latest Data -> OPEN : {} | HIGH : {} | LOW : {} | CLOSE : {} \n\n {} {} value chart of {} - Last updated at {}"
.format(values['1. open'][0], values['2. high'][0], values['3. low'][0], values['4. close'][0], REQ_TYPE, PLOT, SYMBOL, now)
)
values[plot].plot(color=COLOR)
plt.ylabel('Price in USD')
plt.xlabel('TimeFrame')
if GRIDVIEW: plt.grid()
plt.savefig(chart_save_path)
print("Saved new chart")
if CHARTDOMAIN == 'cryptocurrency':
if CRYPTOPLOT == 'open' and crypto_market == 'CNY': plot = '1a. open (CNY)'
if CRYPTOPLOT == 'open' and crypto_market == 'USD': plot = '1b. open (USD)'
if CRYPTOPLOT == 'high' and crypto_market == 'CNY': plot = '2a. high (CNY)'
if CRYPTOPLOT == 'high' and crypto_market == 'USD': plot = '2b. high (USD)'
if CRYPTOPLOT == 'low' and crypto_market == 'CNY': plot = '3a. low (CNY)'
if CRYPTOPLOT == 'low' and crypto_market == 'USD': plot = '3b. low (USD)'
if CRYPTOPLOT == 'close' and crypto_market == 'CNY': plot = '4a. close (CNY)'
if CRYPTOPLOT == 'close' and crypto_market == 'USD': plot = '4b. close (USD)'
if CRYPTOPLOT == 'marketcapital':
plot = '6. market cap (USD)'
crypto_market = 'USD'
if crypto_market == 'CNY':
ax.set_title(
"Latest Data({} market) -> OPEN : {} | HIGH : {} | LOW : {} | CLOSE : {} \n\n {} {} value chart of {} - Last updated at {}"
.format(crypto_market, values['1a. open (CNY)'][0], values['2a. high (CNY)'][0], values['3a. low (CNY)'][0], values['4a. close (CNY)'][0], CRYPTOINTERVAL, CRYPTOPLOT, CRYPTOSYMBOL, now)
)
if crypto_market == 'USD':
ax.set_title(
"Latest Data({} market) -> OPEN : {} | HIGH : {} | LOW : {} | CLOSE : {} \n\n {} {} value chart of {} - Last updated at {}"
.format(crypto_market, values['1b. open (USD)'][0], values['2b. high (USD)'][0], values['3b. low (USD)'][0], values['4b. close (USD)'][0], CRYPTOINTERVAL, CRYPTOPLOT, CRYPTOSYMBOL, now)
)
values[plot].plot(color=COLOR)
plt.ylabel('Price')
plt.xlabel('TimeFrame')
if GRIDVIEW: plt.grid()
plt.savefig(chart_save_path)
print("Saved new chart")
def rewrite_readme():
alt_text = 'AlphaVantage-Action-Bot-Chart'
now = datetime.now().strftime("%b %d, %Y(%H:%M:%S)")
promote_text = "**Realtime Stock/Crytpocurrency Chart📈 Rendered By [AlphaVantage-Action-Bot](https://github.com/manojnaidu619/AlphaVantage-Action-Bot) | Last updated the above chart on {} **".format(now)
code_line = f'![{alt_text}]({PATHTOCHART}/chart.png)'
readme = './README.md'
line = RENDERLINE-1
parsed_data = []
def insert_string(array, pos, data):
array.insert(pos, "{} \n".format(data))
array.insert(pos + 1, "{} \n".format(promote_text))
with open(readme, 'r') as file: data = file.readlines()
for index, x in enumerate(data):
to_remove = False
if x.startswith("![{}]".format(alt_text)): to_remove = True
if x.startswith('**Realtime Stock/Crytpocurrency Chart'): to_remove = True
if not to_remove: parsed_data.append(x)
data = parsed_data
insert_string(data, line, code_line)
with open(readme, 'w') as file: file.writelines( data )
# Driver Code
request_type, request_object = setup_request_object(REQ_TYPE, SYMBOL, INTERVAL)
if (request_type != False and request_object != False):
values, columns = make_request(request_type, request_object)
save_chart(values, CRYPTOMARKET)
rewrite_readme()
  • From line 8-50, the variables could be customized to requirements.

So now, your repo will contain a python script file, whose path is YOUR_REPO_NAME/alphavantage/alphavantage-bot.py. It should look like this...

Script Path

Step 2 - Adding AlphaVantage API key to repo secrets.

After filling the basic details, you should get your API key instantly.

Alt Text

  • Now, paste the API key inside your repo secrets with the name ALPHA_VANTAGE_KEY.

Alt Text

Step 3 - Setup Workflow file(Final step, yay!).

Paste the below code inside
REPO_ROOT/.github/workflows/AlphaVantage-Action-Bot.yml


name: AlphaVantage-Action-Bot

on:
  schedule:
    - cron: "*/30 * * * *"  
    # Runs every 30th minute
    # Could be customized to requirement
    # To know more about crontabs refer https://crontab.guru/ 


jobs:
  alphavantage-render-chart:
    runs-on: ubuntu-latest
    steps:
      - name: checkout repo content
        uses: actions/checkout@v2 # checkout the repository content to github runner.
      - name: setup python
        uses: actions/setup-python@v2
        with:
           python-version: 3.8 #install the python needed
      - name: Install dependencies
        run: python -m pip install --upgrade pip matplotlib pandas alpha_vantage
      - name: execute python script 
        run: python ./alphavantage/alphavantage-bot.py
        env:
           ALPHA_VANTAGE_KEY: ${{ secrets.ALPHA_VANTAGE_KEY }}
      - name: Commit and push if changed
        run: |
         git add .
         git diff
         git config --global user.email "alphavantage-action-bot@example.com"
         git config --global user.name "AlphaVantage Action Bot"
         git commit -m "AlphaVantage Action Bot Updated README" -a || echo "No changes to commit"
         git push
Enter fullscreen mode Exit fullscreen mode

Now, your workflow file's path should like something like this...

Wokflow file path

Congrats! You have successfully set up the workflow 😎

Link to Code

GitHub logo manojnaidu619 / AlphaVantage-Action-Bot

A github action to render real-time stocks/cryptocurrency charts inside readme

AlphaVantage-Action-Bot

A github action to render real-time stocks/cryptocurrency charts inside readme

AlphaVantage-Action-Bot-Chart **Realtime Stock/Crytpocurrency Chart📈 Rendered By AlphaVantage-Action-Bot | Last updated the above chart on Oct 07, 2024(00:57:34) **

Hello programmers, hope you are all doing fantastic!🥳 .We all know that Readme file is crucial for any repository, it serves as a user manual and helps us in getting started.

This action makes the best use of readme file to show the trajectory of stock prices in order to gauge your company’s general health.

📌 Click on DEV logo below to view detailed article

Manoj Naidu's DEV Profile

What Is it?

AlphaVantage Action Bot is a Github action that renders the realtime chart of a stock/cryptocurrency inside the readme file. We will be using the Alpha Vantage Public Stock APIs to build the action bot. You may also check out this finance API guide that surveys some of the popular stock and crypto data APIs…

Additional Resources / Info

Special Thanks to the AlphaVantage team for reaching me out on this article✌️

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay