Coded Example of LangChain Enabled Cooperative Agents



Coded Example of LangChain Enabled Cooperative Agents

A step-by-step guide to creating a LangChain enabled cooperative agent application for building a toy stock trading bot.

Generated by DALL-E 2

Table of Contents

  1. Introduction
  2. Useful Resources
  3. Application Code
    – Configuration
    – Import Packages
    – Define a CAMEL Agent
    – Define Roles and Set Task for Role-Playing
    – Create the Task Specifier
    – Create Role-Playing Inception Prompts
    – Create the AI Assistant and AI User
    – Start Role-Playing Session
  4. Application Output
  5. Conclusion

Introduction

In this article, we will walk through step-by-step a coded example of creating a LangChain enabled cooperative agent application for building a toy stock trading bot. The article is based on the 2023 paper ‘CAMEL: Communicative Agents for “Mind” Exploration of Large Scale Language Model Society’ in which researchers propose a novel cooperative agent framework called “role-playing”. This framework aims to facilitate autonomous cooperation among communicative agents and provide insight into their “cognitive” processes.

The role-playing framework involves agents prompting each other until a task is solved. At the beginning of the exercise the task is specified and a role is assigned to each agent. This is known as ‘inception prompting’ and is the only task specific human input into the process. The framework consists of two main roles: the AI assistant and the AI user. The AI user acts as the project manager and provides instructions to an AI assistant, who acts as a specialist and responds to the instructions with specific solutions. The conversation between the two agents follows a specific format to ensure consistent and accurate data generation with this format being well defined in the prompt. The conversation format is not specific to the task, rather it is part of the general framework for this technique. An example of this will be given later.

Figure 1 provides a graphic that depicts how the various parts described fit together. For more detail on the framework the full research paper can be found here, or a summary of the paper can be found here.

Figure 1 (Li et al, 2023)

Useful Resources

The code in this tutorial draws heavily on LangChain documentation.

LangChain documentation: https://python.langchain.com/docs/use_cases/more/agents/agent_simulations/camel_role_playing

The researchers implementation: https://github.com/lightaime/camel

Project website: https://www.camel-ai.org/

Arxiv paper: https://arxiv.org/abs/2303.17760

Application Code

The code in this notebook is complete and if copied into a notebook will produce a working agent.

Configuration

To run this code you will need an OpenAI account with a paid for subscription to access their large language model APIs.

If you don’t have access to gpt-4 you can switch this out for gpt-3.5-turbo and still get good results.

openai_api_key = "<Insert OpenAI Secure Key Here>"

model_name = "gpt-4"

Import Packages

from typing import List
from langchain.chat_models import ChatOpenAI
from langchain.prompts.chat import SystemMessagePromptTemplate,HumanMessagePromptTemplate
from langchain.schema import AIMessage, HumanMessage, SystemMessage, BaseMessage

Define a CAMEL Agent

The primary purpose of the CAMELAgent class is to make the agent stateful by acting as its memory, keeping track of the conversation history. The CAMEL agent takes as inputs messages and an instance of a large language model. In our case, we will be passing an instance of an OpenAI language model. We will discuss the system messages when we cover the specific agents created for this application.

The CAMEL agent will be used to instantiate the Task Specifier, the AI Assistant and the AI User — see figure 1.

class CAMELAgent:
def __init__(
self,
system_message: SystemMessage,
model: ChatOpenAI,
) -> None:
self.system_message = system_message
self.model = model
self.init_messages()

def reset(self) -> None:
self.init_messages()
return self.stored_messages

def init_messages(self) -> None:
self.stored_messages = [self.system_message]

def update_messages(self, message: BaseMessage) -> List[BaseMessage]:
self.stored_messages.append(message)
return self.stored_messages

def step(
self,
input_message: HumanMessage,
) -> AIMessage:
messages = self.update_messages(input_message)

output_message = self.model(messages)
self.update_messages(output_message)

return output_message

Define Roles and Set Task for Role-Playing

In this example, we will be asking the role-playing application to develop a trading bot for the stock market. To achieve this aim we first specify two roles that can work together to achieve this aim. We choose a Stock Trader who acts as the project manager and domain expert as well as a Python Developer who acts as the technical expert. We also specify the task we want the application to complete.

These are the only human inputs required to apply the role-playing application to a new task, the rest of the code generalises across tasks.

assistant_role_name = "Python Programmer"
user_role_name = "Stock Trader"
task = "Develop a trading bot for the stock market"
word_limit = 50 # word limit for task specifier

