File size: 18,637 Bytes
2dc7acf |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 |
{
"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
}
|