Automate Your Finance Blog with WordPress and Google Bard in Python

Introduction

Earlier I gave you an overview of how you can you GPT APIs to build a stock sentiment analysis system. In this post, I am going to introduce you to Google Bard, Google’s answer to OpenAI’s chatGPT. Bard has been around for a few months but they recently offered APIs to access their LLM. Initially, they introduced PaLM APIs but very recently they have offered Gemini Pro and Gemini Pro Vision APIs which means that like GPT4 Vision, you can now use Bard APIs to process images. We are not going to discuss image processing capabilities at the moment. I am going to offer a use case where I will be using Gemini Pro APIs to create a daily stock market performance report and post it as an article on a WordPress blog using WordPress Rest APIs. The demo of the project is given below:

Google is offering three different model sizes:

 

First, I will give you a bit about how I will use Google Bard to test the prompt, and later I will be using Gemini APIs to generate the blog post. At the end, I will be sending the generated content to the WordPress blog via API. Let’s start!

Writing Prompt

Head on to Bard and write the below prompt:

Write me an article on stock market performance for the date 22 December 2023, including key indices such as the S&P 500, Dow Jones Industrial Average, and NASDAQ Composite. Highlight notable gainers and losers, identifying the sectors driving market movement. Discuss any significant economic events, corporate announcements, or geopolitical factors influencing market trends. Include information on trading volume, volatility, and any technical patterns observed. Additionally, comment on the overall market sentiment, investor behavior, and potential implications for the upcoming trading sessions. Lastly, offer insights into relevant commodities, currencies, and interest rates that may have impacted the broader financial landscape. Add relevant headings where needed. Also suggest relevant Blog post title in H1 tag. At the end return data in JSON format with two fields: Title and Description where the “Title” contains the blog title and “Desrcription” contains the entire article. Do not return any other text besides JSON

After asking for the required piece of text I am asking to return the data in JSON format with the fields: Title and Description

Google Bard

You might find a slight change in the prompt I sent to Bard and the API itself because I had to tweak it to return the desired response via APIs. To Bard, I did not send, Do not return any other text besides JSON.

Using Gemini APIs

We have tested our prompt, and it’s time to integrate the prompt by using Gemini Pro APIs. To do that you will have to generate an API key first. Go to https://makersuite.google.com/app/apikey and create the API Key. Before testing the prompt itself, let’s see the different LLM models offered by Google.

import google.generativeai as genai
from dotenv import load_dotenv

if __name__ == '__main__':
   load_dotenv()
   genai.configure(api_key=api_key)
   models = genai.list_models()
   for model in models:
     print(model.display_name, model.name)

When you run this code it outputs:

PaLM 2 Chat (Legacy) models/chat-bison-001
PaLM 2 (Legacy) models/text-bison-001
Embedding Gecko models/embedding-gecko-001
Gemini Pro models/gemini-pro
Gemini Pro Vision models/gemini-pro-vision
Embedding 001 models/embedding-001
Model that performs Attributed Question Answering. models/aqa

For this post, I am going to use Gemini Pro. Now let’s write the code using the prompt which will return the blog article in JSON format.

import json

import google.generativeai as genai
from dotenv import load_dotenv
import os
from datetime import datetime


def generate_article(stock_date):
    # Convert the string to a datetime object
    date_object = datetime.strptime(stock_date, "%Y-%m-%d")
    # Format the date
    formatted_date = date_object.strftime("%d %B %Y")
    load_dotenv()

    api_key = os.environ.get("GEMINI_API_KEY")
    prompt = f'Write me an article on stock market performance for the date {formatted_date}, including key indices such as the S&P 500, Dow Jones Industrial Average, and NASDAQ Composite. Highlight notable gainers and losers, identifying the sectors driving market movement. Discuss any significant economic events, corporate announcements, or geopolitical factors influencing market trends. Include information on trading volume, volatility, and any technical patterns observed. Additionally, comment on the overall market sentiment, investor behavior, and potential implications for the upcoming trading sessions. Lastly, offer insights into relevant commodities, currencies, and interest rates that may have impacted the broader financial landscape. Also suggest relevant Blog post title in H1 tag. At the end return data in JSON format with two fields: Title and Description where the "Title" contains the blog title and "Desrcription" contains the entire article. Do not return any other text besides JSON'
    genai.configure(api_key=api_key)
    model = genai.GenerativeModel("gemini-pro")
    response = model.generate_content(contents=prompt)
    response_text = response.text.replace("```json", '').replace("```", "")
    json_data = json.loads(response_text)
    return json_data


if __name__ == '__main__':
    # Assuming you have a date string
    date_string = "2023-12-22"
    article = generate_article(date_string)
    print(article)

Since I am writing the article on Sunday(24 December) and the market is closed, I have manually set the last Friday date here. Otherwise, the script will be working as a CRON job after market hours in working days and return the required data. As expected, when you run it, it generates the following JSON payload. I also had to sanitize the return output because the API often adds “`json and “` before and after the JSON payload.

Anyways, we have done half of our work. Now we have to send this generated article to our WordPress blog.

Download the latest version of WordPress from the website and install it on your machine. To enable the Markdown, you will have to install the Markup Markdown plugin. This plugin will disable the default editor and enable the Markdown editor.

Markdown Editor

Cool, No?

WordPress REST APIs

Now let’s test whether WordPress APIs are working or not. Before doing that, you have to change the format of permalink. The default format will not let you return the JSON data. I did something like the below, without doing this APIs will not work.

Now let’s make a sample call to http://localhost:8000/wp-json and if all goes well you will see something like the below:

WordPress REST APO

It returns a big JSON payload with all the details. The return of the JSON tells that the WordPress JSON API is working properly.

Using API to create posts

Before creating or updating/deleting a post you must be authenticated as a WordPress user. WordPress provides a Basic Auth plugin to do this. Download the file and put it in the plugins directory. Below is the code to create a post. You can check the docs to learn more about the endpoint related to post creation.

def create_post(title, text):
    article_url = ''

    headers = {
        'Content-Type': 'application/json',
    }

    json_data = {
        'title': title,
        'content': text,
        'status': 'publish',
    }
    if title != '' and text != '':
        r = requests.post('http://localhost:8000/wp-json/wp/v2/posts', headers=headers, json=json_data,
                          auth=('admin', 'admin'))
        if r.status_code == 201:
            article_url = r.json()['guid']['rendered']
    return article_url

Notice that I am passing my user/password, in this case, admin/admin for authentication purposes. For this very reason, I installed the authentication plugin. If all goes well, it will return the following output:

Want to see how it got rendered? here you go!

Sweet, isn’t it?

Conclusion

So… in this post, you learned how you can leverage the power of LLMs to automate a blog in a certain niche. In our case, a finance blog. Currently, Gemini APIs have very limited access to the Internet but one does not always need real-time data. You can modify this prompt further to return high-volume keywords and then set them as tags by using WordPress tags APIs. Like always, the code is available on GitHub.

Do you need to automate blogs using chatGPT or Google Bard APIs for your desired niche? let me know and I will create a system for you. Contact at kadnan@gmail.com

If you like this post then you should subscribe to my blog for future updates.

* indicates required