Create the Task Specifier

The purpose of the Task Specifier is to take as input a short description of the task and flesh it out with more details of what is required — make it more specific. The researchers who proposed the role-playing framework found that the provision of these extra details at the outset improved the performance of the application.

The Task Specifier is used once at the outset of the process. The output of the Task Specifier is handed to the two agents and they use the fleshed out task description as a goal to collaborate toward acheiving.

Here we define the messages required to instantiate the Task Specifier.

task_specifier_sys_msg = SystemMessage(content="You can make a task more specific.")

task_specifier_prompt = """Here is a task that {assistant_role_name} will help {user_role_name} to complete: {task}.
Please make it more specific. Be creative and imaginative.
Please reply with the specified task in {word_limit} words or less. Do not add anything else."""

task_specifier_template = HumanMessagePromptTemplate.from_template(
template=task_specifier_prompt
)

task_specifier_msg = task_specifier_template.format_messages(
assistant_role_name=assistant_role_name,
user_role_name=user_role_name,
task=task,
word_limit=word_limit,
)[0]

We instantiate the Task Specifier.

task_specify_agent = CAMELAgent(task_specifier_sys_msg, ChatOpenAI(temperature=1.0, 
openai_api_key=openai_api_key,
model_name=model_name))

We pass the Task Specifier the previously defined parameters specific to the task in hand. The Task Specifier returns the fleshed out task.

specified_task_msg = task_specify_agent.step(task_specifier_msg)

specified_task = specified_task_msg.content
print(f"Specified task: {specified_task_msg.content}")

We see that the fleshed out task message contains many more details about what is required of the collaborative agents.

Create Role-Playing Inception Prompts

Create the role-playing inception prompts for the AI assistant and AI user. These prompts provide detailed instructions to the agents as to what is expected of them. You will notice that many of the instructions are aimed at preventing certain undesirable behaviours. The developers of the framework found that without these specific directions the agents exhibited behaviours including role flipping, where the assistant and user switch roles; assistant repeating instructions without role flipping; flake replies, where the assistant promised action but failed to follow through; and infinite loops of meaningless conversation.

assistant_inception_prompt = """Never forget you are a {assistant_role_name} and I am a {user_role_name}. Never flip roles! Never instruct me!
We share a common interest in collaborating to successfully complete a task.
You must help me to complete the task.
Here is the task: {task}. Never forget our task!
I must instruct you based on your expertise and my needs to complete the task.

I must give you one instruction at a time.
You must write a specific solution that appropriately completes the requested instruction.
You must decline my instruction honestly if you cannot perform the instruction due to physical, moral, legal reasons or your capability and explain the reasons.
Do not add anything else other than your solution to my instruction.
You are never supposed to ask me any questions you only answer questions.
You are never supposed to reply with a flake solution. Explain your solutions.
Your solution must be declarative sentences and simple present tense.
Unless I say the task is completed, you should always start with:

Solution: <YOUR_SOLUTION>

<YOUR_SOLUTION> should be specific and provide preferable implementations and examples for task-solving.
Always end <YOUR_SOLUTION> with: Next request."""
user_inception_prompt = """Never forget you are a {user_role_name} and I am a {assistant_role_name}. Never flip roles! You will always instruct me.
We share a common interest in collaborating to successfully complete a task.
I must help you to complete the task.
Here is the task: {task}. Never forget our task!
You must instruct me based on my expertise and your needs to complete the task ONLY in the following two ways:

1. Instruct with a necessary input:
Instruction: <YOUR_INSTRUCTION>
Input: <YOUR_INPUT>

2. Instruct without any input:
Instruction: <YOUR_INSTRUCTION>
Input: None

The "Instruction" describes a task or question. The paired "Input" provides further context or information for the requested "Instruction".

You must give me one instruction at a time.
I must write a response that appropriately completes the requested instruction.
I must decline your instruction honestly if I cannot perform the instruction due to physical, moral, legal reasons or my capability and explain the reasons.
You should instruct me not ask me questions.
Now you must start to instruct me using the two ways described above.
Do not add anything else other than your instruction and the optional corresponding input!
Keep giving me instructions and necessary inputs until you think the task is completed.
When the task is completed, you must only reply with a single word <CAMEL_TASK_DONE>.
Never say <CAMEL_TASK_DONE> unless my responses have solved your task."""

Create the AI Assistant and AI User

