MIXI DEVELOPERS
🐫

Camel-AIのCamelを触ってみた

2024/11/01に公開

Camel-AIとは

🐫 CAMELとは、AIの振る舞いを研究するためのオープンソースの研究グループです。

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

CAMELが目指していること:

  • AIの能力の成長過程を解明すること
  • AIの行動パターンを理解すること
  • AIがもたらす可能性を探ること
  • AIに関連するリスクを特定すること

これらの研究は、大規模な実験を通して行われています。

CAMELが開発・提供している研究ツール:

  • AIエージェント(自動で作業を行うAI)
  • タスク(AIに与える課題)
  • プロンプト(AIへの指示方法)
  • モデル(AIの基盤システム)
  • シミュレーション環境(AIの振る舞いを検証できる仮想空間)

このように、CAMELはAI研究をオープンに進め、誰もが研究に参加できる環境を整えています。

実際に動かしてみる

今回はdockerの環境を構築してcamel-aiを動かしてみました。

環境構築

https://github.com/camel-ai/camel/blob/master/.container/README.md

こちらに記載がある環境構築の手順に則って進めていきました。

.envファイルには OPENAI_API_KEY をいれておけば最低限の動作確認は実施できるかと思います。

トラブルシューティング

docker compose up -d の際にエラーが出た場合は、poetry lock を実行することでエラー解消する可能性があります。

https://github.com/camel-ai/camel/issues/1131

実行

今回はまずサンプルとして用意されているこちらのエージェントを動かしてみます。

https://github.com/camel-ai/camel/blob/master/examples/ai_society/role_playing.py

dockerの仮想環境の中でpythonのコードを実行します。

$ python examples/ai_society/role_playing.py

実際に動き出すとこのような形で進んでいきます。

今回のサンプルでは Python ProgrammerStock Trader のエージェントが協力してトレーディングボットの作成を行います。
実際のプロンプトの中身は

'task': 'Develop a Python-based trading bot that utilizes machine learning to analyze historical stock data, identify patterns, and execute buy/sell orders on a specific stock (e.g., Tesla) based on real-time market conditions. Implement risk management strategies and backtest the bot using data from the past year to optimize performance.', 'assistant_role': 'Python Programmer', 'user_role': 'Stock Trader'

Python programmerとStorck Trader共通でタスクが指示されています。
内容を簡単にまとめると

機械学習を利用して過去の株式データを分析し、パターンを特定し、リアルタイムの市況に基づいて特定の株式の買い注文と売り注文を実行するPython ベースの取引ボットを開発すること。

といった内容が記載されています。

またそれぞれのエージェントへのプロンプトの中身は以下のようになっています。

Python Programmer
===== RULES OF ASSISTANT =====
Never forget you are a Python Programmer and I am a Stock Trader. 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: Develop a Python-based trading bot that utilizes machine learning to analyze historical stock data, identify patterns, and execute buy/sell orders on a specific stock (e.g., Tesla) based on real-time market conditions. Implement risk management strategies and backtest the bot using data from the past year to optimize performance.. 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 solves the requested instruction and explain your solutions.
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.
Unless I say the task is completed, you should always start with:

Solution: <YOUR_SOLUTION>

<YOUR_SOLUTION> should be very specific, include detailed explanations and provide preferable detailed implementations and examples and lists for task-solving.
Always end <YOUR_SOLUTION> with: Next request.
Stock Trader
===== RULES OF USER =====
Never forget you are a Stock Trader and I am a Python Programmer. 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: Develop a Python-based trading bot that utilizes machine learning to analyze historical stock data, identify patterns, and execute buy/sell orders on a specific stock (e.g., Tesla) based on real-time market conditions. Implement risk management strategies and backtest the bot using data from the past year to optimize performance.. Never forget our task!
You must instruct me based on my expertise and your needs to solve 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 solves 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.'

簡単に記載されているプロンプトの内容をまとめると
与えられているそれぞれの役割の定義を忘れないでね。お互いの役割を勝手に交換しないでね。
一緒にタスクのゴールを目指して協力していきましょう。
実際にタスクのゴールに向けて指示を与えていく内容やプロセスの約束事(<YOUR_INSTRUCTION><YOUR_SOLUTION>)はこうですよ。
最後に全部終わったら <CAMEL_TASK_DONE> と書いてね。

その結果、出力の最後はこのようになりました。

result
### Explanation of the Code:
- **LiveTradingBot Class**: This class integrates the Alpaca API with the trading bot.
  - **Initialization**: The constructor initializes the Alpaca API connection and sets stop-loss and take-profit percentages.
  - **Entering a Trade**: The `enter_trade` method executes a market order to buy shares when entering a trade.
  - **Checking Exit Conditions**: The `check_exit_conditions` method checks if the current price meets the stop-loss or take-profit conditions and executes a market order to sell shares if necessary.
  - **Running the Bot**: The `run` method continuously fetches real-time market data, makes predictions using the model, and manages trades based on the predictions and exit conditions.
  - **Getting Latest Features**: The `get_latest_features` method is a placeholder for implementing the logic to retrieve the latest features for prediction.

### Important Notes:
- **API Key and Secret**: Make sure to replace `'YOUR_ALPACA_API_KEY'` and `'YOUR_ALPACA_API_SECRET'` with your actual Alpaca API credentials.
- **Testing**: Use the paper trading URL for testing to avoid real financial risks. Once you are confident in the bot's performance, you can switch to the live trading URL.
- **Feature Extraction**: You need to implement the logic to extract the latest features for prediction based on your model's requirements.

This implementation allows you to execute live trades based on the model's predictions and manage risk using stop-loss and take-profit mechanisms.

Next request.


AI User:

<CAMEL_TASK_DONE>


AI Assistant:

Solution: Thank you for collaborating on this trading bot project! If you have any further questions or need assistance with another task in the future, feel free to reach out.

作成したトレーディングボットのプログラムの説明や使い方の説明が記載されています。
プロンプトで指示を出したとおりに <CAMEL_TASK_DONE> が出力されていますね。
最後に出力結果の全文を折りたたんで貼っておきます。とても長いですが、マークダウン記法での出力のため見やすいです。

自分でエージェントを作って動かしてみる

次はサンプルコードなどを参考にして

  1. Pythonのライブラリをインストールするプログラムを作って実行
  2. インストールしたライブラリを使用し内積を計算するPythonのプログラムを作って実行
  3. 東京の天気予報を調べるプログラムを作って実行

という3つのタスクを実行するエージェントを作成してみました。
まずは実行結果の一部がこちらです。(内積の計算結果、天気予報表示)
実行結果の全体は次の章に記載しております。

