{ "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": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Sure, I'd be happy to help you build a factor library in Python for your financial company. Let's get started!\n", "\n", "A factor library is a useful tool for quantitative analysis and modeling, which helps in evaluating and creating investment strategies. It provides a set of reusable functions and classes that can be used to calculate various factors or indicators based on financial data.\n", "\n", "To build a factor library in Python, we'll start by creating a new Python module to house our library. Let's call it \"factor_library.py\". Open a text editor or an integrated development environment (IDE) and create a new file with that name.\n", "\n", "Here's a basic outline of the steps we'll take to build the factor library:\n", "\n", "1. Import necessary libraries:\n", " ```\n", " import numpy as np\n", " import pandas as pd\n", " ```\n", "\n", "2. Define functions for different factors:\n", " - For example, let's create a moving average factor function:\n", " ```\n", " def moving_average(df, window):\n", " return df['close'].rolling(window).mean()\n", " ```\n", "\n", " - You can define various other factors based on your requirements, such as relative strength index (RSI), exponential moving average (EMA), Bollinger Bands, etc.\n", "\n", "3. Create a class to encapsulate related factors:\n", " - The class can be used to package multiple related factors together and provide a consistent interface.\n", " - Here's an example:\n", " ```\n", " class TechnicalIndicators:\n", " def __init__(self, df):\n", " self.df = df\n", "\n", " def moving_average(self, window):\n", " return self.df['close'].rolling(window).mean()\n", "\n", " def rsi(self, window):\n", " # Implement RSI calculation logic here\n", " pass\n", "\n", " # Other factor functions can be added similarly\n", " ```\n", "\n", "4. Test the library:\n", " - After implementing each factor, write some test code to ensure that the functions are working as expected.\n", " - For example:\n", " ```\n", " df = pd.read_csv('financial_data.csv')\n", " ti = TechnicalIndicators(df)\n", " ma_50 = ti.moving_average(50)\n", " print(ma_50)\n", " ```\n", "\n", "5. Document the library:\n", " - To make it easier for others (including yourself) to understand and use the library, provide clear documentation for each function, class, and their parameters.\n", " - You can use docstrings and comments to explain the purpose, inputs, and outputs of each function.\n", "\n", "Once you've completed these steps, you'll have a basic factor library in Python that you can expand upon and customize according to your specific needs. Remember to adhere to programming best practices, such as modular design, code reusability, and readability.\n", "\n", "Keep in mind that the example provided here is just a starting point, and the actual implementation of the factors will depend on your requirements and the financial data you're working with.\n", "\n", "I hope this helps you get started with building your factor library in Python. Let me know if you have any further questions!\n" ] } ], "source": [ "Init_Prompt = \"You are now a senior software development engineer in top financial company. You will help me to build a factor library in Python today.\"\n", "answer = agent.get_single_response(Init_Prompt)\n", "print(answer)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Sure, I'd be happy to help you build a factor library in Python for your financial company. Let's get started!\n", "\n", "A factor library is a useful tool for quantitative analysis and modeling, which helps in evaluating and creating investment strategies. It provides a set of reusable functions and classes that can be used to calculate various factors or indicators based on financial data.\n", "\n", "To build a factor library in Python, we'll start by creating a new Python module to house our library. Let's call it \"factor_library.py\". Open a text editor or an integrated development environment (IDE) and create a new file with that name.\n", "\n", "Here's a basic outline of the steps we'll take to build the factor library:\n", "\n", "1. Import necessary libraries:\n", " ```\n", " import numpy as np\n", " import pandas as pd\n", " ```\n", "\n", "2. Define functions for different factors:\n", " - For example, let's create a moving average factor function:\n", " ```\n", " def moving_average(df, window):\n", " return df['close'].rolling(window).mean()\n", " ```\n", "\n", " - You can define various other factors based on your requirements, such as relative strength index (RSI), exponential moving average (EMA), Bollinger Bands, etc.\n", "\n", "3. Create a class to encapsulate related factors:\n", " - The class can be used to package multiple related factors together and provide a consistent interface.\n", " - Here's an example:\n", " ```\n", " class TechnicalIndicators:\n", " def __init__(self, df):\n", " self.df = df\n", "\n", " def moving_average(self, window):\n", " return self.df['close'].rolling(window).mean()\n", "\n", " def rsi(self, window):\n", " # Implement RSI calculation logic here\n", " pass\n", "\n", " # Other factor functions can be added similarly\n", " ```\n", "\n", "4. Test the library:\n", " - After implementing each factor, write some test code to ensure that the functions are working as expected.\n", " - For example:\n", " ```\n", " df = pd.read_csv('financial_data.csv')\n", " ti = TechnicalIndicators(df)\n", " ma_50 = ti.moving_average(50)\n", " print(ma_50)\n", " ```\n", "\n", "5. Document the library:\n", " - To make it easier for others (including yourself) to understand and use the library, provide clear documentation for each function, class, and their parameters.\n", " - You can use docstrings and comments to explain the purpose, inputs, and outputs of each function.\n", "\n", "Once you've completed these steps, you'll have a basic factor library in Python that you can expand upon and customize according to your specific needs. Remember to adhere to programming best practices, such as modular design, code reusability, and readability.\n", "\n", "Keep in mind that the example provided here is just a starting point, and the actual implementation of the factors will depend on your requirements and the financial data you're working with.\n", "\n", "I hope this helps you get started with building your factor library in Python. Let me know if you have any further questions!" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Certainly! When designing the base class for all factors, it's important to consider the common functionality and attributes that factors will share. Here's an example of how you can design the base class for factors in Python:\n", "\n", "```python\n", "import pandas as pd\n", "\n", "class Factor:\n", " def __init__(self, df):\n", " self.df = df\n", "\n", " def calculate(self):\n", " \"\"\"\n", " This method should be implemented in each derived factor class.\n", " It should contain the specific logic to calculate the factor value.\n", " \"\"\"\n", " raise NotImplementedError(\"Subclasses must implement calculate method.\")\n", "```\n", "\n", "In this base class, we define an `__init__` method that takes a data frame `df` as input. This allows us to initialize the base factor class with the necessary financial data. You can enhance this class by including other common attributes that all factors may need.\n", "\n", "We also define a `calculate` method, which is marked as `NotImplementedError`. This method needs to be overridden in each derived factor class with the specific logic to calculate the factor value.\n", "\n", "Now, any specific factor class you create should inherit from this base `Factor` class and implement its own `calculate` method:\n", "\n", "```python\n", "class MovingAverageFactor(Factor):\n", " def __init__(self, df, window):\n", " super().__init__(df)\n", " self.window = window\n", "\n", " def calculate(self):\n", " return self.df['close'].rolling(self.window).mean()\n", "```\n", "\n", "In this example, we create a `MovingAverageFactor` class that inherits from the base `Factor` class. It takes an additional `window` parameter specific to the moving average calculation. The `calculate` method in this class implements the logic to calculate the moving average factor value using the `rolling` method from pandas.\n", "\n", "By designing a base class for all factors, you establish a consistent structure that can be used to create and organize various factor classes. This approach allows for easy expansion and maintenance of your factor library.\n", "\n", "Remember, this is just a basic example, and you can add more functionality and attributes to the base class as per your requirements.\n" ] } ], "source": [ "Prompt_1 = \"First, please help me design the base class of all factors\"\n", "answer = agent.get_single_response(Prompt_1)\n", "print(answer)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Certainly! When designing the base class for all factors, it's important to consider the common functionality and attributes that factors will share. Here's an example of how you can design the base class for factors in Python:\n", "\n", "```python\n", "import pandas as pd\n", "\n", "class Factor:\n", " def __init__(self, df):\n", " self.df = df\n", "\n", " def calculate(self):\n", " \"\"\"\n", " This method should be implemented in each derived factor class.\n", " It should contain the specific logic to calculate the factor value.\n", " \"\"\"\n", " raise NotImplementedError(\"Subclasses must implement calculate method.\")\n", "```\n", "\n", "In this base class, we define an `__init__` method that takes a data frame `df` as input. This allows us to initialize the base factor class with the necessary financial data. You can enhance this class by including other common attributes that all factors may need.\n", "\n", "We also define a `calculate` method, which is marked as `NotImplementedError`. This method needs to be overridden in each derived factor class with the specific logic to calculate the factor value.\n", "\n", "Now, any specific factor class you create should inherit from this base `Factor` class and implement its own `calculate` method:\n", "\n", "```python\n", "class MovingAverageFactor(Factor):\n", " def __init__(self, df, window):\n", " super().__init__(df)\n", " self.window = window\n", "\n", " def calculate(self):\n", " return self.df['close'].rolling(self.window).mean()\n", "```\n", "\n", "In this example, we create a `MovingAverageFactor` class that inherits from the base `Factor` class. It takes an additional `window` parameter specific to the moving average calculation. The `calculate` method in this class implements the logic to calculate the moving average factor value using the `rolling` method from pandas.\n", "\n", "By designing a base class for all factors, you establish a consistent structure that can be used to create and organize various factor classes. This approach allows for easy expansion and maintenance of your factor library.\n", "\n", "Remember, this is just a basic example, and you can add more functionality and attributes to the base class as per your requirements." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Certainly! Here are five examples of fundamental factors that you can design based on the base `Factor` class:\n", "\n", "1. Price-to-Earnings Ratio (P/E Ratio):\n", "```python\n", "class PERatioFactor(Factor):\n", " def calculate(self):\n", " return self.df['close'] / self.df['earnings_per_share']\n", "```\n", "In this example, the `calculate` method divides the closing price of each data point by the corresponding earnings per share to calculate the P/E ratio factor.\n", "\n", "2. Price-to-Book Ratio (P/B Ratio):\n", "```python\n", "class PBRatioFactor(Factor):\n", " def calculate(self):\n", " return self.df['close'] / self.df['book_value_per_share']\n", "```\n", "The `calculate` method divides the closing price by the book value per share to calculate the P/B ratio factor.\n", "\n", "3. Dividend Yield:\n", "```python\n", "class DividendYieldFactor(Factor):\n", " def calculate(self):\n", " return self.df['dividends'] / self.df['close']\n", "```\n", "The `calculate` method divides the dividends by the closing price to calculate the dividend yield factor.\n", "\n", "4. Debt-to-Equity Ratio:\n", "```python\n", "class DebtToEquityRatioFactor(Factor):\n", " def calculate(self):\n", " return self.df['total_debt'] / self.df['total_equity']\n", "```\n", "The `calculate` method divides the total debt by the total equity to calculate the debt-to-equity ratio factor.\n", "\n", "5. Return on Equity (ROE):\n", "```python\n", "class ROEFactor(Factor):\n", " def calculate(self):\n", " return self.df['net_income'] / self.df['total_equity']\n", "```\n", "The `calculate` method divides the net income by the total equity to calculate the return on equity factor.\n", "\n", "These are just a few examples of fundamental factors that you can calculate based on the provided base `Factor` class. Remember to customize the calculations based on the specific financial data columns available in your data frame (`df`). You can expand upon these examples and create additional factor classes based on your requirements.\n" ] } ], "source": [ "Prompt_2 = \"Second, please help me design 5 fundamental factors based on the base class\"\n", "answer = agent.get_single_response(Prompt_2)\n", "print(answer)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Certainly! Here are five examples of fundamental factors that you can design based on the base `Factor` class:\n", "\n", "1. Price-to-Earnings Ratio (P/E Ratio):\n", "```python\n", "class PERatioFactor(Factor):\n", " def calculate(self):\n", " return self.df['close'] / self.df['earnings_per_share']\n", "```\n", "In this example, the `calculate` method divides the closing price of each data point by the corresponding earnings per share to calculate the P/E ratio factor.\n", "\n", "2. Price-to-Book Ratio (P/B Ratio):\n", "```python\n", "class PBRatioFactor(Factor):\n", " def calculate(self):\n", " return self.df['close'] / self.df['book_value_per_share']\n", "```\n", "The `calculate` method divides the closing price by the book value per share to calculate the P/B ratio factor.\n", "\n", "3. Dividend Yield:\n", "```python\n", "class DividendYieldFactor(Factor):\n", " def calculate(self):\n", " return self.df['dividends'] / self.df['close']\n", "```\n", "The `calculate` method divides the dividends by the closing price to calculate the dividend yield factor.\n", "\n", "4. Debt-to-Equity Ratio:\n", "```python\n", "class DebtToEquityRatioFactor(Factor):\n", " def calculate(self):\n", " return self.df['total_debt'] / self.df['total_equity']\n", "```\n", "The `calculate` method divides the total debt by the total equity to calculate the debt-to-equity ratio factor.\n", "\n", "5. Return on Equity (ROE):\n", "```python\n", "class ROEFactor(Factor):\n", " def calculate(self):\n", " return self.df['net_income'] / self.df['total_equity']\n", "```\n", "The `calculate` method divides the net income by the total equity to calculate the return on equity factor.\n", "\n", "These are just a few examples of fundamental factors that you can calculate based on the provided base `Factor` class. Remember to customize the calculations based on the specific financial data columns available in your data frame (`df`). You can expand upon these examples and create additional factor classes based on your requirements." ] }, { "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 }