Create a helper to get system messages for the AI assistant and AI user from the role names and task.

// LAST UPDATED ON 29/09
Amazon Most Wished For
def get_sys_msgs(assistant_role_name: str, user_role_name: str, task: str):
assistant_sys_template = SystemMessagePromptTemplate.from_template(
template=assistant_inception_prompt
)
assistant_sys_msg = assistant_sys_template.format_messages(
assistant_role_name=assistant_role_name,
user_role_name=user_role_name,
task=task,
)[0]

user_sys_template = SystemMessagePromptTemplate.from_template(
template=user_inception_prompt
)
user_sys_msg = user_sys_template.format_messages(
assistant_role_name=assistant_role_name,
user_role_name=user_role_name,
task=task,
)[0]

return assistant_sys_msg, user_sys_msg

Here we instantiate the AI Assistant and AI User using the CAMELAgent class.

assistant_sys_msg, user_sys_msg = get_sys_msgs(
assistant_role_name, user_role_name, specified_task
)

assistant_agent = CAMELAgent(assistant_sys_msg, ChatOpenAI(temperature=0.2,
openai_api_key=openai_api_key,
model_name=model_name))
user_agent = CAMELAgent(user_sys_msg, ChatOpenAI(temperature=0.2,
openai_api_key=openai_api_key,
model_name=model_name))

# Reset agents
assistant_agent.reset()
user_agent.reset()

# Initialize chats
user_msg = HumanMessage(
content=(
f"{user_sys_msg.content}. "
"Now start to give me introductions one by one. "
"Only reply with Instruction and Input."
)
)

assistant_msg = HumanMessage(content=f"{assistant_sys_msg.content}")
assistant_msg = assistant_agent.step(user_msg)

Start Role-Playing Session

Here we start the role playing session. The agents converse with each other passing message back and forth. A limit to the number of exchanges between them is set at 30 to safe guard against infinite loops.

print(f"Original task prompt:\n{task}\n")
print(f"Specified task prompt:\n{specified_task}\n")

chat_turn_limit, n = 30, 0
while n < chat_turn_limit:
n += 1
user_ai_msg = user_agent.step(assistant_msg)
user_msg = HumanMessage(content=user_ai_msg.content)
print(f"AI User ({user_role_name}):\n\n{user_msg.content}\n\n")

assistant_ai_msg = assistant_agent.step(user_msg)
assistant_msg = HumanMessage(content=assistant_ai_msg.content)
print(f"AI Assistant ({assistant_role_name}):\n\n{assistant_msg.content}\n\n")
if "<CAMEL_TASK_DONE>" in user_msg.content:
break

Application Output

The primary observation is that the application appears to achieve its stated goal or at least has a very good go at it. If feel absolutely confident that the stock trading bot would not beat the stock market but it looks like it would run and the steps taken look perfectly reasonable.

In this tutorial we use gpt-4 as the underlying large language model and so get a slightly different result to the researchers in the original paper. One difference is that the initial interaction in this output is odd. The Stock Trader is meant to issue instructions and the Python programer return results. Here however the first instruction includes the solution. This does not happen when using gpt-3. After the first interaction this doesn’t happen again.

Another interesting difference is that a gpt-4 based application delivers a more sophiticated result than the gpt-3 equivalent. Specifically, the gpt-4 solution uses an LSTM to predict stock prices whilst the gpt-3 based application uses logistic regression.

You should experiment with running the gpt-3 based application and perhaps test the resulting algorithms — on historic data of course. I’d be interested to know how you get on.

Original task prompt:
Develop a trading bot for the stock market

Specified task prompt:
Develop a Python-based, AI-driven trading bot for the US stock market that implements machine learning to predict future trends. The bot should use sentiment analysis for forecasting, supports stop-loss orders, automatic buying and selling, and provides daily performance reports.

AI User (Stock Trader):

To set up the environment for the trading bot, we need to install the necessary Python libraries. Here is the Python code to do this:

```python
# Importing necessary libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import yfinance as yf
import alpaca_trade_api as tradeapi
```

This code imports the necessary libraries for data manipulation (numpy, pandas), data visualization (matplotlib), machine learning (sklearn, keras), sentiment analysis (nltk), stock data fetching (yfinance), and trading (alpaca_trade_api).

Please make sure to install these libraries using pip:

```bash
pip install numpy pandas matplotlib sklearn keras nltk yfinance alpaca-trade-api
```

Also, download the vader_lexicon for sentiment analysis:

