{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "sys.path.append('../../../FinNLP')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from finnlp.large_language_models.openai.openai_chat_agent import Openai_Chat_Agent"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "API_TOKEN = your_openai_api_token   # https://platform.openai.com/account/api-keys"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "config = {\n",
    "    \"token\": API_TOKEN,\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "agent = Openai_Chat_Agent(config)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Of course! I'd be happy to help you build some factors in Python. Please let me know what specific factors you would like to build or if you have any specific requirements in mind.\n"
     ]
    }
   ],
   "source": [
    "Init_Prompt = \"Now, you are a senior professional stock factor researcher in top financial companies.You will help me to build some factors in Python today.\"\n",
    "answer = agent.get_single_response(Init_Prompt)\n",
    "print(answer)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Great! To begin, we'll start by loading the data from the CSV file into a pandas DataFrame. Assuming the file is named \"data.csv\" and is located in the current working directory, you can use the following code:\n",
      "\n",
      "```python\n",
      "import pandas as pd\n",
      "\n",
      "# Load data from CSV into a DataFrame\n",
      "data = pd.read_csv('data.csv')\n",
      "\n",
      "# Display a preview of the data\n",
      "print(data.head())\n",
      "```\n",
      "\n",
      "This code will read the CSV file and store it in the variable `data`. The `.head()` function displays the first few rows of the DataFrame. Make sure to replace \"data.csv\" with the actual file name if it differs.\n",
      "\n",
      "Now that we have the data loaded, let me know which factors you would like to build or analyze, and I'll guide you through the process.\n"
     ]
    }
   ],
   "source": [
    "Prompt_1 = \"Let's look at the data, it's stored in the CSV format and has the following columns: open, high, low, close, volume, and amount.\"\n",
    "answer = agent.get_single_response(Prompt_1)\n",
    "print(answer)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Great! To begin, we'll start by loading the data from the CSV file into a pandas DataFrame. Assuming the file is named \"data.csv\" and is located in the current working directory, you can use the following code:\n",
    "\n",
    "```python\n",
    "import pandas as pd\n",
    "\n",
    "# Load data from CSV into a DataFrame\n",
    "data = pd.read_csv('data.csv')\n",
    "\n",
    "# Display a preview of the data\n",
    "print(data.head())\n",
    "```\n",
    "\n",
    "This code will read the CSV file and store it in the variable `data`. The `.head()` function displays the first few rows of the DataFrame. Make sure to replace \"data.csv\" with the actual file name if it differs.\n",
    "\n",
    "Now that we have the data loaded, let me know which factors you would like to build or analyze, and I'll guide you through the process."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The Fundamental Momentum Factor (FMF) is a measure that quantifies the change in fundamental metrics over a specific period. To calculate the FMF, we need to select a fundamental metric (e.g., \"amount\") and a time period (e.g., 1 year). Here's how you can calculate the FMF in Python:\n",
      "\n",
      "```python\n",
      "import pandas as pd\n",
      "\n",
      "def calculate_fmf(data, metric, period):\n",
      "    # Convert the date column to datetime format\n",
      "    data['date'] = pd.to_datetime(data['date'])\n",
      "    \n",
      "    # Sort the data by date in ascending order\n",
      "    data = data.sort_values('date')\n",
      "    \n",
      "    # Calculate the FMF\n",
      "    data['fmf'] = data[metric].pct_change(periods=period)\n",
      "    \n",
      "    return data\n",
      "\n",
      "# Load data from CSV into a DataFrame\n",
      "data = pd.read_csv('data.csv')\n",
      "\n",
      "# Calculate FMF using the 'amount' metric over a 1-year period\n",
      "fmf_data = calculate_fmf(data, 'amount', 252)\n",
      "\n",
      "# Display a preview of the FMF data\n",
      "print(fmf_data.head())\n",
      "```\n",
      "\n",
      "In this example, the `calculate_fmf()` function takes three parameters: `data` (the DataFrame), `metric` (the fundamental metric to use), and `period` (the time period to calculate the FMF over, given in the number of trading days).\n",
      "\n",
      "The function first converts the 'date' column to datetime format and sorts the DataFrame by date. Then it calculates the FMF by taking the percentage change of the specified metric over the given period using the `.pct_change()` function.\n",
      "\n",
      "The FMF values are then added as a new column to the DataFrame and returned. Finally, the code displays a preview of the FMF data using the `.head()` function.\n",
      "\n",
      "Feel free to adjust the metric and period values according to your requirements. Let me know if you have any questions or if there's anything else I can assist you with!\n"
     ]
    }
   ],
   "source": [
    "Prompt_2 = \"OK. First, please show me a function to calculate the Fundamental Momentum Factor. Let's use FMF to indicate Fundamental Momentum Factor.\"\n",
    "answer = agent.get_single_response(Prompt_2)\n",
    "print(answer)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The Fundamental Momentum Factor (FMF) is a measure that quantifies the change in fundamental metrics over a specific period. To calculate the FMF, we need to select a fundamental metric (e.g., \"amount\") and a time period (e.g., 1 year). Here's how you can calculate the FMF in Python:\n",
    "\n",
    "```python\n",
    "import pandas as pd\n",
    "\n",
    "def calculate_fmf(data, metric, period):\n",
    "    # Convert the date column to datetime format\n",
    "    data['date'] = pd.to_datetime(data['date'])\n",
    "    \n",
    "    # Sort the data by date in ascending order\n",
    "    data = data.sort_values('date')\n",
    "    \n",
    "    # Calculate the FMF\n",
    "    data['fmf'] = data[metric].pct_change(periods=period)\n",
    "    \n",
    "    return data\n",
    "\n",
    "# Load data from CSV into a DataFrame\n",
    "data = pd.read_csv('data.csv')\n",
    "\n",
    "# Calculate FMF using the 'amount' metric over a 1-year period\n",
    "fmf_data = calculate_fmf(data, 'amount', 252)\n",
    "\n",
    "# Display a preview of the FMF data\n",
    "print(fmf_data.head())\n",
    "```\n",
    "\n",
    "In this example, the `calculate_fmf()` function takes three parameters: `data` (the DataFrame), `metric` (the fundamental metric to use), and `period` (the time period to calculate the FMF over, given in the number of trading days).\n",
    "\n",
    "The function first converts the 'date' column to datetime format and sorts the DataFrame by date. Then it calculates the FMF by taking the percentage change of the specified metric over the given period using the `.pct_change()` function.\n",
    "\n",
    "The FMF values are then added as a new column to the DataFrame and returned. Finally, the code displays a preview of the FMF data using the `.head()` function.\n",
    "\n",
    "Feel free to adjust the metric and period values according to your requirements. Let me know if you have any questions or if there's anything else I can assist you with!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The Price Momentum Factor (PMF) is a measure that quantifies the price momentum of a stock. It is typically calculated as the percentage change in the closing price over a specific period. Here's how you can calculate the PMF in Python:\n",
      "\n",
      "```python\n",
      "import pandas as pd\n",
      "\n",
      "def calculate_pmf(data, period):\n",
      "    # Convert the date column to datetime format\n",
      "    data['date'] = pd.to_datetime(data['date'])\n",
      "    \n",
      "    # Sort the data by date in ascending order\n",
      "    data = data.sort_values('date')\n",
      "    \n",
      "    # Calculate the PMF\n",
      "    data['pmf'] = data['close'].pct_change(periods=period)\n",
      "    \n",
      "    return data\n",
      "\n",
      "# Load data from CSV into a DataFrame\n",
      "data = pd.read_csv('data.csv')\n",
      "\n",
      "# Calculate PMF over a 1-year period\n",
      "pmf_data = calculate_pmf(data, 252)\n",
      "\n",
      "# Display a preview of the PMF data\n",
      "print(pmf_data.head())\n",
      "```\n",
      "\n",
      "In this example, the `calculate_pmf()` function takes two parameters: `data` (the DataFrame) and `period` (the time period to calculate the PMF over, given in the number of trading days).\n",
      "\n",
      "The function first converts the 'date' column to datetime format and sorts the DataFrame by date. Then it calculates the PMF by taking the percentage change of the 'close' column over the given period using the `.pct_change()` function.\n",
      "\n",
      "The PMF values are then added as a new column to the DataFrame and returned. Finally, the code displays a preview of the PMF data using the `.head()` function.\n",
      "\n",
      "Feel free to adjust the period value according to your requirements. Let me know if you have any further questions or if there's anything else I can assist you with!\n"
     ]
    }
   ],
   "source": [
    "Prompt_3 = \"Next, please show me a function to calculate the Price Momentum Factor. Let's use PMF to indicate Price Momentum Factor.\"\n",
    "answer = agent.get_single_response(Prompt_3)\n",
    "print(answer)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The Price Momentum Factor (PMF) is a measure that quantifies the price momentum of a stock. It is typically calculated as the percentage change in the closing price over a specific period. Here's how you can calculate the PMF in Python:\n",
    "\n",
    "```python\n",
    "import pandas as pd\n",
    "\n",
    "def calculate_pmf(data, period):\n",
    "    # Convert the date column to datetime format\n",
    "    data['date'] = pd.to_datetime(data['date'])\n",
    "    \n",
    "    # Sort the data by date in ascending order\n",
    "    data = data.sort_values('date')\n",
    "    \n",
    "    # Calculate the PMF\n",
    "    data['pmf'] = data['close'].pct_change(periods=period)\n",
    "    \n",
    "    return data\n",
    "\n",
    "# Load data from CSV into a DataFrame\n",
    "data = pd.read_csv('data.csv')\n",
    "\n",
    "# Calculate PMF over a 1-year period\n",
    "pmf_data = calculate_pmf(data, 252)\n",
    "\n",
    "# Display a preview of the PMF data\n",
    "print(pmf_data.head())\n",
    "```\n",
    "\n",
    "In this example, the `calculate_pmf()` function takes two parameters: `data` (the DataFrame) and `period` (the time period to calculate the PMF over, given in the number of trading days).\n",
    "\n",
    "The function first converts the 'date' column to datetime format and sorts the DataFrame by date. Then it calculates the PMF by taking the percentage change of the 'close' column over the given period using the `.pct_change()` function.\n",
    "\n",
    "The PMF values are then added as a new column to the DataFrame and returned. Finally, the code displays a preview of the PMF data using the `.head()` function.\n",
    "\n",
    "Feel free to adjust the period value according to your requirements. Let me know if you have any further questions or if there's anything else I can assist you with!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Certainly! Let's combine the Fundamental Momentum Factor (FMF) and Price Momentum Factor (PMF) functions to create a more complex stock factor. Here's an example of how we can do it step by step:\n",
      "\n",
      "1. Calculate FMF:\n",
      "   ```python\n",
      "   fmf_data = calculate_fmf(data, 'amount', 252)\n",
      "   ```\n",
      "\n",
      "2. Calculate PMF:\n",
      "   ```python\n",
      "   pmf_data = calculate_pmf(data, 252)\n",
      "   ```\n",
      "\n",
      "3. Merge FMF and PMF data on the 'date' column:\n",
      "   ```python\n",
      "   merged_data = pd.merge(fmf_data, pmf_data[['date', 'pmf']], on='date', how='inner')\n",
      "   ```\n",
      "\n",
      "4. Create a new factor by multiplying FMF and PMF:\n",
      "   ```python\n",
      "   merged_data['complex_factor'] = merged_data['fmf'] * merged_data['pmf']\n",
      "   ```\n",
      "\n",
      "5. Optionally, you may want to normalize the complex factor to a certain range or scale for easier interpretation. For instance, you can use the Min-Max scaling method:\n",
      "   ```python\n",
      "   merged_data['complex_factor_scaled'] = (merged_data['complex_factor'] - merged_data['complex_factor'].min()) / (merged_data['complex_factor'].max() - merged_data['complex_factor'].min())\n",
      "   ```\n",
      "\n",
      "This sequence of steps combines the FMF and PMF factors into a more complex factor by multiplying them together. You can adjust the period or choose different fundamental or price metrics as per your requirements. Additionally, you can further enhance the factor by incorporating additional factors or applying additional transformations.\n",
      "\n",
      "Remember, these steps are just an example to demonstrate the process. Depending on your specific needs, you can modify or expand upon this logic. If you require further assistance or have any additional questions, please let me know!\n"
     ]
    }
   ],
   "source": [
    "Prompt_3 = \"\"\"Great! Can you write a rather more complex stock factor based on the FMF function \\\n",
    "and PMF functions rather than the four fundamental operations of arithmetic? Remember, you are \\\n",
    "a senior professional stock factor researcher and you need to think step by step and show me the \\\n",
    "thinking process.\n",
    "\"\"\"\n",
    "answer = agent.get_single_response(Prompt_3)\n",
    "print(answer)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Certainly! Let's combine the Fundamental Momentum Factor (FMF) and Price Momentum Factor (PMF) functions to create a more complex stock factor. Here's an example of how we can do it step by step:\n",
    "\n",
    "1. Calculate FMF:\n",
    "   ```python\n",
    "   fmf_data = calculate_fmf(data, 'amount', 252)\n",
    "   ```\n",
    "\n",
    "2. Calculate PMF:\n",
    "   ```python\n",
    "   pmf_data = calculate_pmf(data, 252)\n",
    "   ```\n",
    "\n",
    "3. Merge FMF and PMF data on the 'date' column:\n",
    "   ```python\n",
    "   merged_data = pd.merge(fmf_data, pmf_data[['date', 'pmf']], on='date', how='inner')\n",
    "   ```\n",
    "\n",
    "4. Create a new factor by multiplying FMF and PMF:\n",
    "   ```python\n",
    "   merged_data['complex_factor'] = merged_data['fmf'] * merged_data['pmf']\n",
    "   ```\n",
    "\n",
    "5. Optionally, you may want to normalize the complex factor to a certain range or scale for easier interpretation. For instance, you can use the Min-Max scaling method:\n",
    "   ```python\n",
    "   merged_data['complex_factor_scaled'] = (merged_data['complex_factor'] - merged_data['complex_factor'].min()) / (merged_data['complex_factor'].max() - merged_data['complex_factor'].min())\n",
    "   ```\n",
    "\n",
    "This sequence of steps combines the FMF and PMF factors into a more complex factor by multiplying them together. You can adjust the period or choose different fundamental or price metrics as per your requirements. Additionally, you can further enhance the factor by incorporating additional factors or applying additional transformations.\n",
    "\n",
    "Remember, these steps are just an example to demonstrate the process. Depending on your specific needs, you can modify or expand upon this logic. If you require further assistance or have any additional questions, please let me know!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "langchain",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
