From 7c3fbb7f3e972ef418ae22ea71b0ebbfa65a3f6a Mon Sep 17 00:00:00 2001 From: Virat Singh Date: Fri, 29 Nov 2024 13:24:55 -0500 Subject: [PATCH 1/3] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index f98dfe1e..6b738ef6 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,8 @@ An AI-powered hedge fund that uses multiple agents to make trading decisions. Th 2. Quantitative Agent - Analyzes technical indicators and generates trading signals 3. Risk Management Agent - Evaluates portfolio risk and sets position limits 4. Portfolio Management Agent - Makes final trading decisions and generates orders + +Screenshot 2024-11-29 at 1 24 40 PM ## Features From d3654ae649f36332b3f113662925cffb67c1248a Mon Sep 17 00:00:00 2001 From: juancaoviedo Date: Sat, 30 Nov 2024 11:32:54 -0500 Subject: [PATCH 2/3] refactor code add few files --- CODE_OF_CONDUCT.md | 132 +++++++++++++++ CONTRIBUTING.md | 61 +++++++ LICENSE.md | 8 + README.md | 10 +- TERMS_AND_CONDITIONS.md | 112 +++++++++++++ poetry.toml | 2 + pyproject.toml | 7 +- src/__init__.py | 0 src/{ => ai_hedge_fund/agents}/agents.py | 152 ++++++++++-------- .../backtesting}/backtester.py | 44 ++--- src/ai_hedge_fund/run_backtest.py | 22 +++ src/ai_hedge_fund/run_hedge_fund.py | 64 ++++++++ src/{ => ai_hedge_fund/tools}/tools.py | 37 +++-- 13 files changed, 534 insertions(+), 117 deletions(-) create mode 100644 CODE_OF_CONDUCT.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE.md create mode 100644 TERMS_AND_CONDITIONS.md create mode 100644 poetry.toml delete mode 100644 src/__init__.py rename src/{ => ai_hedge_fund/agents}/agents.py (78%) rename src/{ => ai_hedge_fund/backtesting}/backtester.py (79%) create mode 100644 src/ai_hedge_fund/run_backtest.py create mode 100644 src/ai_hedge_fund/run_hedge_fund.py rename src/{ => ai_hedge_fund/tools}/tools.py (74%) diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..5d082fb1 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,132 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances of + any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, + without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official email address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +[INSERT CONTACT METHOD]. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of +actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +https://www.contributor-covenant.org/version/2/1/code_of_conduct.html. + +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..14d8711c --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,61 @@ +# Contributing to AI-Hedge-Fund + +A big welcome and thank you for considering contributing to AI-Hedge-Fund! Thanks to people like you open-source projects are changing the world! + +Reading and following these guidelines will help the commmunity make the contribution process easy and effective for everyone. It also communicates that you agree to respect the time of the developers managing and developing AI-Hedge-Fund. In return, we will reciprocate that respect by addressing your issue, assessing changes, and helping you finalize your pull requests. + +## Quicklinks + +* [Code of Conduct](#code-of-conduct) +* [Getting Started](#getting-started) + * [Issues](#issues) + * [Pull Requests](#pull-requests) +* [Getting Help](#getting-help) + +## Code of Conduct + +We take our open source community seriously and hold ourselves and other contributors to high standards of communication. By participating and contributing to this project, you agree to uphold our [Code of Conduct](CODE_OF_CONDUCT.md). + +## Getting Started + +Contributions are made to this repo via Issues and Pull Requests (PRs). A few general guidelines that cover both: + +- Search for existing Issues and PRs before creating your own. +- We work hard to makes sure issues are handled in a timely manner but, depending on the impact, it could take a while to investigate the root cause. A friendly ping in the comment thread to the submitter or a contributor can help draw attention if your issue is blocking. +- To report security vulnerabilities, please create an issue and add in the label "Security vulnerability". + +### Issues + +Issues should be used to report problems with AI-Hedge-Fund, request a new feature, or to discuss potential changes before a PR is created. When you create a new Issue, a template will be loaded that will guide you through collecting and providing the information we need to investigate. + +If you find an Issue that addresses the problem you're having, please add your own reproduction information to the existing issue rather than creating a new one. Adding a [reaction](https://github.blog/2016-03-10-add-reactions-to-pull-requests-issues-and-comments/) can also help be indicating to our maintainers that a particular problem is affecting more than just the reporter. + +### Pull Requests + +PRs to AI-Hedge-Fund are always welcome and can be a quick way to get your fix or improvement slated for the next release. In general, PRs should: + +- Only fix/add the functionality in question **OR** address wide-spread whitespace/style issues, not both. +- Add or modify the unit or integration tests for each fixed or changed functionality. +- Address a single concern in the least number of changed lines as possible. +- Include documentation in the repository. +- Be accompanied by a complete Pull Request template (loaded automatically when a PR is created). +- Update the README.md with details of changes to the interface, this includes new environment variables, exposed ports, useful file locations and container parameters. +- Increase the version numbers in any examples files and the README.md to the new version that this Pull Request would represent. The versioning scheme we use is [SemVer](http://semver.org/). +- You may merge the Pull Request in once you have the sign-off of two other developers, or if you + do not have permission to do that, you may request the second reviewer to merge it for you. + +For changes that address core functionality or would require breaking changes (e.g. a major release), it's best to open an Issue to discuss your proposal first. This is not required but can save time creating and reviewing changes. + +In general, we follow the ["fork-and-pull" Git workflow](https://github.com/susam/gitpr) + +1. Fork the repository to your own Github account +2. Clone the project to your machine +3. Create a branch locally with a succinct but descriptive name +4. Commit changes to the branch +5. Follow any formatting and testing guidelines specific to this repo +6. Push changes to your fork +7. Open a PR in our repository and follow the PR template so that we can efficiently review the changes. + +## Getting Help + +For the moment, the only way to reach to the developers is by creating issues. In the future, new channels will be open to reach the developers. \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 00000000..97f48681 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,8 @@ +The MIT License (MIT) +Copyright © 2024 + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index 6b738ef6..d7291153 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,9 @@ # AI Hedge Fund +[![Code of Conduct](https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg)](code_of_conduct.md) +[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE.md) +[![Contributing](https://img.shields.io/badge/Contributing-Guidelines-green.svg)](CONTRIBUTING.md) + An AI-powered hedge fund that uses multiple agents to make trading decisions. The system employs several specialized agents working together: 1. Market Data Agent - Gathers and preprocesses market data @@ -55,8 +59,9 @@ export FINANCIAL_DATASETS_API_KEY='your-api-key-here' ### Running the Hedge Fund ```bash -poetry run python src/agents.py --ticker AAPL --start-date 2024-01-01 --end-date 2024-03-01 +poetry run hedge-fund --ticker AAPL --start-date 2024-01-01 --end-date 2024-03-01 ``` +Or, in vscode go to the debug tab and launch the Hedge fund debug config to run in debug mode. You can modify the args in the launch.json file on the .vscode folder. **Example Output:** ```json @@ -69,8 +74,9 @@ poetry run python src/agents.py --ticker AAPL --start-date 2024-01-01 --end-date ### Running the Backtester ```bash -poetry run python src/backtester.py --ticker AAPL --start-date 2024-01-01 --end-date 2024-03-01 +poetry run backtester --ticker AAPL --start-date 2024-01-01 --end-date 2024-03-01 ``` +Or in vscode go to the debug tab and launch the Bakctester debug config to run in debug mode. You can modify the args in the launch.json file on the .vscode folder. **Example Output:** ``` diff --git a/TERMS_AND_CONDITIONS.md b/TERMS_AND_CONDITIONS.md new file mode 100644 index 00000000..d43dcdc2 --- /dev/null +++ b/TERMS_AND_CONDITIONS.md @@ -0,0 +1,112 @@ +# Terms and Conditions + +Last updated: November 30, 2024 + +Please read these terms and conditions carefully before using Our Service. + +## Interpretation and Definitions + +### Interpretation + +The words of which the initial letter is capitalized have meanings defined under the following conditions. The following definitions shall have the same meaning regardless of whether they appear in singular or in plural. + +### Definitions + +For the purposes of these Terms and Conditions: + +- __Application__ means the AI-Hedge-Fund software downloaded by You on any electronic device. +- __Affiliate__ means an entity that controls, is controlled by or is under common control with a party, where "control" means ownership of 50% or more of the shares, equity interest or other securities entitled to vote for election of directors or other managing authority. +- __Country__ refers to: United States of America. +- __Company__ (referred to as either "the Company", "We", "Us" or "Our" in this Agreement) refers to the group of developers and contributors of the Application and Service. +- __Device__ means any device that can access the Service such as a computer, a cellphone or a digital tablet, AI-agents and others. +- __Service__ refers to the Application and the services related to it. +- __Terms and Conditions__ (also referred as "Terms") mean these Terms and Conditions that form the entire agreement between You and the Company regarding the use of the Service. +- __Third-party Social Media Service__ means any services or content (including data, information, products or services) provided by a third-party that may be displayed, included or made available by the Service. +- __You__ means the individual accessing or using the Service, or the company, or other legal entity on behalf of which such individual is accessing or using the Service, as applicable. + +## Acknowledgment + +These are the Terms and Conditions governing the use of this Service and the agreement that operates between You and the Company. These Terms and Conditions set out the rights and obligations of all users regarding the use of the Service. + +Your access to and use of the Service is conditioned on Your acceptance of and compliance with these Terms and Conditions. These Terms and Conditions apply to all visitors, users and others who access or use the Service. + +By accessing or using the Service You agree to be bound by these Terms and Conditions. If You disagree with any part of these Terms and Conditions then You may not access the Service. + +You represent that you are over the age of 18. The Company does not recommend those under 18 to use the Service. + + +## Intellectual Property + +Refer to the [License](LICENSE.md). + +## Links to Other Websites + +Our Service may contain links to third-party web sites or services that are not owned or controlled by the Company. + +The Company has no control over, and assumes no responsibility for, the content, privacy policies, or practices of any third party web sites or services. You further acknowledge and agree that the Company shall not be responsible or liable, directly or indirectly, for any damage or loss caused or alleged to be caused by or in connection with the use of or reliance on any such content, goods or services available on or through any such web sites or services. + +We strongly advise You to read the terms and conditions and privacy policies of any third-party web sites or services that You visit. + +## Termination + +We may terminate or suspend Your access immediately, without prior notice or liability, for any reason whatsoever, including without limitation if You breach these Terms and Conditions. + +Upon termination, Your right to use the Service will cease immediately. + + +## Limitation of Liability + +To the maximum extent permitted by applicable law, in no event shall the Company or its suppliers be liable for any special, incidental, indirect, or consequential damages whatsoever (including, but not limited to, damages for monetary losses or for loss of profits, loss of data or other information, for business interruption, for personal injury, loss of privacy arising out of or in any way related to the use of or inability to use the Service, third-party software and/or third-party hardware used with the Service, or otherwise in connection with any provision of this Terms), even if the Company or any supplier has been advised of the possibility of such damages and even if the remedy fails of its essential purpose. + +Some states do not allow the exclusion of implied warranties or limitation of liability for incidental or consequential damages, which means that some of the above limitations may not apply. In these states, each party's liability will be limited to the greatest extent permitted by law. + +## "AS IS" and "AS AVAILABLE" Disclaimer + +The Service is provided to You "AS IS" and "AS AVAILABLE" and with all faults and defects without warranty of any kind. To the maximum extent permitted under applicable law, the Company, on its own behalf and on behalf of its Affiliates and its and their respective licensors and service providers, expressly disclaims all warranties, whether express, implied, statutory or otherwise, with respect to the Service, including all implied warranties of merchantability, fitness for a particular purpose, title and non-infringement, and warranties that may arise out of course of dealing, course of performance, usage or trade practice. Without limitation to the foregoing, the Company provides no warranty or undertaking, and makes no representation of any kind that the Service will meet Your requirements, achieve any intended results, be compatible or work with any other software, applications, systems or services, operate without interruption, meet any performance or reliability standards or be error free or that any errors or defects can or will be corrected. + +Without limiting the foregoing, neither the Company nor any of the company's provider makes any representation or warranty of any kind, express or implied: (i) as to the operation or availability of the Service, or the information, content, and materials or products included thereon; (ii) that the Service will be uninterrupted or error-free; (iii) as to the accuracy, reliability, or currency of any information or content provided through the Service; or (iv) that the Service, its servers, the content, or e-mails sent from or on behalf of the Company are free of viruses, scripts, trojan horses, worms, malware, timebombs or other harmful components. + +Some jurisdictions do not allow the exclusion of certain types of warranties or limitations on applicable statutory rights of a consumer, so some or all of the above exclusions and limitations may not apply to You. But in such a case the exclusions and limitations set forth in this section shall be applied to the greatest extent enforceable under applicable law. + +## Governing Law + +The laws of the Country, excluding its conflicts of law rules, shall govern this Terms and Your use of the Service. Your use of the Application may also be subject to other local, state, national, or international laws. + +## Disputes Resolution + +If You have any concern or dispute about the Service, You agree to first try to resolve the dispute informally by contacting the Company. + + +## For European Union (EU) Users + +If You are a European Union consumer, you will benefit from any mandatory provisions of the law of the country in which You are resident. + + +## United States Legal Compliance + +You represent and warrant that (i) You are not located in a country that is subject to the United States government embargo, or that has been designated by the United States government as a "terrorist supporting" country, and (ii) You are not listed on any United States government list of prohibited or restricted parties. + +## Severability and Waiver + +### Severability + +If any provision of these Terms is held to be unenforceable or invalid, such provision will be changed and interpreted to accomplish the objectives of such provision to the greatest extent possible under applicable law and the remaining provisions will continue in full force and effect. + +### Waiver + +Except as provided herein, the failure to exercise a right or to require performance of an obligation under these Terms shall not affect a party's ability to exercise such right or require such performance at any time thereafter nor shall the waiver of a breach constitute a waiver of any subsequent breach. + +## Translation Interpretation + +These Terms and Conditions may have been translated if We have made them available to You on our Service. +You agree that the original English text shall prevail in the case of a dispute. + +## Changes to These Terms and Conditions + +We reserve the right, at Our sole discretion, to modify or replace these Terms at any time. If a revision is material We will make reasonable efforts to provide at least 30 days' notice prior to any new terms taking effect. What constitutes a material change will be determined at Our sole discretion. + +By continuing to access or use Our Service after those revisions become effective, You agree to be bound by the revised terms. If You do not agree to the new terms, in whole or in part, please stop using the Service. + +## Contact Us + +If you have any questions about these Terms and Conditions, You can contact us creating and issue on the public github repository. \ No newline at end of file diff --git a/poetry.toml b/poetry.toml new file mode 100644 index 00000000..efa46ec0 --- /dev/null +++ b/poetry.toml @@ -0,0 +1,2 @@ +[virtualenvs] +in-project = true \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml index 6e1e9f1d..025b9b1e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,8 +5,9 @@ description = "An AI-powered hedge fund that uses multiple agents to make tradin authors = ["Your Name "] readme = "README.md" packages = [ - { include = "src", from = "." } + { include = "ai_hedge_fund", from = "src" } ] + [tool.poetry.dependencies] python = "^3.9" langchain = "0.1.0" @@ -23,6 +24,10 @@ black = "^23.7.0" isort = "^5.12.0" flake8 = "^6.1.0" +[tool.poetry.scripts] +hedge-fund = "ai_hedge_fund.run_hedge_fund:main" +backtester = "ai_hedge_fund.run_backtest:main" + [build-system] requires = ["poetry-core"] build-backend = "poetry.core.masonry.api" \ No newline at end of file diff --git a/src/__init__.py b/src/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/src/agents.py b/src/ai_hedge_fund/agents/agents.py similarity index 78% rename from src/agents.py rename to src/ai_hedge_fund/agents/agents.py index 696149a8..a0f989dd 100644 --- a/src/agents.py +++ b/src/ai_hedge_fund/agents/agents.py @@ -1,23 +1,31 @@ +import argparse +import operator +from datetime import datetime from typing import Annotated, Any, Dict, Sequence, TypedDict -import operator from langchain_core.messages import BaseMessage, HumanMessage from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder from langchain_openai.chat_models import ChatOpenAI from langgraph.graph import END, StateGraph -from src.tools import calculate_bollinger_bands, calculate_macd, calculate_obv, calculate_rsi, get_prices, prices_to_df - -import argparse -from datetime import datetime +from ai_hedge_fund.tools.tools import ( + calculate_bollinger_bands, + calculate_macd, + calculate_obv, + calculate_rsi, + get_prices, + prices_to_df, +) llm = ChatOpenAI(model="gpt-4o") + # Define agent state class AgentState(TypedDict): messages: Annotated[Sequence[BaseMessage], operator.add] data: Dict[str, Any] + ##### 1. Market Data Agent ##### def market_data_agent(state: AgentState): """Responsible for gathering and preprocessing market data""" @@ -25,14 +33,10 @@ def market_data_agent(state: AgentState): data = state["data"] # Get the historical price data - prices = get_prices( - data["ticker"], data["start_date"], data["end_date"] - ) + prices = get_prices(data["ticker"], data["start_date"], data["end_date"]) + + return {"messages": messages, "data": {**data, "prices": prices}} - return { - "messages": messages, - "data": {**data, "prices": prices} - } ##### 2. Quantitative Agent ##### def quant_agent(state: AgentState): @@ -40,72 +44,78 @@ def quant_agent(state: AgentState): data = state["data"] prices = data["prices"] prices_df = prices_to_df(prices) - + # Calculate indicators # 1. MACD (Moving Average Convergence Divergence) macd_line, signal_line = calculate_macd(prices_df) - + # 2. RSI (Relative Strength Index) rsi = calculate_rsi(prices_df) - + # 3. Bollinger Bands (Bollinger Bands) upper_band, lower_band = calculate_bollinger_bands(prices_df) - + # 4. OBV (On-Balance Volume) obv = calculate_obv(prices_df) - + # Generate individual signals signals = [] - + # MACD signal - if macd_line.iloc[-2] < signal_line.iloc[-2] and macd_line.iloc[-1] > signal_line.iloc[-1]: - signals.append('bullish') - elif macd_line.iloc[-2] > signal_line.iloc[-2] and macd_line.iloc[-1] < signal_line.iloc[-1]: - signals.append('bearish') + if ( + macd_line.iloc[-2] < signal_line.iloc[-2] + and macd_line.iloc[-1] > signal_line.iloc[-1] + ): + signals.append("bullish") + elif ( + macd_line.iloc[-2] > signal_line.iloc[-2] + and macd_line.iloc[-1] < signal_line.iloc[-1] + ): + signals.append("bearish") else: - signals.append('neutral') - + signals.append("neutral") + # RSI signal if rsi.iloc[-1] < 30: - signals.append('bullish') + signals.append("bullish") elif rsi.iloc[-1] > 70: - signals.append('bearish') + signals.append("bearish") else: - signals.append('neutral') - + signals.append("neutral") + # Bollinger Bands signal - current_price = prices_df['close'].iloc[-1] + current_price = prices_df["close"].iloc[-1] if current_price < lower_band.iloc[-1]: - signals.append('bullish') + signals.append("bullish") elif current_price > upper_band.iloc[-1]: - signals.append('bearish') + signals.append("bearish") else: - signals.append('neutral') - + signals.append("neutral") + # OBV signal obv_slope = obv.diff().iloc[-5:].mean() if obv_slope > 0: - signals.append('bullish') + signals.append("bullish") elif obv_slope < 0: - signals.append('bearish') + signals.append("bearish") else: - signals.append('neutral') - + signals.append("neutral") + # Determine overall signal - bullish_signals = signals.count('bullish') - bearish_signals = signals.count('bearish') - + bullish_signals = signals.count("bullish") + bearish_signals = signals.count("bearish") + if bullish_signals > bearish_signals: - overall_signal = 'bullish' + overall_signal = "bullish" elif bearish_signals > bullish_signals: - overall_signal = 'bearish' + overall_signal = "bearish" else: - overall_signal = 'neutral' - + overall_signal = "neutral" + # Calculate confidence level based on the proportion of indicators agreeing total_signals = len(signals) confidence = max(bullish_signals, bearish_signals) / total_signals - + # Create the quant agent's message message_content = f""" Trading Signal: {overall_signal} @@ -115,11 +125,9 @@ def quant_agent(state: AgentState): content=message_content.strip(), name="quant_agent", ) - - return { - "messages": state["messages"] + [message], - "data": data - } + + return {"messages": state["messages"] + [message], "data": data} + ##### 3. Risk Management Agent ##### def risk_management_agent(state: AgentState): @@ -136,7 +144,7 @@ def risk_management_agent(state: AgentState): evaluate portfolio exposure and recommend position sizing. Provide the following in your output (not as a JSON): - max_position_size: , - - risk_score: """ + - risk_score: """, ), MessagesPlaceholder(variable_name="messages"), ( @@ -151,7 +159,7 @@ def risk_management_agent(state: AgentState): Current Position: {portfolio['stock']} shares Only include the max position size and risk score in your output. - """ + """, ), ] ) @@ -182,7 +190,7 @@ def portfolio_management_agent(state: AgentState): Only buy if you have available cash. The quantity that you buy must be less than or equal to the max position size. Only sell if you have shares in the portfolio to sell. - The quantity that you sell must be less than or equal to the current position.""" + The quantity that you sell must be less than or equal to the current position.""", ), MessagesPlaceholder(variable_name="messages"), ( @@ -201,7 +209,7 @@ def portfolio_management_agent(state: AgentState): Remember, the action must be either buy, sell, or hold. You can only buy if you have available cash. You can only sell if you have shares in the portfolio to sell. - """ + """, ), ] ) @@ -210,6 +218,7 @@ def portfolio_management_agent(state: AgentState): result = chain.invoke(state).content return {"messages": [HumanMessage(content=result, name="portfolio_management")]} + ##### Run the Hedge Fund ##### def run_hedge_fund(ticker: str, start_date: str, end_date: str, portfolio: dict): final_state = app.invoke( @@ -221,16 +230,17 @@ def run_hedge_fund(ticker: str, start_date: str, end_date: str, portfolio: dict) "ticker": ticker, "start_date": start_date, "end_date": end_date, - "portfolio": portfolio + "portfolio": portfolio, }, ) ], - "data": {"ticker": ticker, "start_date": start_date, "end_date": end_date} + "data": {"ticker": ticker, "start_date": start_date, "end_date": end_date}, }, config={"configurable": {"thread_id": 42}}, ) return final_state["messages"][-1].content + # Define the new workflow workflow = StateGraph(AgentState) @@ -251,30 +261,34 @@ def run_hedge_fund(ticker: str, start_date: str, end_date: str, portfolio: dict) # Add this at the bottom of the file if __name__ == "__main__": - parser = argparse.ArgumentParser(description='Run the hedge fund trading system') - parser.add_argument('--ticker', type=str, required=True, help='Stock ticker symbol') - parser.add_argument('--start-date', type=str, required=True, help='Start date (YYYY-MM-DD)') - parser.add_argument('--end-date', type=str, required=True, help='End date (YYYY-MM-DD)') - + parser = argparse.ArgumentParser(description="Run the hedge fund trading system") + parser.add_argument("--ticker", type=str, required=True, help="Stock ticker symbol") + parser.add_argument( + "--start-date", type=str, required=True, help="Start date (YYYY-MM-DD)" + ) + parser.add_argument( + "--end-date", type=str, required=True, help="End date (YYYY-MM-DD)" + ) + args = parser.parse_args() - + # Validate dates try: - datetime.strptime(args.start_date, '%Y-%m-%d') - datetime.strptime(args.end_date, '%Y-%m-%d') + datetime.strptime(args.start_date, "%Y-%m-%d") + datetime.strptime(args.end_date, "%Y-%m-%d") except ValueError: raise ValueError("Dates must be in YYYY-MM-DD format") - + # Sample portfolio - you might want to make this configurable too portfolio = { "cash": 100000.0, # $100,000 initial cash - "stock": 0 # No initial stock position + "stock": 0, # No initial stock position } - + result = run_hedge_fund( ticker=args.ticker, start_date=args.start_date, end_date=args.end_date, - portfolio=portfolio + portfolio=portfolio, ) - print(result) \ No newline at end of file + print(result) diff --git a/src/backtester.py b/src/ai_hedge_fund/backtesting/backtester.py similarity index 79% rename from src/backtester.py rename to src/ai_hedge_fund/backtesting/backtester.py index ad2afc0e..fb3f3e55 100644 --- a/src/backtester.py +++ b/src/ai_hedge_fund/backtesting/backtester.py @@ -3,8 +3,8 @@ import matplotlib.pyplot as plt import pandas as pd -from src.tools import get_price_data -from src.agents import run_hedge_fund +from ai_hedge_fund.tools.tools import get_price_data + class Backtester: def __init__(self, agent, ticker, start_date, end_date, initial_capital): @@ -20,6 +20,7 @@ def parse_action(self, agent_output): try: # Expect JSON output from agent import json + decision = json.loads(agent_output) return decision["action"], decision["quantity"] except: @@ -54,7 +55,9 @@ def run_backtest(self): dates = pd.date_range(self.start_date, self.end_date, freq="B") print("\nStarting backtest...") - print(f"{'Date':<12} {'Ticker':<6} {'Action':<6} {'Quantity':>8} {'Price':>8} {'Cash':>12} {'Stock':>8} {'Total Value':>12}") + print( + f"{'Date':<12} {'Ticker':<6} {'Action':<6} {'Quantity':>8} {'Price':>8} {'Cash':>12} {'Stock':>8} {'Total Value':>12}" + ) print("-" * 70) for current_date in dates: @@ -65,18 +68,20 @@ def run_backtest(self): ticker=self.ticker, start_date=lookback_start, end_date=current_date_str, - portfolio=self.portfolio + portfolio=self.portfolio, ) action, quantity = self.parse_action(agent_output) df = get_price_data(self.ticker, lookback_start, current_date_str) - current_price = df.iloc[-1]['close'] + current_price = df.iloc[-1]["close"] # Execute the trade with validation executed_quantity = self.execute_trade(action, quantity, current_price) # Update total portfolio value - total_value = self.portfolio["cash"] + self.portfolio["stock"] * current_price + total_value = ( + self.portfolio["cash"] + self.portfolio["stock"] * current_price + ) self.portfolio["portfolio_value"] = total_value # Log the current state with executed quantity @@ -96,8 +101,8 @@ def analyze_performance(self): # Calculate total return total_return = ( - self.portfolio["portfolio_value"] - self.initial_capital - ) / self.initial_capital + self.portfolio["portfolio_value"] - self.initial_capital + ) / self.initial_capital print(f"Total Return: {total_return * 100:.2f}%") # Plot the portfolio value over time @@ -114,7 +119,7 @@ def analyze_performance(self): # Calculate Sharpe Ratio (assuming 252 trading days in a year) mean_daily_return = performance_df["Daily Return"].mean() std_daily_return = performance_df["Daily Return"].std() - sharpe_ratio = (mean_daily_return / std_daily_return) * (252 ** 0.5) + sharpe_ratio = (mean_daily_return / std_daily_return) * (252**0.5) print(f"Sharpe Ratio: {sharpe_ratio:.2f}") # Calculate Maximum Drawdown @@ -124,24 +129,3 @@ def analyze_performance(self): print(f"Maximum Drawdown: {max_drawdown * 100:.2f}%") return performance_df - -### 4. Run the Backtest ##### -if __name__ == "__main__": - # Define parameters - ticker = "AAPL" # Example ticker symbol - start_date = "2024-01-01" # Adjust as needed - end_date = "2024-03-31" # Adjust as needed - initial_capital = 100000 # $100,000 - - # Create an instance of Backtester - backtester = Backtester( - agent=run_hedge_fund, - ticker=ticker, - start_date=start_date, - end_date=end_date, - initial_capital=initial_capital, - ) - - # Run the backtesting process - backtester.run_backtest() - performance_df = backtester.analyze_performance() diff --git a/src/ai_hedge_fund/run_backtest.py b/src/ai_hedge_fund/run_backtest.py new file mode 100644 index 00000000..8c48c8f8 --- /dev/null +++ b/src/ai_hedge_fund/run_backtest.py @@ -0,0 +1,22 @@ +from ai_hedge_fund.agents.agents import run_hedge_fund +from ai_hedge_fund.backtesting.backtester import Backtester + +if __name__ == "__main__": + # Define parameters + ticker = "AAPL" # Example ticker symbol + start_date = "2024-01-01" # Adjust as needed + end_date = "2024-03-31" # Adjust as needed + initial_capital = 100000 # $100,000 + + # Create an instance of Backtester + backtester = Backtester( + agent=run_hedge_fund, + ticker=ticker, + start_date=start_date, + end_date=end_date, + initial_capital=initial_capital, + ) + + # Run the backtesting process + backtester.run_backtest() + performance_df = backtester.analyze_performance() diff --git a/src/ai_hedge_fund/run_hedge_fund.py b/src/ai_hedge_fund/run_hedge_fund.py new file mode 100644 index 00000000..60764a93 --- /dev/null +++ b/src/ai_hedge_fund/run_hedge_fund.py @@ -0,0 +1,64 @@ +import argparse +from datetime import datetime + +from langgraph.graph import END, StateGraph + +from ai_hedge_fund.agents.agents import ( + AgentState, + market_data_agent, + portfolio_management_agent, + quant_agent, + risk_management_agent, + run_hedge_fund, +) + +# Add this at the bottom of the file +if __name__ == "__main__": + # Define the new workflow + workflow = StateGraph(AgentState) + + # Add nodes + workflow.add_node("market_data_agent", market_data_agent) + workflow.add_node("quant_agent", quant_agent) + workflow.add_node("risk_management_agent", risk_management_agent) + workflow.add_node("portfolio_management_agent", portfolio_management_agent) + + # Define the workflow + workflow.set_entry_point("market_data_agent") + workflow.add_edge("market_data_agent", "quant_agent") + workflow.add_edge("quant_agent", "risk_management_agent") + workflow.add_edge("risk_management_agent", "portfolio_management_agent") + workflow.add_edge("portfolio_management_agent", END) + + # Check for the parser + parser = argparse.ArgumentParser(description="Run the hedge fund trading system") + parser.add_argument("--ticker", type=str, required=True, help="Stock ticker symbol") + parser.add_argument( + "--start-date", type=str, required=True, help="Start date (YYYY-MM-DD)" + ) + parser.add_argument( + "--end-date", type=str, required=True, help="End date (YYYY-MM-DD)" + ) + + args = parser.parse_args() + + # Validate dates + try: + datetime.strptime(args.start_date, "%Y-%m-%d") + datetime.strptime(args.end_date, "%Y-%m-%d") + except ValueError as e: + raise ValueError("Dates must be in YYYY-MM-DD format") from e + + # Sample portfolio - you might want to make this configurable too + portfolio = { + "cash": 100000.0, # $100,000 initial cash + "stock": 0, # No initial stock position + } + + result = run_hedge_fund( + ticker=args.ticker, + start_date=args.start_date, + end_date=args.end_date, + portfolio=portfolio, + ) + print(result) diff --git a/src/tools.py b/src/ai_hedge_fund/tools/tools.py similarity index 74% rename from src/tools.py rename to src/ai_hedge_fund/tools/tools.py index 0c540e71..8729788f 100644 --- a/src/tools.py +++ b/src/ai_hedge_fund/tools/tools.py @@ -2,7 +2,8 @@ import pandas as pd import requests - + + def get_prices(ticker, start_date, end_date): """Fetch price data from the API.""" headers = {"X-API-KEY": os.environ.get("FINANCIAL_DATASETS_API_KEY")} @@ -25,6 +26,7 @@ def get_prices(ticker, start_date, end_date): raise ValueError("No price data returned") return prices + def prices_to_df(prices): """Convert prices to a DataFrame.""" df = pd.DataFrame(prices) @@ -36,29 +38,33 @@ def prices_to_df(prices): df.sort_index(inplace=True) return df + # Update the get_price_data function to use the new functions def get_price_data(ticker, start_date, end_date): prices = get_prices(ticker, start_date, end_date) return prices_to_df(prices) + def calculate_confidence_level(signals): """Calculate confidence level based on the difference between SMAs.""" - sma_diff_prev = abs(signals['sma_5_prev'] - signals['sma_20_prev']) - sma_diff_curr = abs(signals['sma_5_curr'] - signals['sma_20_curr']) + sma_diff_prev = abs(signals["sma_5_prev"] - signals["sma_20_prev"]) + sma_diff_curr = abs(signals["sma_5_curr"] - signals["sma_20_curr"]) diff_change = sma_diff_curr - sma_diff_prev # Normalize confidence between 0 and 1 - confidence = min(max(diff_change / signals['current_price'], 0), 1) + confidence = min(max(diff_change / signals["current_price"], 0), 1) return confidence + def calculate_macd(prices_df): - ema_12 = prices_df['close'].ewm(span=12, adjust=False).mean() - ema_26 = prices_df['close'].ewm(span=26, adjust=False).mean() + ema_12 = prices_df["close"].ewm(span=12, adjust=False).mean() + ema_26 = prices_df["close"].ewm(span=26, adjust=False).mean() macd_line = ema_12 - ema_26 signal_line = macd_line.ewm(span=9, adjust=False).mean() return macd_line, signal_line + def calculate_rsi(prices_df, period=14): - delta = prices_df['close'].diff() + delta = prices_df["close"].diff() gain = (delta.where(delta > 0, 0)).fillna(0) loss = (-delta.where(delta < 0, 0)).fillna(0) avg_gain = gain.rolling(window=period).mean() @@ -67,9 +73,10 @@ def calculate_rsi(prices_df, period=14): rsi = 100 - (100 / (1 + rs)) return rsi + def calculate_bollinger_bands(prices_df, window=20): - sma = prices_df['close'].rolling(window).mean() - std_dev = prices_df['close'].rolling(window).std() + sma = prices_df["close"].rolling(window).mean() + std_dev = prices_df["close"].rolling(window).std() upper_band = sma + (std_dev * 2) lower_band = sma - (std_dev * 2) return upper_band, lower_band @@ -78,11 +85,11 @@ def calculate_bollinger_bands(prices_df, window=20): def calculate_obv(prices_df): obv = [0] for i in range(1, len(prices_df)): - if prices_df['close'].iloc[i] > prices_df['close'].iloc[i - 1]: - obv.append(obv[-1] + prices_df['volume'].iloc[i]) - elif prices_df['close'].iloc[i] < prices_df['close'].iloc[i - 1]: - obv.append(obv[-1] - prices_df['volume'].iloc[i]) + if prices_df["close"].iloc[i] > prices_df["close"].iloc[i - 1]: + obv.append(obv[-1] + prices_df["volume"].iloc[i]) + elif prices_df["close"].iloc[i] < prices_df["close"].iloc[i - 1]: + obv.append(obv[-1] - prices_df["volume"].iloc[i]) else: obv.append(obv[-1]) - prices_df['OBV'] = obv - return prices_df['OBV'] \ No newline at end of file + prices_df["OBV"] = obv + return prices_df["OBV"] From a33dc48608a4200283ef74fbdb8ea9d19af54300 Mon Sep 17 00:00:00 2001 From: juancaoviedo Date: Sat, 30 Nov 2024 11:34:00 -0500 Subject: [PATCH 3/3] allow vs code sync --- .gitignore | 1 - .vscode/extensions.json | 16 ++++++++++++++++ .vscode/launch.json | 32 ++++++++++++++++++++++++++++++++ .vscode/settings.json | 19 +++++++++++++++++++ 4 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 .vscode/extensions.json create mode 100644 .vscode/launch.json create mode 100644 .vscode/settings.json diff --git a/.gitignore b/.gitignore index 5e9dea55..a6b84940 100644 --- a/.gitignore +++ b/.gitignore @@ -30,7 +30,6 @@ ENV/ # IDE .idea/ -.vscode/ *.swp *.swo diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 00000000..7f718ee7 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,16 @@ +{ + // See https://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations. + // Extension identifier format: ${publisher}.${name}. Example: vscode.csharp + + // List of extensions which should be recommended for users of this workspace. + "recommendations": [ + "ms-python.python", + "charliermarsh.ruff", + "sonarsource.sonarlint-vscode", + "golang.go" + ], + // List of extensions recommended by VS Code that should not be recommended for users of this workspace. + "unwantedRecommendations": [ + + ] +} \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 00000000..ad095073 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,32 @@ +{ + "configurations": [ + { + "name": "Hedge Fund", + "type": "debugpy", + "request": "launch", + "python": "${workspaceFolder}/.venv/Scripts/python", + "module": "ai_hedge_fund.run_hedge_fund", + "cwd": "${workspaceFolder}", + "envFile": "${workspaceFolder}/.env.example", + "args": [ + "--ticker", "AAPL", + "--start-date", "2024-01-01", + "--end-date", "2024-03-01" + ] + }, + { + "name": "Backtester", + "type": "debugpy", + "request": "launch", + "python": "${workspaceFolder}/.venv/Scripts/python", + "module": "ai_hedge_fund.run_backtest", + "cwd": "${workspaceFolder}", + "envFile": "${workspaceFolder}/.env.example", + "args": [ + "--ticker", "AAPL", + "--start-date", "2024-01-01", + "--end-date", "2024-03-01" + ] + } + ] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..1f9dadd4 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,19 @@ +{ + "[python]": { + "editor.formatOnSave": true, + "editor.codeActionsOnSave": { + "source.fixAll": "explicit", + "source.organizeImports": "explicit" + }, + "editor.defaultFormatter": "charliermarsh.ruff" + }, + "flake8.enabled": false, + "remote.autoForwardPortsFallback": 0, + "[go]": { + "editor.insertSpaces": false, + "editor.formatOnSave": true, + "editor.codeActionsOnSave": { + "source.organizeImports": "explicit" + } + } + } \ No newline at end of file