```python
nltk.download('vader_lexicon')
```

Please run these commands in your Python environment to set up the environment for the trading bot.


AI Assistant (Python Programmer):

Solution: To set up the environment for the trading bot, you need to install the necessary Python libraries. Here is the Python code to do this:

```python
# Importing necessary libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import yfinance as yf
import alpaca_trade_api as tradeapi
```

This code imports the necessary libraries for data manipulation (numpy, pandas), data visualization (matplotlib), machine learning (sklearn, keras), sentiment analysis (nltk), stock data fetching (yfinance), and trading (alpaca_trade_api).

Please make sure to install these libraries using pip:

```bash
pip install numpy pandas matplotlib sklearn keras nltk yfinance alpaca-trade-api
```

Also, download the vader_lexicon for sentiment analysis:

```python
nltk.download('vader_lexicon')
```

Please run these commands in your Python environment to set up the environment for the trading bot. Next request.


AI User (Stock Trader):

Instruction: Fetch the historical stock data.
Input: 'AAPL'


AI Assistant (Python Programmer):

Solution: To fetch the historical stock data for 'AAPL', we can use the yfinance library. Here is the Python code to do this:

```python
# Define the ticker symbol
tickerSymbol = 'AAPL'

# Get data on this ticker
tickerData = yf.Ticker(tickerSymbol)

# Get the historical prices for this ticker
tickerDf = tickerData.history(period='1d', start='2010-1-1', end='2020-12-31')

# See your data
print(tickerDf)
```

This code fetches the daily historical stock data for 'AAPL' from January 1, 2010, to December 31, 2020. The data includes open, high, low, close prices, and volume. Next request.


AI User (Stock Trader):

Instruction: Implement the sentiment analysis function.
Input: None


AI Assistant (Python Programmer):

Solution: To implement the sentiment analysis function, we can use the nltk library's SentimentIntensityAnalyzer. Here is the Python code to do this:

```python
# Initialize the SentimentIntensityAnalyzer
sia = SentimentIntensityAnalyzer()

def sentiment_analysis(text):
# Get the sentiment scores
sentiment = sia.polarity_scores(text)

# Return the compound score which is the aggregate of positive, negative and neutral scores
return sentiment['compound']
```

This code defines a function called sentiment_analysis that takes a text string as input and returns the compound sentiment score. The compound score is a metric that calculates the sum of all the lexicon ratings which have been normalized between -1(most extreme negative) and +1 (most extreme positive). Next request.


AI User (Stock Trader):

Instruction: Create a function to preprocess the stock data for the machine learning model.
Input: None


AI Assistant (Python Programmer):

Solution: To preprocess the stock data for the machine learning model, we can create a function that scales the data and reshapes it into a format suitable for the LSTM model. Here is the Python code to do this:

```python
# Initialize the MinMaxScaler
scaler = MinMaxScaler(feature_range=(0,1))

def preprocess_data(stock_data, look_back):
# Scale the stock data
scaled_data = scaler.fit_transform(stock_data['Close'].values.reshape(-1,1))

# Create empty lists to store the X and Y data
X_data, Y_data = [], []

# Loop through the data and create sequences for the model
for i in range(look_back, len(scaled_data)):
X_data.append(scaled_data[i-look_back:i, 0])
Y_data.append(scaled_data[i, 0])

# Convert the X and Y data to numpy arrays
X_data, Y_data = np.array(X_data), np.array(Y_data)

# Reshape the X data to fit the LSTM model
X_data = np.reshape(X_data, (X_data.shape[0], X_data.shape[1], 1))

return X_data, Y_data
```

This code defines a function called preprocess_data that takes the stock data and a look_back period as inputs. The function scales the 'Close' prices of the stock data to a range of 0 to 1, creates sequences of the scaled data for the model, and reshapes the sequences to fit the LSTM model. The function returns the X and Y data for the model. Next request.


AI User (Stock Trader):

Instruction: Develop the LSTM model for predicting future stock trends.
Input: None


AI Assistant (Python Programmer):

Solution: To develop the LSTM model for predicting future stock trends, we can use the keras library. Here is the Python code to do this:

```python
def create_model(X_data):
# Initialize the Sequential model
model = Sequential()

# Add the first LSTM layer with dropout
model.add(LSTM(units=50, return_sequences=True, input_shape=(X_data.shape[1], 1)))
model.add(Dropout(0.2))

# Add the second LSTM layer with dropout
model.add(LSTM(units=50, return_sequences=False))
model.add(Dropout(0.2))

# Add the output layer
model.add(Dense(units=1))

# Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')

return model
```