result
Executing code block 1: {
The dot product of [8 9] and [5 4] is: 76
}
result
Weather report: tokyo

   _`/"".-.     Patchy rain nearby
    ,\_(   ).   +23(25) °C
     /(___(__)8 km/h
       ‘ ‘ ‘ ‘  10 km
      ‘ ‘ ‘ ‘   0.1 mm
                                                       ┌─────────────┐
┌──────────────────────────────┬───────────────────────┤  Fri 01 Nov ├───────────────────────┬──────────────────────────────┐
│            Morning           │             Noon      └──────┬──────┘     Evening           │             Night            │
├──────────────────────────────┼──────────────────────────────┼──────────────────────────────┼──────────────────────────────┤
│  _`/"".-.     Patchy rain ne…│  _`/"".-.     Patchy rain ne…│  _`/"".-.     Patchy rain ne…│  _`/"".-.     Patchy rain ne…│
│   ,\_(   ).   +23(25) °C     │   ,\_(   ).   +23(25) °C     │   ,\_(   ).   +23(25) °C     │   ,\_(   ).   +24(25) °C     │
│    /(___(__)11-15 km/h   │    /(___(__)7-10 km/h    │    /(___(__)8-10 km/h    │    /(___(__)9-12 km/h    │
│      ‘ ‘ ‘ ‘  10 km          │      ‘ ‘ ‘ ‘  10 km          │      ‘ ‘ ‘ ‘  10 km          │      ‘ ‘ ‘ ‘  10 km          │
│     ‘ ‘ ‘ ‘   0.1 mm | 100%  │     ‘ ‘ ‘ ‘   0.1 mm | 100%  │     ‘ ‘ ‘ ‘   0.1 mm | 100%  │     ‘ ‘ ‘ ‘   0.1 mm | 100%  │
└──────────────────────────────┴──────────────────────────────┴──────────────────────────────┴──────────────────────────────┘
                                                       ┌─────────────┐
┌──────────────────────────────┬───────────────────────┤  Sat 02 Nov ├───────────────────────┬──────────────────────────────┐
│            Morning           │             Noon      └──────┬──────┘     Evening           │             Night            │
├──────────────────────────────┼──────────────────────────────┼──────────────────────────────┼──────────────────────────────┤
│  _`/"".-.     Light rain sho…│      .-.      Moderate rain  │  _`/"".-.     Light rain sho…│  _`/"".-.     Light rain sho…│
│   ,\_(   ).   +22(25) °C     │     (   ).    21 °C          │   ,\_(   ).   +24(27) °C     │   ,\_(   ).   +25(27) °C     │
│    /(___(__)9-13 km/h    │    (___(__)4-5 km/h     │    /(___(__)21-34 km/h   │    /(___(__)36-63 km/h   │
│      ‘ ‘ ‘ ‘  10 km          │   ‚‘‚‘‚‘‚‘    7 km           │      ‘ ‘ ‘ ‘  10 km          │      ‘ ‘ ‘ ‘  10 km          │
│     ‘ ‘ ‘ ‘   0.2 mm | 100%  │   ‚’‚’‚’‚’    3.7 mm | 100%  │     ‘ ‘ ‘ ‘   1.2 mm | 100%  │     ‘ ‘ ‘ ‘   0.5 mm | 100%  │
└──────────────────────────────┴──────────────────────────────┴──────────────────────────────┴──────────────────────────────┘
                                                       ┌─────────────┐
┌──────────────────────────────┬───────────────────────┤  Sun 03 Nov ├───────────────────────┬──────────────────────────────┐
│            Morning           │             Noon      └──────┬──────┘     Evening           │             Night            │
├──────────────────────────────┼──────────────────────────────┼──────────────────────────────┼──────────────────────────────┤
│  _`/"".-.     Patchy rain ne…│  _`/"".-.     Patchy rain ne…│  _`/"".-.     Patchy rain ne…│  _`/"".-.     Patchy rain ne…│
│   ,\_(   ).   +23(25) °C     │   ,\_(   ).   22 °C          │   ,\_(   ).   21 °C          │   ,\_(   ).   22 °C          │
│    /(___(__)31-46 km/h   │    /(___(__)37-47 km/h   │    /(___(__)39-48 km/h   │    /(___(__)37-46 km/h   │
│      ‘ ‘ ‘ ‘  10 km          │      ‘ ‘ ‘ ‘  10 km          │      ‘ ‘ ‘ ‘  10 km          │      ‘ ‘ ‘ ‘  10 km          │
│     ‘ ‘ ‘ ‘   0.0 mm | 75%   │     ‘ ‘ ‘ ‘   0.0 mm | 87%   │     ‘ ‘ ‘ ‘   0.0 mm | 80%   │     ‘ ‘ ‘ ‘   0.0 mm | 72%   │
└──────────────────────────────┴──────────────────────────────┴──────────────────────────────┴──────────────────────────────┘
Location: 東京都, 日本 [34.2255804,139.294774527387]

ちゃんと動いていますよね。いいかんじですね。
途中何度か作成したプログラムの実行の許可を Y/n で求められる場面がありました。

この実際にこのエージェントを動かすためのプログラムはたったこれだけです。

from camel.agents import EmbodiedAgent
from camel.generators import SystemMessageGenerator as sys_msg_gen
from camel.messages import BaseMessage as bm
from camel.types import RoleType

def main():
    # Set the role name and the task
    role = 'Programmer'
    task = 'Writing and executing codes.'

    # Create the meta_dict and the role_tuple
    meta_dict = dict(role=role, task=task)
    role_tuple = (role, RoleType.EMBODIMENT)

    # Generate the system message based on this
    sys_msg = sys_msg_gen().from_dict(meta_dict=meta_dict, role_tuple=role_tuple)

    embodied_agent = EmbodiedAgent(
        system_message=sys_msg,
        tool_agents=None,
        code_interpreter=None,
        verbose=True
    )

    user_msg = bm.make_user_message(
        role_name='user',
        content=(
            '1. write a bash script to install numpy. '
            '2. then write a python script to compute '
            'the dot product of [8, 9] and [5, 4], '
            'and print the result. '
            '3. then write a script to search for '
            'the weather at tokyo with wttr.in/tokyo.'
        ),
    )

    response = embodied_agent.step(user_msg)
    print(response.msg.content)


if __name__ == "__main__":
    main()

あなたはプログラマーだよという役割、プログラムを書いて実行することがタスクだよ。という定義を最初にしています。
そのうえで詳細な指示を content で与えています。

実行結果

ai_society/role_playing.pyの実行結果

root@42307521d6d7:/app/camel# python examples/ai_society/role_playing.py
AI Assistant sys message:
BaseMessage(role_name='Python Programmer', role_type=<RoleType.ASSISTANT: 'assistant'>, meta_dict={'task': 'Develop a Python-based trading bot that utilizes machine learning to analyze historical stock data, identify patterns, and execute buy/sell orders on a specific stock (e.g., Tesla) based on real-time market conditions. Implement risk management strategies and backtest the bot using data from the past year to optimize performance.', 'assistant_role': 'Python Programmer', 'user_role': 'Stock Trader'}, content='===== RULES OF ASSISTANT =====\nNever forget you are a Python Programmer and I am a Stock Trader. Never flip roles! Never instruct me!\nWe share a common interest in collaborating to successfully complete a task.\nYou must help me to complete the task.\nHere is the task: Develop a Python-based trading bot that utilizes machine learning to analyze historical stock data, identify patterns, and execute buy/sell orders on a specific stock (e.g., Tesla) based on real-time market conditions. Implement risk management strategies and backtest the bot using data from the past year to optimize performance.. Never forget our task!\nI must instruct you based on your expertise and my needs to complete the task.\n\nI must give you one instruction at a time.\nYou must write a specific solution that appropriately solves the requested instruction and explain your solutions.\nYou must decline my instruction honestly if you cannot perform the instruction due to physical, moral, legal reasons or your capability and explain the reasons.\nUnless I say the task is completed, you should always start with:\n\nSolution: <YOUR_SOLUTION>\n\n<YOUR_SOLUTION> should be very specific, include detailed explanations and provide preferable detailed implementations and examples and lists for task-solving.\nAlways end <YOUR_SOLUTION> with: Next request.', video_bytes=None, image_list=None, image_detail='auto', video_detail='low')

AI User sys message:
BaseMessage(role_name='Stock Trader', role_type=<RoleType.USER: 'user'>, meta_dict={'task': 'Develop a Python-based trading bot that utilizes machine learning to analyze historical stock data, identify patterns, and execute buy/sell orders on a specific stock (e.g., Tesla) based on real-time market conditions. Implement risk management strategies and backtest the bot using data from the past year to optimize performance.', 'assistant_role': 'Python Programmer', 'user_role': 'Stock Trader'}, content='===== RULES OF USER =====\nNever forget you are a Stock Trader and I am a Python Programmer. Never flip roles! You will always instruct me.\nWe share a common interest in collaborating to successfully complete a task.\nI must help you to complete the task.\nHere is the task: Develop a Python-based trading bot that utilizes machine learning to analyze historical stock data, identify patterns, and execute buy/sell orders on a specific stock (e.g., Tesla) based on real-time market conditions. Implement risk management strategies and backtest the bot using data from the past year to optimize performance.. Never forget our task!\nYou must instruct me based on my expertise and your needs to solve the task ONLY in the following two ways:\n\n1. Instruct with a necessary input:\nInstruction: <YOUR_INSTRUCTION>\nInput: <YOUR_INPUT>\n\n2. Instruct without any input:\nInstruction: <YOUR_INSTRUCTION>\nInput: None\n\nThe "Instruction" describes a task or question. The paired "Input" provides further context or information for the requested "Instruction".\n\nYou must give me one instruction at a time.\nI must write a response that appropriately solves the requested instruction.\nI must decline your instruction honestly if I cannot perform the instruction due to physical, moral, legal reasons or my capability and explain the reasons.\nYou should instruct me not ask me questions.\nNow you must start to instruct me using the two ways described above.\nDo not add anything else other than your instruction and the optional corresponding input!\nKeep giving me instructions and necessary inputs until you think the task is completed.\nWhen the task is completed, you must only reply with a single word <CAMEL_TASK_DONE>.\nNever say <CAMEL_TASK_DONE> unless my responses have solved your task.', video_bytes=None, image_list=None, image_detail='auto', video_detail='low')

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

Specified task prompt:
Develop a Python-based trading bot that utilizes machine learning to analyze historical stock data, identify patterns, and execute buy/sell orders on a specific stock (e.g., Tesla) based on real-time market conditions. Implement risk management strategies and backtest the bot using data from the past year to optimize performance.

Final task prompt:
Develop a Python-based trading bot that utilizes machine learning to analyze historical stock data, identify patterns, and execute buy/sell orders on a specific stock (e.g., Tesla) based on real-time market conditions. Implement risk management strategies and backtest the bot using data from the past year to optimize performance.

AI User:

Instruction: Set up a Python environment with the necessary libraries for data analysis and machine learning.
Input: Include libraries such as pandas, numpy, scikit-learn, and matplotlib.

AI Assistant:

Solution: To set up a Python environment for data analysis and machine learning, you can use a package manager like pip to install the necessary libraries. Here’s how you can do it step-by-step:

  1. Install Python: Make sure you have Python installed on your machine. You can download it from python.org.

  2. Create a Virtual Environment (optional but recommended): This helps to manage dependencies for different projects separately.

    python -m venv trading_bot_env
    
  3. Activate the Virtual Environment:

    • On Windows:
      trading_bot_env\Scripts\activate
      
    • On macOS/Linux:
      source trading_bot_env/bin/activate
      
  4. Install the Necessary Libraries: Use pip to install the required libraries for data analysis and machine learning.

    pip install pandas numpy scikit-learn matplotlib
    
  5. Verify Installation: You can verify that the libraries are installed correctly by running the following commands in a Python shell:

    import pandas as pd
    import numpy as np
    from sklearn import datasets
    import matplotlib.pyplot as plt
    
    print("Libraries imported successfully!")
    

This setup will provide you with the essential tools to analyze historical stock data, implement machine learning algorithms, and visualize data effectively.

Next request.

AI User:

Instruction: Gather historical stock data for Tesla (TSLA) for the past year.
Input: Use a data source like Yahoo Finance or Alpha Vantage to download the data in CSV format.

AI Assistant:

Solution: To gather historical stock data for Tesla (TSLA) for the past year, you can use the yfinance library, which allows you to easily download stock data from Yahoo Finance. Here’s how to do it step-by-step:

  1. Install the yfinance Library: If you haven't installed it yet, you can do so using pip:

    pip install yfinance
    
  2. Download Historical Data: You can use the following Python code to download the historical stock data for Tesla (TSLA) for the past year and save it as a CSV file.

    import yfinance as yf
    import pandas as pd
    
    # Define the stock symbol and the time period
    stock_symbol = 'TSLA'
    start_date = '2022-10-01'  # One year ago from today
    end_date = '2023-10-01'     # Today's date
    
    # Download the historical stock data
    tsla_data = yf.download(stock_symbol, start=start_date, end=end_date)
    
    # Save the data to a CSV file
    tsla_data.to_csv('TSLA_historical_data.csv')
    
    print("Historical data for Tesla (TSLA) has been downloaded and saved as 'TSLA_historical_data.csv'.")
    
  3. Explanation of the Code:

    • We import the necessary libraries: yfinance for downloading stock data and pandas for handling data.
    • We define the stock symbol for Tesla and specify the start and end dates for the data we want to retrieve.
    • We use the yf.download() function to fetch the historical data.
    • Finally, we save the downloaded data to a CSV file named TSLA_historical_data.csv.

This will give you a CSV file containing the historical stock data for Tesla over the past year, which you can then use for analysis and machine learning.

Next request.

AI User:

Instruction: Preprocess the historical stock data to prepare it for machine learning analysis.
Input: Include steps such as handling missing values, feature engineering (e.g., creating moving averages), and normalizing the data.

AI Assistant:

Solution: Preprocessing historical stock data is crucial for preparing it for machine learning analysis. Below are the steps to handle missing values, perform feature engineering (such as creating moving averages), and normalize the data.

  1. Load the Historical Data: First, we need to load the CSV file containing the historical stock data.

  2. Handle Missing Values: We will check for any missing values and decide how to handle them (e.g., filling them or dropping them).

  3. Feature Engineering: We will create additional features such as moving averages.

  4. Normalize the Data: We will scale the data to ensure that all features contribute equally to the analysis.

Here’s how you can implement these steps in Python:

import pandas as pd
from sklearn.preprocessing import MinMaxScaler

# Step 1: Load the historical data
data = pd.read_csv('TSLA_historical_data.csv', index_col='Date', parse_dates=True)

# Step 2: Handle missing values
# Check for missing values
print(data.isnull().sum())

# Fill missing values with the previous value (forward fill)
data.fillna(method='ffill', inplace=True)

# Alternatively, you could drop rows with missing values
# data.dropna(inplace=True)

# Step 3: Feature Engineering
# Create moving averages
data['MA_5'] = data['Close'].rolling(window=5).mean()  # 5-day moving average
data['MA_20'] = data['Close'].rolling(window=20).mean()  # 20-day moving average

# Create additional features if needed (e.g., daily returns)
data['Daily_Return'] = data['Close'].pct_change()

# Step 4: Normalize the Data
# Select features for normalization
features = ['Close', 'MA_5', 'MA_20', 'Daily_Return']
data = data[features]

# Initialize the MinMaxScaler
scaler = MinMaxScaler()

# Fit and transform the data
data[features] = scaler.fit_transform(data[features])

# Display the preprocessed data
print(data.head())

# Save the preprocessed data to a new CSV file
data.to_csv('TSLA_preprocessed_data.csv')

print("Data preprocessing completed and saved as 'TSLA_preprocessed_data.csv'.")

Explanation of the Code:

  • Loading Data: We load the historical stock data from the CSV file and parse the dates.
  • Handling Missing Values: We check for missing values and use forward fill to fill them. Alternatively, we could drop rows with missing values.
  • Feature Engineering: We create moving averages (5-day and 20-day) and calculate daily returns as additional features.
  • Normalization: We use MinMaxScaler from sklearn to scale the features between 0 and 1, which is important for many machine learning algorithms.
  • Saving Preprocessed Data: Finally, we save the preprocessed data to a new CSV file for future use.

This preprocessing will prepare the historical stock data for machine learning analysis effectively.

Next request.

AI User:

Instruction: Implement a machine learning model to predict stock prices based on the preprocessed data.
Input: Use a regression model such as Linear Regression or Random Forest Regressor from scikit-learn.

AI Assistant:

Solution: To implement a machine learning model to predict stock prices based on the preprocessed data, we can use a regression model such as Linear Regression or Random Forest Regressor from scikit-learn. Below, I will demonstrate how to use both models to predict the closing price of Tesla (TSLA) based on the preprocessed features.

Steps to Implement the Machine Learning Model:

  1. Load the Preprocessed Data: Load the preprocessed data from the CSV file.
  2. Split the Data: Divide the data into training and testing sets.
  3. Train the Model: Train the regression model on the training set.
  4. Make Predictions: Use the model to make predictions on the test set.
  5. Evaluate the Model: Assess the model's performance using metrics such as Mean Absolute Error (MAE) or Mean Squared Error (MSE).

Here’s how you can implement this in Python:

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error, mean_squared_error

# Step 1: Load the preprocessed data
data = pd.read_csv('TSLA_preprocessed_data.csv', index_col='Date', parse_dates=True)

# Step 2: Split the data into features and target variable
X = data[['MA_5', 'MA_20', 'Daily_Return']]  # Features
y = data['Close']  # Target variable

# Split the data into training and testing sets (80% train, 20% test)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Step 3: Train the Linear Regression model
linear_model = LinearRegression()
linear_model.fit(X_train, y_train)

# Step 4: Make predictions with Linear Regression
y_pred_linear = linear_model.predict(X_test)

# Step 5: Evaluate the Linear Regression model
mae_linear = mean_absolute_error(y_test, y_pred_linear)
mse_linear = mean_squared_error(y_test, y_pred_linear)

print(f"Linear Regression MAE: {mae_linear}")
print(f"Linear Regression MSE: {mse_linear}")

# Step 3: Train the Random Forest Regressor model
rf_model = RandomForestRegressor(n_estimators=100, random_state=42)
rf_model.fit(X_train, y_train)

# Step 4: Make predictions with Random Forest Regressor
y_pred_rf = rf_model.predict(X_test)

# Step 5: Evaluate the Random Forest Regressor model
mae_rf = mean_absolute_error(y_test, y_pred_rf)
mse_rf = mean_squared_error(y_test, y_pred_rf)

print(f"Random Forest MAE: {mae_rf}")
print(f"Random Forest MSE: {mse_rf}")

Explanation of the Code:

  • Loading Data: We load the preprocessed data that contains the features and the target variable (closing price).
  • Splitting Data: We split the data into features (X) and target variable (y), and then further split it into training and testing sets using train_test_split.
  • Training the Model: We create and train both a Linear Regression model and a Random Forest Regressor model using the training data.
  • Making Predictions: We use both models to make predictions on the test set.
  • Evaluating the Model: We calculate the Mean Absolute Error (MAE) and Mean Squared Error (MSE) for both models to assess their performance.

This implementation will allow you to predict stock prices based on the preprocessed data using regression models.

Next request.

AI User:

Instruction: Implement a risk management strategy for the trading bot, including stop-loss and take-profit mechanisms.
Input: Define the parameters for stop-loss and take-profit levels based on a percentage of the entry price.

AI Assistant:

Solution: Implementing a risk management strategy is crucial for any trading bot to minimize losses and secure profits. Below, I will outline how to implement stop-loss and take-profit mechanisms based on a percentage of the entry price.

Steps to Implement Risk Management Strategy:

  1. Define Stop-Loss and Take-Profit Parameters: Set the percentage levels for stop-loss and take-profit.
  2. Implement the Logic: Create functions to determine when to execute a stop-loss or take-profit order based on the current price relative to the entry price.

Example Implementation:

Here’s how you can implement this in Python:

class TradingBot:
    def __init__(self, stop_loss_pct=0.02, take_profit_pct=0.05):
        """
        Initialize the trading bot with stop-loss and take-profit percentages.

        :param stop_loss_pct: Percentage for stop-loss (e.g., 0.02 for 2%)
        :param take_profit_pct: Percentage for take-profit (e.g., 0.05 for 5%)
        """
        self.stop_loss_pct = stop_loss_pct
        self.take_profit_pct = take_profit_pct
        self.entry_price = None

    def enter_trade(self, entry_price):
        """
        Enter a trade by setting the entry price.

        :param entry_price: The price at which the trade is entered.
        """
        self.entry_price = entry_price
        print(f"Entered trade at price: {self.entry_price}")

    def check_exit_conditions(self, current_price):
        """
        Check if the current price meets the stop-loss or take-profit conditions.

        :param current_price: The current market price of the stock.
        :return: A string indicating whether to exit the trade.
        """
        if self.entry_price is None:
            return "No active trade."

        stop_loss_price = self.entry_price * (1 - self.stop_loss_pct)
        take_profit_price = self.entry_price * (1 + self.take_profit_pct)

        if current_price <= stop_loss_price:
            return "Stop-loss triggered. Exit trade."
        elif current_price >= take_profit_price:
            return "Take-profit triggered. Exit trade."
        else:
            return "Hold position."

# Example usage
trading_bot = TradingBot(stop_loss_pct=0.02, take_profit_pct=0.05)

# Simulate entering a trade
trading_bot.enter_trade(entry_price=100)

# Simulate checking exit conditions at different current prices
current_prices = [98, 102, 95, 105]

for price in current_prices:
    result = trading_bot.check_exit_conditions(current_price=price)
    print(f"Current Price: {price} - {result}")

Explanation of the Code:

  • TradingBot Class: This class encapsulates the trading bot's functionality, including stop-loss and take-profit parameters.
  • Initialization: The constructor initializes the stop-loss and take-profit percentages.
  • Entering a Trade: The enter_trade method sets the entry price when a trade is initiated.
  • Checking Exit Conditions: The check_exit_conditions method calculates the stop-loss and take-profit prices based on the entry price and checks if the current price meets either condition. It returns a message indicating whether to exit the trade or hold the position.
  • Example Usage: The example simulates entering a trade at a price of 100 and checks exit conditions at various current prices.

This implementation provides a basic framework for managing risk in your trading bot by defining stop-loss and take-profit levels based on a percentage of the entry price.

Next request.

AI User:

Instruction: Backtest the trading bot using historical data to evaluate its performance.
Input: Implement a backtesting function that simulates trades based on the predictions and risk management strategy.

AI Assistant:

Solution: To backtest the trading bot using historical data, we will implement a backtesting function that simulates trades based on the predictions made by the machine learning model and applies the risk management strategy (stop-loss and take-profit).

Steps to Implement Backtesting:

  1. Load Historical Data: Load the preprocessed historical data.
  2. Simulate Trades: Iterate through the historical data, making buy/sell decisions based on the model's predictions and applying the risk management strategy.
  3. Calculate Performance Metrics: Track the performance of the trading strategy, including total returns, number of trades, and win/loss ratio.

Here’s how you can implement this in Python:

import pandas as pd

class TradingBot:
    def __init__(self, stop_loss_pct=0.02, take_profit_pct=0.05):
        self.stop_loss_pct = stop_loss_pct
        self.take_profit_pct = take_profit_pct
        self.entry_price = None
        self.position = 0  # 1 for long, 0 for no position

    def enter_trade(self, entry_price):
        self.entry_price = entry_price
        self.position = 1  # Entering a long position
        print(f"Entered trade at price: {self.entry_price}")

    def check_exit_conditions(self, current_price):
        if self.entry_price is None:
            return "No active trade."

        stop_loss_price = self.entry_price * (1 - self.stop_loss_pct)
        take_profit_price = self.entry_price * (1 + self.take_profit_pct)

        if current_price <= stop_loss_price:
            self.position = 0  # Exit position
            return "Stop-loss triggered. Exit trade."
        elif current_price >= take_profit_price:
            self.position = 0  # Exit position
            return "Take-profit triggered. Exit trade."
        else:
            return "Hold position."

def backtest_trading_bot(data, model):
    trading_bot = TradingBot(stop_loss_pct=0.02, take_profit_pct=0.05)
    total_returns = 0
    num_trades = 0
    win_trades = 0

    for i in range(len(data)):
        current_price = data['Close'].iloc[i]

        # Predict the next price (for simplicity, using the current price as a placeholder)
        if i < len(data) - 1:
            predicted_price = model.predict(data[['MA_5', 'MA_20', 'Daily_Return']].iloc[[i]])[0]
        else:
            predicted_price = current_price  # No prediction available for the last entry

        # Enter trade if the predicted price is higher than the current price
        if predicted_price > current_price and trading_bot.position == 0:
            trading_bot.enter_trade(current_price)
            num_trades += 1

        # Check exit conditions
        exit_condition = trading_bot.check_exit_conditions(current_price)

        # If exited, calculate returns
        if trading_bot.position == 0 and trading_bot.entry_price is not None:
            trade_return = current_price - trading_bot.entry_price
            total_returns += trade_return
            if trade_return > 0:
                win_trades += 1
            trading_bot.entry_price = None  # Reset entry price for the next trade

    win_ratio = win_trades / num_trades if num_trades > 0 else 0
    print(f"Total Returns: {total_returns}")
    print(f"Number of Trades: {num_trades}")
    print(f"Win Ratio: {win_ratio:.2f}")

# Example usage
# Load the preprocessed data
data = pd.read_csv('TSLA_preprocessed_data.csv', index_col='Date', parse_dates=True)

# Assuming you have a trained model (e.g., linear_model or rf_model)
# For demonstration, we will use the Linear Regression model from previous steps
backtest_trading_bot(data, linear_model)

Explanation of the Code:

  • TradingBot Class: This class is similar to the previous implementation, with methods for entering trades and checking exit conditions.
  • Backtesting Function: The backtest_trading_bot function takes the historical data and a trained model as inputs.
    • It initializes the trading bot and tracks total returns, number of trades, and win trades.
    • It iterates through the historical data, making predictions using the model and entering trades based on the predicted price.
    • It checks exit conditions and calculates returns for each trade.
  • Performance Metrics: At the end of the backtest, it prints the total returns, number of trades, and win ratio.

This implementation allows you to evaluate the performance of the trading strategy using historical data, providing insights into its effectiveness.

Next request.

AI User:

Instruction: Optimize the trading bot's parameters (e.g., stop-loss and take-profit percentages) using a grid search or random search method.
Input: Define a function that tests different combinations of parameters and evaluates performance based on backtesting results.

AI Assistant:

Solution: To optimize the trading bot's parameters (such as stop-loss and take-profit percentages), we can implement a grid search or random search method. In this case, I will demonstrate a grid search approach, where we will test different combinations of stop-loss and take-profit percentages and evaluate their performance based on backtesting results.

Steps to Implement Parameter Optimization:

  1. Define a Function for Backtesting: Modify the backtesting function to accept stop-loss and take-profit parameters.
  2. Implement Grid Search: Create a function that iterates through combinations of stop-loss and take-profit percentages, performs backtesting, and records the results.
  3. Evaluate Performance: Track the best-performing parameter combination based on total returns or win ratio.

Here’s how you can implement this in Python:

import numpy as np

def optimize_trading_bot(data, model, stop_loss_range, take_profit_range):
    best_total_returns = -np.inf
    best_params = None

    # Iterate through combinations of stop-loss and take-profit percentages
    for stop_loss_pct in stop_loss_range:
        for take_profit_pct in take_profit_range:
            trading_bot = TradingBot(stop_loss_pct=stop_loss_pct, take_profit_pct=take_profit_pct)
            total_returns = 0
            num_trades = 0
            win_trades = 0

            for i in range(len(data)):
                current_price = data['Close'].iloc[i]

                # Predict the next price
                if i < len(data) - 1:
                    predicted_price = model.predict(data[['MA_5', 'MA_20', 'Daily_Return']].iloc[[i]])[0]
                else:
                    predicted_price = current_price

                # Enter trade if the predicted price is higher than the current price
                if predicted_price > current_price and trading_bot.position == 0:
                    trading_bot.enter_trade(current_price)
                    num_trades += 1

                # Check exit conditions
                exit_condition = trading_bot.check_exit_conditions(current_price)

                # If exited, calculate returns
                if trading_bot.position == 0 and trading_bot.entry_price is not None:
                    trade_return = current_price - trading_bot.entry_price
                    total_returns += trade_return
                    if trade_return > 0:
                        win_trades += 1
                    trading_bot.entry_price = None  # Reset entry price for the next trade

            # Evaluate performance
            if total_returns > best_total_returns:
                best_total_returns = total_returns
                best_params = (stop_loss_pct, take_profit_pct)

    print(f"Best Total Returns: {best_total_returns}")
    print(f"Best Parameters - Stop Loss: {best_params[0]}, Take Profit: {best_params[1]}")

# Example usage
# Load the preprocessed data
data = pd.read_csv('TSLA_preprocessed_data.csv', index_col='Date', parse_dates=True)

# Assuming you have a trained model (e.g., linear_model or rf_model)
# Define ranges for stop-loss and take-profit percentages
stop_loss_range = [0.01, 0.02, 0.03]  # 1%, 2%, 3%
take_profit_range = [0.03, 0.05, 0.07]  # 3%, 5%, 7%

# Optimize trading bot parameters
optimize_trading_bot(data, linear_model, stop_loss_range, take_profit_range)

Explanation of the Code:

  • Optimize Trading Bot Function: The optimize_trading_bot function takes the historical data, a trained model, and ranges for stop-loss and take-profit percentages.
    • It initializes variables to track the best total returns and corresponding parameters.
    • It iterates through all combinations of stop-loss and take-profit percentages.
    • For each combination, it performs backtesting using the modified TradingBot class and calculates total returns.
    • It updates the best parameters if the current combination yields better returns.
  • Example Usage: The example shows how to load the preprocessed data, define ranges for stop-loss and take-profit percentages, and call the optimization function.

This implementation allows you to systematically test different parameter combinations and identify the optimal settings for your trading bot.

Next request.

AI User:

Instruction: Integrate the trading bot with a real-time market data API to execute live trades based on the model's predictions.
Input: Use an API like Alpaca or Interactive Brokers for executing trades and retrieving real-time market data.

AI Assistant:

Solution: To integrate the trading bot with a real-time market data API for executing live trades based on the model's predictions, we can use the Alpaca API. Alpaca provides a user-friendly interface for trading stocks and retrieving real-time market data.

Steps to Integrate the Trading Bot with Alpaca API:

  1. Set Up an Alpaca Account: Create an account on Alpaca and obtain your API key and secret.
  2. Install the Alpaca Trade API: Install the Alpaca Python library using pip.
  3. Connect to the Alpaca API: Use the API key and secret to authenticate and connect to the Alpaca API.
  4. Implement Live Trading Logic: Modify the trading bot to execute buy/sell orders based on the model's predictions and real-time market data.

Example Implementation:

Here’s how you can implement this in Python:

  1. Install the Alpaca Trade API:

    pip install alpaca-trade-api
    
  2. Integrate the Trading Bot:

import alpaca_trade_api as tradeapi
import pandas as pd
import time

class LiveTradingBot:
    def __init__(self, api_key, api_secret, base_url, stop_loss_pct=0.02, take_profit_pct=0.05):
        self.api = tradeapi.REST(api_key, api_secret, base_url, api_version='v2')
        self.stop_loss_pct = stop_loss_pct
        self.take_profit_pct = take_profit_pct
        self.entry_price = None
        self.position = 0  # 1 for long, 0 for no position
        self.symbol = 'TSLA'

    def enter_trade(self, entry_price):
        self.entry_price = entry_price
        self.position = 1  # Entering a long position
        self.api.submit_order(
            symbol=self.symbol,
            qty=1,  # Number of shares to buy
            side='buy',
            type='market',
            time_in_force='gtc'
        )
        print(f"Entered trade at price: {self.entry_price}")

    def check_exit_conditions(self, current_price):
        if self.entry_price is None:
            return "No active trade."

        stop_loss_price = self.entry_price * (1 - self.stop_loss_pct)
        take_profit_price = self.entry_price * (1 + self.take_profit_pct)

        if current_price <= stop_loss_price:
            self.position = 0  # Exit position
            self.api.submit_order(
                symbol=self.symbol,
                qty=1,  # Number of shares to sell
                side='sell',
                type='market',
                time_in_force='gtc'
            )
            print("Stop-loss triggered. Exit trade.")
        elif current_price >= take_profit_price:
            self.position = 0  # Exit position
            self.api.submit_order(
                symbol=self.symbol,
                qty=1,  # Number of shares to sell
                side='sell',
                type='market',
                time_in_force='gtc'
            )
            print("Take-profit triggered. Exit trade.")
        else:
            return "Hold position."

    def run(self, model):
        while True:
            # Get real-time market data
            current_price = self.api.get_last_trade(self.symbol).price

            # Predict the next price using the model
            # Here we assume you have a method to get the latest features
            latest_features = self.get_latest_features()  # Implement this method based on your features
            predicted_price = model.predict(latest_features)[0]

            # Enter trade if the predicted price is higher than the current price
            if predicted_price > current_price and self.position == 0:
                self.enter_trade(current_price)

            # Check exit conditions
            self.check_exit_conditions(current_price)

            # Sleep for a while before the next iteration
            time.sleep(60)  # Check every minute

    def get_latest_features(self):
        # Implement this method to return the latest features for prediction
        # For example, you can fetch the latest moving averages and daily returns
        pass

# Example usage
api_key = 'YOUR_ALPACA_API_KEY'
api_secret = 'YOUR_ALPACA_API_SECRET'
base_url = 'https://paper-api.alpaca.markets'  # Use paper trading URL for testing

live_trading_bot = LiveTradingBot(api_key, api_secret, base_url)
# Assuming you have a trained model (e.g., linear_model or rf_model)
live_trading_bot.run(linear_model)

Explanation of the Code:

  • LiveTradingBot Class: This class integrates the Alpaca API with the trading bot.
    • Initialization: The constructor initializes the Alpaca API connection and sets stop-loss and take-profit percentages.
    • Entering a Trade: The enter_trade method executes a market order to buy shares when entering a trade.
    • Checking Exit Conditions: The check_exit_conditions method checks if the current price meets the stop-loss or take-profit conditions and executes a market order to sell shares if necessary.
    • Running the Bot: The run method continuously fetches real-time market data, makes predictions using the model, and manages trades based on the predictions and exit conditions.
    • Getting Latest Features: The get_latest_features method is a placeholder for implementing the logic to retrieve the latest features for prediction.

Important Notes:

  • API Key and Secret: Make sure to replace 'YOUR_ALPACA_API_KEY' and 'YOUR_ALPACA_API_SECRET' with your actual Alpaca API credentials.
  • Testing: Use the paper trading URL for testing to avoid real financial risks. Once you are confident in the bot's performance, you can switch to the live trading URL.
  • Feature Extraction: You need to implement the logic to extract the latest features for prediction based on your model's requirements.

This implementation allows you to execute live trades based on the model's predictions and manage risk using stop-loss and take-profit mechanisms.

Next request.

AI User:

<CAMEL_TASK_DONE>

AI Assistant:

Solution: Thank you for collaborating on this trading bot project! If you have any further questions or need assistance with another task in the future, feel free to reach out.

自作したエージェントの実行結果

root@42307521d6d7:/app/camel# python examples/weather.py

Explanation:
To accomplish the tasks you've outlined, I will perform the following actions:

  1. Create a Bash script to install NumPy using pip. This will ensure that the necessary library is available for the Python script that follows.
  2. Create a Python script that computes the dot product of the two lists [8, 9] and [5, 4]. The dot product is calculated as the sum of the products of the corresponding entries of the two sequences.
  3. Create a Bash script to fetch the weather information for Tokyo using the wttr.in service.

Step 1: Bash Script to Install NumPy

I will write a Bash script named install_numpy.sh that uses pip to install NumPy.

Step 2: Python Script for Dot Product Calculation

Next, I will write a Python script named dot_product.py that computes the dot product of the two lists.

Step 3: Bash Script to Fetch Weather Information

Finally, I will write another Bash script named get_weather.sh that uses curl to fetch the weather information for Tokyo from wttr.in.

Now, let's write the code for each of these scripts.

Bash Script to Install NumPy

Code:

install_numpy.sh

#!/bin/bash

This script installs NumPy using pip

pip install numpy

Explanation:

Python Script for Dot Product Calculation

Code:

dot_product.py

import numpy as np

Define the vectors

a = np.array([8, 9])
b = np.array([5, 4])

Compute the dot product

dot_product = np.dot(a, b)

Print the result

print(f"The dot product of {a} and {b} is: {dot_product}")

Explanation:

Bash Script to Fetch Weather Information

Code:

get_weather.sh

#!/bin/bash

This script fetches the weather information for Tokyo

curl wttr.in/tokyo

Explanation:

Summary of Actions

  1. Create install_numpy.sh to install NumPy.
  2. Create dot_product.py to compute and print the dot product of two vectors.
  3. Create get_weather.sh to fetch and display the weather for Tokyo.

Now, I will execute these actions by writing the scripts to the respective files.

Code to Create the Scripts

Code:

Create the install_numpy.sh script

echo '#!/bin/bash

This script installs NumPy using pip

pip install numpy' > install_numpy.sh
chmod +x install_numpy.sh

Create the dot_product.py script

echo 'import numpy as np

Define the vectors

a = np.array([8, 9])
b = np.array([5, 4])

Compute the dot product

dot_product = np.dot(a, b)

Print the result

print(f"The dot product of {a} and {b} is: {dot_product}")' > dot_product.py

Create the get_weather.sh script

echo '#!/bin/bash

This script fetches the weather information for Tokyo

curl wttr.in/tokyo' > get_weather.sh
chmod +x get_weather.sh

Explanation:
Now, I will execute the above code to create the scripts.

The following bash code will run on your computer:

install_numpy.sh

#!/bin/bash

This script installs NumPy using pip

pip install numpy
Running code? [Y/n]:Y
======stderr======
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv

[notice] A new release of pip is available: 23.0.1 -> 24.3.1
[notice] To update, run: pip install --upgrade pip

==================
The following python code will run on your computer:

dot_product.py

import numpy as np

Define the vectors

a = np.array([8, 9])
b = np.array([5, 4])

Compute the dot product

dot_product = np.dot(a, b)

Print the result

print(f"The dot product of {a} and {b} is: {dot_product}")
Running code? [Y/n]:Y
The following bash code will run on your computer:

get_weather.sh

#!/bin/bash

This script fetches the weather information for Tokyo

curl wttr.in/tokyo
Running code? [Y/n]:Y
======stderr======
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed

0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
100 9286 100 9286 0 0 10068 0 --:--:-- --:--:-- --:--:-- 10060
100 9286 100 9286 0 0 10067 0 --:--:-- --:--:-- --:--:-- 10060

==================
The following bash code will run on your computer:

Create the install_numpy.sh script

echo '#!/bin/bash

This script installs NumPy using pip

pip install numpy' > install_numpy.sh
chmod +x install_numpy.sh

Create the dot_product.py script

echo 'import numpy as np

Define the vectors

a = np.array([8, 9])
b = np.array([5, 4])

Compute the dot product

dot_product = np.dot(a, b)

Print the result

print(f"The dot product of {a} and {b} is: {dot_product}")' > dot_product.py

Create the get_weather.sh script

echo '#!/bin/bash

This script fetches the weather information for Tokyo

curl wttr.in/tokyo' > get_weather.sh
chmod +x get_weather.sh
Running code? [Y/n]:Y

  1. write a bash script to install numpy. 2. then write a python script to compute the dot product of [8, 9] and [5, 4], and print the result. 3. then write a script to search for the weather at tokyo with wttr.in/tokyo.

Embodied Actions:

Executed Results:
Executing code block 0: {
Requirement already satisfied: numpy in /usr/local/lib/python3.10/site-packages (1.26.4)
(stderr: WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv

[notice] A new release of pip is available: 23.0.1 -> 24.3.1
[notice] To update, run: pip install --upgrade pip
)}
Executing code block 1: {
The dot product of [8 9] and [5 4] is: 76
}
Executing code block 2: {

Weather report: tokyo

   _`/"".-.     Patchy rain nearby
    ,\_(   ).   +23(25) °C
     /(___(__)8 km/h
       ‘ ‘ ‘ ‘  10 km
      ‘ ‘ ‘ ‘   0.1 mm
                                                       ┌─────────────┐
┌──────────────────────────────┬───────────────────────┤  Fri 01 Nov ├───────────────────────┬──────────────────────────────┐
│            Morning           │             Noon      └──────┬──────┘     Evening           │             Night            │
├──────────────────────────────┼──────────────────────────────┼──────────────────────────────┼──────────────────────────────┤
│  _`/"".-.     Patchy rain ne…│  _`/"".-.     Patchy rain ne…│  _`/"".-.     Patchy rain ne…│  _`/"".-.     Patchy rain ne…│
│   ,\_(   ).   +23(25) °C     │   ,\_(   ).   +23(25) °C     │   ,\_(   ).   +23(25) °C     │   ,\_(   ).   +24(25) °C     │
│    /(___(__)11-15 km/h   │    /(___(__)7-10 km/h    │    /(___(__)8-10 km/h    │    /(___(__)9-12 km/h    │
│      ‘ ‘ ‘ ‘  10 km          │      ‘ ‘ ‘ ‘  10 km          │      ‘ ‘ ‘ ‘  10 km          │      ‘ ‘ ‘ ‘  10 km          │
│     ‘ ‘ ‘ ‘   0.1 mm | 100%  │     ‘ ‘ ‘ ‘   0.1 mm | 100%  │     ‘ ‘ ‘ ‘   0.1 mm | 100%  │     ‘ ‘ ‘ ‘   0.1 mm | 100%  │
└──────────────────────────────┴──────────────────────────────┴──────────────────────────────┴──────────────────────────────┘
                                                       ┌─────────────┐
┌──────────────────────────────┬───────────────────────┤  Sat 02 Nov ├───────────────────────┬──────────────────────────────┐
│            Morning           │             Noon      └──────┬──────┘     Evening           │             Night            │
├──────────────────────────────┼──────────────────────────────┼──────────────────────────────┼──────────────────────────────┤
│  _`/"".-.     Light rain sho…│      .-.      Moderate rain  │  _`/"".-.     Light rain sho…│  _`/"".-.     Light rain sho…│
│   ,\_(   ).   +22(25) °C     │     (   ).    21 °C          │   ,\_(   ).   +24(27) °C     │   ,\_(   ).   +25(27) °C     │
│    /(___(__)9-13 km/h    │    (___(__)4-5 km/h     │    /(___(__)21-34 km/h   │    /(___(__)36-63 km/h   │
│      ‘ ‘ ‘ ‘  10 km          │   ‚‘‚‘‚‘‚‘    7 km           │      ‘ ‘ ‘ ‘  10 km          │      ‘ ‘ ‘ ‘  10 km          │
│     ‘ ‘ ‘ ‘   0.2 mm | 100%  │   ‚’‚’‚’‚’    3.7 mm | 100%  │     ‘ ‘ ‘ ‘   1.2 mm | 100%  │     ‘ ‘ ‘ ‘   0.5 mm | 100%  │
└──────────────────────────────┴──────────────────────────────┴──────────────────────────────┴──────────────────────────────┘
                                                       ┌─────────────┐
┌──────────────────────────────┬───────────────────────┤  Sun 03 Nov ├───────────────────────┬──────────────────────────────┐
│            Morning           │             Noon      └──────┬──────┘     Evening           │             Night            │
├──────────────────────────────┼──────────────────────────────┼──────────────────────────────┼──────────────────────────────┤
│  _`/"".-.     Patchy rain ne…│  _`/"".-.     Patchy rain ne…│  _`/"".-.     Patchy rain ne…│  _`/"".-.     Patchy rain ne…│
│   ,\_(   ).   +23(25) °C     │   ,\_(   ).   22 °C          │   ,\_(   ).   21 °C          │   ,\_(   ).   22 °C          │
│    /(___(__)31-46 km/h   │    /(___(__)37-47 km/h   │    /(___(__)39-48 km/h   │    /(___(__)37-46 km/h   │
│      ‘ ‘ ‘ ‘  10 km          │      ‘ ‘ ‘ ‘  10 km          │      ‘ ‘ ‘ ‘  10 km          │      ‘ ‘ ‘ ‘  10 km          │
│     ‘ ‘ ‘ ‘   0.0 mm | 75%   │     ‘ ‘ ‘ ‘   0.0 mm | 87%   │     ‘ ‘ ‘ ‘   0.0 mm | 80%   │     ‘ ‘ ‘ ‘   0.0 mm | 72%   │
└──────────────────────────────┴──────────────────────────────┴──────────────────────────────┴──────────────────────────────┘
Location: 東京都, 日本 [34.2255804,139.294774527387]

Follow @igor_chubin for wttr.in updates
(stderr:   % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
100  9286  100  9286    0     0  10068      0 --:--:-- --:--:-- --:--:-- 10060
100  9286  100  9286    0     0  10067      0 --:--:-- --:--:-- --:--:-- 10060
)}

Executing code block 3: {
}

まとめ

マルチエージェントフレームワークとしてのCAMEL

多くのマルチエージェントのフレームワークが誕生し、その多くの開発が途中で止まっている中、CAMELは現在も継続的に開発が進められています。

現在の状況

  • 活発な開発が行われている
  • コミュニティによるサポートがある
  • オープンな研究環境が整備されている

フレームワークの特徴

  • AIの振る舞いの研究に特化
  • 大規模な実験を通じた検証
  • 誰もが研究に参加できる環境

この記事で紹介したように、CAMELは環境構築から実行まで比較的容易に始められます。
みなさまもぜひ実際に動かしてみて、マルチエージェントフレームワークを体験してみてください。

参考情報

MIXI DEVELOPERS
MIXI DEVELOPERS

Discussion