1. Home
  2. Docs
  3. Knowledge Base
  4. Examples – Python – Python Nodes
  5. OpenAI API Example

OpenAI API Example

Introduction: The Sentiment Analysis with GPT-3.5 Turbo Python Node allows you to leverage the power of OpenAI’s GPT-3.5 Turbo model to analyze the sentiment of a given text. This Python node script can be seamlessly integrated into MachinaTrader’s Visual Strategy Editor, enabling you to incorporate sentiment analysis directly into your trading strategies. With the ability to determine whether a text’s sentiment is positive, negative, or neutral, you can gain valuable insights to make more informed trading decisions.

Explanation: The provided Python node script leverages the OpenAI API and the GPT-3.5 Turbo model to perform sentiment analysis. The function compute_sentiment_chatgpt(text) is responsible for analyzing the sentiment of the input text using GPT-3.5 Turbo.

Here’s a breakdown of the key components in the script:

  1. OpenAI API Key Setup: The script starts by setting up the OpenAI API key, which is required to access the GPT-3.5 Turbo model. Make sure to replace the openai_api_key variable with your actual OpenAI API key.

  2. Function – compute_sentiment_chatgpt(text): This function takes a text parameter as input and sends a chat-like message to GPT-3.5 Turbo for sentiment analysis. The message includes a system role instructing GPT-3.5 Turbo that it’s a helpful assistant and a user role with the input text requesting the sentiment analysis. The model is asked to respond with a one-word answer in lowercase representing whether the sentiment is positive, negative, or neutral.

  3. API Call and Response Handling: The function sends an API request to OpenAI’s endpoint (API_URL) with the constructed message data in JSON format. It specifies the model, number of responses (n), and maximum tokens in the response (max_tokens). The temperature parameter controls the randomness of the model’s output. The response is then processed to extract the sentiment result.

  4. Output: The sentiment result is extracted from the API response and returned by the function. The result is a single word representing the sentiment of the input text.

Example Usage: The script demonstrates the usage of the compute_sentiment_chatgpt(text) function by analyzing the sentiment of the example text. The resulting sentiment, whether positive, negative, or neutral, is then printed to the console.

By incorporating this Python node script into MachinaTrader’s Visual Strategy Editor, you can easily perform sentiment analysis on various texts, allowing you to enhance your trading strategies with a deeper understanding of market sentiment.

For more information visit the OpenAI API documentation here: API Reference – OpenAI API

Was this article helpful to you? Yes No

How can we help?