This code defines a function called create_model that takes the X data as input. The function initializes a Sequential model, adds two LSTM layers with dropout to prevent overfitting, and adds an output layer. The model is compiled with the Adam optimizer and the mean squared error loss function. The function returns the compiled model. Next request.


AI User (Stock Trader):

Instruction: Train the LSTM model with the preprocessed stock data.
Input: None


AI Assistant (Python Programmer):

Solution: To train the LSTM model with the preprocessed stock data, we can use the fit method of the model. Here is the Python code to do this:

```python
# Preprocess the stock data with a look_back period of 60 days
X_data, Y_data = preprocess_data(tickerDf, 60)

# Split the data into training and testing sets
X_train, X_test, Y_train, Y_test = train_test_split(X_data, Y_data, test_size=0.2, random_state=0)

# Create the LSTM model
model = create_model(X_train)

# Train the model
model.fit(X_train, Y_train, epochs=50, batch_size=32)
```

This code preprocesses the stock data with a look_back period of 60 days, splits the data into training and testing sets, creates the LSTM model, and trains the model with the training data for 50 epochs with a batch size of 32. Next request.


AI User (Stock Trader):

Instruction: Implement the function to place stop-loss orders.
Input: None


AI Assistant (Python Programmer):

Solution: To implement the function to place stop-loss orders, we can use the alpaca_trade_api library. Here is the Python code to do this:

```python
# Initialize the Alpaca API
api = tradeapi.REST('<APCA-API-KEY-ID>', '<APCA-API-SECRET-KEY>', base_url='https://paper-api.alpaca.markets')

def place_stop_loss_order(symbol, qty, stop_price):
# Place a stop-loss order
api.submit_order(
symbol=symbol,
qty=qty,
side='sell',
type='stop',
time_in_force='gtc',
stop_price=stop_price,
)
```

This code defines a function called place_stop_loss_order that takes a symbol, quantity, and stop price as inputs. The function uses the Alpaca API to submit a stop-loss order for the given symbol with the given quantity and stop price. The order is a 'sell' order with a 'stop' type and a 'gtc' (good till cancelled) time in force. Please replace '<APCA-API-KEY-ID>' and '<APCA-API-SECRET-KEY>' with your actual Alpaca API key ID and secret key. Next request.


AI User (Stock Trader):

Instruction: Implement the function for automatic buying and selling of stocks based on the LSTM model's predictions.
Input: None


AI Assistant (Python Programmer):

Solution: To implement the function for automatic buying and selling of stocks based on the LSTM model's predictions, we can use the predict method of the model and the Alpaca API. Here is the Python code to do this:

```python
def automatic_trading(symbol, qty):
# Fetch the latest stock data
stock_data = yf.Ticker(symbol).history(period='1d', start='2020-1-1', end='2020-12-31')

# Preprocess the stock data
X_data, _ = preprocess_data(stock_data, 60)

# Predict the future stock price
predicted_price = model.predict(X_data[-1:])

# If the predicted price is higher than the current price, buy the stock
if predicted_price > stock_data['Close'].iloc[-1]:
api.submit_order(
symbol=symbol,
qty=qty,
side='buy',
type='market',
time_in_force='gtc',
)
# If the predicted price is lower than the current price, sell the stock
elif predicted_price < stock_data['Close'].iloc[-1]:
api.submit_order(
symbol=symbol,
qty=qty,
side='sell',
type='market',
time_in_force='gtc',
)
```

This code defines a function called automatic_trading that takes a symbol and quantity as inputs. The function fetches the latest stock data for the given symbol, preprocesses the data, predicts the future stock price using the LSTM model, and places a 'buy' order if the predicted price is higher than the current price or a 'sell' order if the predicted price is lower than the current price. The orders are 'market' orders with a 'gtc' (good till cancelled) time in force. Next request.


Retrying langchain.chat_models.openai.ChatOpenAI.completion_with_retry.<locals>._completion_with_retry in 4.0 seconds as it raised RateLimitError: Rate limit reached for 10KTPM-200RPM in organization org-7jnEzG0R9U2IB4UjK2PmXUla on tokens per min. Limit: 10000 / min. Please try again in 6ms. Contact us through our help center at help.openai.com if you continue to have issues..
AI User (Stock Trader):

Instruction: Create a function to generate daily performance reports.
Input: None


AI Assistant (Python Programmer):

Solution: To create a function to generate daily performance reports, we can use the Alpaca API. Here is the Python code to do this:

```python
def generate_report():
# Get the account information
account = api.get_account()

# Get the list of positions
positions = api.list_positions()

# Print the account information
print(f"Portfolio Value: {account.portfolio_value}")
print(f"Buying Power: {account.buying_power}")
print(f"Total Cash: {account.cash}")

# Print the positions
for position in positions:
print(f"Symbol: {position.symbol}")
print(f"Quantity: {position.qty}")
print(f"Average Price: {position.avg_entry_price}")
print(f"Market Value: {position.market_value}")
print(f"Unrealized Profit/Loss: {position.unrealized_pl}")
print(f"Unrealized Profit/Loss %: {position.unrealized_intraday_plpc}")
print("-----------------------------")
```

This code defines a function called generate_report that gets the account information and the list of positions using the Alpaca API and prints the portfolio value, buying power, total cash, and details of each position including the symbol, quantity, average price, market value, unrealized profit/loss, and unrealized profit/loss percentage. Next request.


Retrying langchain.chat_models.openai.ChatOpenAI.completion_with_retry.<locals>._completion_with_retry in 4.0 seconds as it raised RateLimitError: Rate limit reached for 10KTPM-200RPM in organization org-7jnEzG0R9U2IB4UjK2PmXUla on tokens per min. Limit: 10000 / min. Please try again in 6ms. Contact us through our help center at help.openai.com if you continue to have issues..
AI User (Stock Trader):

Instruction: Combine all the functions to create the final trading bot.
Input: None


Solution: To combine all the functions to create the final trading bot, we can define a main function that calls the other functions. Here is the Python code to do this:

```python
def main():
# Define the symbol and quantity
symbol = 'AAPL'
qty = 1

# Fetch the historical stock data
stock_data = yf.Ticker(symbol).history(period='1d', start='2010-1-1', end='2020-12-31')

# Preprocess the stock data
X_data, Y_data = preprocess_data(stock_data, 60)

# Split the data into training and testing sets
X_train, X_test, Y_train, Y_test = train_test_split(X_data, Y_data, test_size=0.2, random_state=0)

# Create the LSTM model
model = create_model(X_train)

# Train the model
model.fit(X_train, Y_train, epochs=50, batch_size=32)

# Perform automatic trading
automatic_trading(symbol, qty)

# Generate the daily performance report
generate_report()
```

This code defines a main function that fetches the historical stock data for 'AAPL', preprocesses the data, splits the data into training and testing sets, creates the LSTM model, trains the model, performs automatic trading, and generates the daily performance report. You can run the main function to start the trading bot. Next request.


AI User (Stock Trader):

<CAMEL_TASK_DONE>


AI Assistant (Python Programmer):

Solution: To combine all the functions to create the final trading bot, we can define a main function that calls the other functions. Here is the Python code to do this:

```python
def main():
# Define the symbol and quantity
symbol = 'AAPL'
qty = 1

# Fetch the historical stock data
stock_data = yf.Ticker(symbol).history(period='1d', start='2010-1-1', end='2020-12-31')

# Preprocess the stock data
X_data, Y_data = preprocess_data(stock_data, 60)

# Split the data into training and testing sets
X_train, X_test, Y_train, Y_test = train_test_split(X_data, Y_data, test_size=0.2, random_state=0)

# Create the LSTM model
model = create_model(X_train)

# Train the model
model.fit(X_train, Y_train, epochs=50, batch_size=32)

# Perform automatic trading
automatic_trading(symbol, qty)

# Generate the daily performance report
generate_report()
```

This code defines a main function that fetches the historical stock data for 'AAPL', preprocesses the data, splits the data into training and testing sets, creates the LSTM model, trains the model, performs automatic trading, and generates the daily performance report. You can run the main function to start the trading bot. Next request.

Conclusion

This research paper presents a novel approach to prompting language models to complete complex tasks. The results of the role-playing framework are impressive. What the paper lacks is any real comparison to how this prompting framework compares to other prompting techniques. My instinct is that this technique, where agents with assumed, different but complementary roles collaborate together, has great potential for extracting new capabilities from large language models.

References

Want to get in touch?

Follow on Medium and Linkedin for practical guides for implementing cutting-edge technologies and summaries of the research papers introducing these technologies.

Original Post>

//Last UPDATE ON 25/09
Today's deals

Leave a Reply