├── .gitignore ├── README.md ├── ai-crypto-analysis ├── README.md ├── ai_crypto_analysis.py └── requirements.txt ├── ai-stock-analysis ├── README.md ├── ai_stock_analysis.py └── requirements.txt └── mcp-agent ├── README.md ├── mcp_client.py ├── mcp_server.py └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # UV 98 | # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | #uv.lock 102 | 103 | # poetry 104 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 105 | # This is especially recommended for binary packages to ensure reproducibility, and is more 106 | # commonly ignored for libraries. 107 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 108 | #poetry.lock 109 | 110 | # pdm 111 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 112 | #pdm.lock 113 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 114 | # in version control. 115 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 116 | .pdm.toml 117 | .pdm-python 118 | .pdm-build/ 119 | 120 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 121 | __pypackages__/ 122 | 123 | # Celery stuff 124 | celerybeat-schedule 125 | celerybeat.pid 126 | 127 | # SageMath parsed files 128 | *.sage.py 129 | 130 | # Environments 131 | .env 132 | .venv 133 | env/ 134 | venv/ 135 | ENV/ 136 | env.bak/ 137 | venv.bak/ 138 | 139 | # Spyder project settings 140 | .spyderproject 141 | .spyproject 142 | 143 | # Rope project settings 144 | .ropeproject 145 | 146 | # mkdocs documentation 147 | /site 148 | 149 | # mypy 150 | .mypy_cache/ 151 | .dmypy.json 152 | dmypy.json 153 | 154 | # Pyre type checker 155 | .pyre/ 156 | 157 | # pytype static type analyzer 158 | .pytype/ 159 | 160 | # Cython debug symbols 161 | cython_debug/ 162 | 163 | # PyCharm 164 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 165 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 166 | # and can be added to the global gitignore or merged into this file. For a more nuclear 167 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 168 | #.idea/ 169 | 170 | # PyPI configuration file 171 | .pypirc 172 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OpenAI Projects 2 | This repository contains the code for the projects I built using OpenAI's LLM models for my [YouTube channel](https://www.youtube.com/@NarimanCodes). Make sure to check out the videos to see how I built them, and also subscribe to the channel for more content like this. 3 | 4 | # Projects 5 | - [AI Stock Analysis](/ai-stock-analysis/README.md) 6 | - [AI Crypto Analysis](/ai-crypto-analysis/README.md) 7 | - [MCP Agent](/mcp-agent/README.md) -------------------------------------------------------------------------------- /ai-crypto-analysis/README.md: -------------------------------------------------------------------------------- 1 | # AI Crypto Analysis 2 | An AI agent to analyze crypto market using ChatGPT, LlamaIndex, and Streamlit. 3 | 4 | You can watch the video on how it was built on my [YouTube](https://youtu.be/6G_6k_qYDLc). 5 | 6 | # Pre-requisites 7 | 8 | Install the dependencies using pip: 9 | 10 | ```bash 11 | pip install -r requirements.txt 12 | ``` 13 | 14 | Generate an OpenAI API key and set the OPENAI_API_KEY environment variable: 15 | 16 | ```bash 17 | export OPENAI_API_KEY=... 18 | ``` 19 | 20 | # Run 21 | Run the application: 22 | 23 | ```bash 24 | streamlit run ai_crypto_analysis.py 25 | ``` -------------------------------------------------------------------------------- /ai-crypto-analysis/ai_crypto_analysis.py: -------------------------------------------------------------------------------- 1 | import streamlit as st 2 | import numpy as np 3 | from typing import TypedDict, List 4 | 5 | from pycoingecko import CoinGeckoAPI 6 | from llama_index.agent.openai import OpenAIAgent 7 | from llama_index.llms.openai import OpenAI 8 | from llama_index.core.tools import FunctionTool 9 | 10 | class CoinInfo(TypedDict): 11 | description: str 12 | market_cap: int 13 | market_cap_rank: int 14 | twitter_followers: int 15 | recent_commits_count: int 16 | 17 | class TechnicalIndicators(TypedDict): 18 | ma_20: List[float] 19 | ma_50: List[float] 20 | ma_200: List[float] 21 | 22 | def fetch_coin_info(coin_id): 23 | cg = CoinGeckoAPI() 24 | coin_info = cg.get_coin_by_id(coin_id) 25 | 26 | return CoinInfo( 27 | description=coin_info['description']['en'], 28 | market_cap=coin_info['market_data']['market_cap']['usd'], 29 | market_cap_rank=coin_info['market_cap_rank'], 30 | twitter_followers=coin_info['community_data']['twitter_followers'], 31 | recent_commits_count=coin_info['developer_data']['commit_count_4_weeks'] 32 | ) 33 | 34 | 35 | def fetch_price_history(coin_id): 36 | cg = CoinGeckoAPI() 37 | return cg.get_coin_market_chart_by_id(coin_id, vs_currency='usd', days=365) 38 | 39 | def calculate_moving_averages(coin_id): 40 | cg = CoinGeckoAPI() 41 | price_history = cg.get_coin_market_chart_by_id(coin_id, vs_currency='usd', days=365) 42 | prices = [price[1] for price in price_history['prices']] 43 | 44 | return TechnicalIndicators( 45 | ma_20=np.convolve(prices, np.ones(20)/20, mode='valid'), 46 | ma_50=np.convolve(prices, np.ones(50)/50, mode='valid'), 47 | ma_200=np.convolve(prices, np.ones(200)/200, mode='valid'), 48 | ) 49 | 50 | llm = OpenAI(model="gpt-4o", temperature=0) 51 | 52 | coin_info_tool = FunctionTool.from_defaults(fn=fetch_coin_info) 53 | price_history_tool = FunctionTool.from_defaults(fn=fetch_price_history) 54 | moving_averages_tool = FunctionTool.from_defaults(fn=calculate_moving_averages) 55 | 56 | agent = OpenAIAgent.from_tools( 57 | [coin_info_tool, price_history_tool, moving_averages_tool], 58 | llm=llm, 59 | system_prompt=""" 60 | You are an advanced AI crypto analysis agent designed to analyze project fundamentals, historical price data, and key technical indicators to evaluate cryptocurrencies. Your goal is to assign a rating to each cryptocurrency based on a scale from Strong Buy (A) to Strong Sell (E) and provide a clear explanation for your rating. 61 | Consider the following factors: 62 | 63 | - Usability and real-world application 64 | - Adoption and recognition within the crypto community 65 | - Developer activity on the project 66 | - Historical price trends and technical indicators 67 | 68 | After the analysis, assign one of the following ratings and provide a detailed explanation for the rating: 69 | 70 | A - Strong Buy: The cryptocurrency has strong real-world applications, solid community support, strong market momentum, and bullish technical indicators. 71 | B - Buy: The project has good fundamentals, growing adoption, and positive technical signals, though it may have some risks or uncertainties. 72 | C - Hold: The cryptocurrency is fairly valued with mixed signals from fundamental and technical analysis. Holding is advised unless major developments arise. 73 | D - Sell: The project shows weak adoption, declining trends, or negative market sentiment, suggesting downside risk. 74 | E - Strong Sell: The cryptocurrency has serious usability issues, weak community support, significant downside risk, or bearish trends indicating potential losses. 75 | """, 76 | verbose=True 77 | ) 78 | 79 | coin = st.selectbox( 80 | "Select a cryptocurrency", 81 | ["bitcoin", "ethereum", "cardano", "solana", "dogecoin"] 82 | ) 83 | 84 | if coin: 85 | st.markdown( 86 | agent.chat(f'Should I invest in {coin}?') 87 | ) 88 | 89 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /ai-crypto-analysis/requirements.txt: -------------------------------------------------------------------------------- 1 | pycoingecko 2 | llama-index 3 | numpy 4 | streamlit -------------------------------------------------------------------------------- /ai-stock-analysis/README.md: -------------------------------------------------------------------------------- 1 | # AI Stock Analysis 2 | An AI agent to analyze stocks using ChatGPT, PydanticAI, and Streamlit. 3 | 4 | You can watch the video on how it was built on my [YouTube](https://youtu.be/aZtfTrlZ4sA). 5 | 6 | # Pre-requisites 7 | 8 | Install the dependencies using pip: 9 | 10 | ```bash 11 | pip install -r requirements.txt 12 | ``` 13 | 14 | Generate an OpenAI API key and set the OPENAI_API_KEY environment variable: 15 | 16 | ```bash 17 | export OPENAI_API_KEY=... 18 | ``` 19 | 20 | # Run 21 | Run the application: 22 | 23 | ```bash 24 | streamlit run ai_stock_analysis.py 25 | ``` -------------------------------------------------------------------------------- /ai-stock-analysis/ai_stock_analysis.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import streamlit as st 3 | from pydantic_ai import Agent, RunContext 4 | from pydantic_ai.settings import ModelSettings 5 | import yfinance as yf 6 | 7 | agent = Agent( 8 | 'openai:gpt-4o', 9 | deps_type=str, 10 | model_settings=ModelSettings(temperature=0), 11 | system_prompt=""" 12 | You are an advanced AI stock rating agent designed to analyze financial reports, 13 | historical price data, and key technical indicators to evaluate stocks. 14 | Your goal is to assign a rating to each stock based on a scale from Strong Buy (A) 15 | to Strong Sell (E) and provide a clear explanation for your rating. 16 | 17 | Consider the following factors: 18 | - Revenue growth 19 | - Profitability 20 | - Price history trends 21 | - Technical indicators 22 | 23 | After the analysis, assign one of the following ratings and provide a detailed explanation for the rating: 24 | A - Strong Buy: The stock is undervalued with strong growth potential, solid financials, and positive market momentum. 25 | B - Buy: The stock has good fundamentals and technical indicators but may have some risks or uncertainties. 26 | C - Hold: The stock is fairly valued with mixed signals from fundamental and technical analysis. Holding is advised unless major catalysts emerge. 27 | D - Sell: The stock shows weak fundamentals, declining trends, or negative market sentiment, suggesting downside risk. 28 | E - Strong Sell: The stock has serious financial or structural problems, significant downside risk, or bearish trends indicating potential losses. 29 | """ 30 | ) 31 | 32 | @agent.tool 33 | def fetch_stock_info(ctx: RunContext[str]): 34 | stock = yf.Ticker(ctx.deps) 35 | return {key: stock.info[key] for key in ['longName', 'marketCap', 'sector']} 36 | 37 | @agent.tool 38 | def fetch_quarterly_financials(ctx: RunContext[str]): 39 | stock = yf.Ticker(ctx.deps) 40 | return stock.quarterly_financials.T[['Total Revenue', 'Net Income']].to_csv() 41 | 42 | @agent.tool 43 | def fetch_annual_financials(ctx: RunContext[str]): 44 | stock = yf.Ticker(ctx.deps) 45 | return stock.financials.T[['Total Revenue', 'Net Income']].to_csv() 46 | 47 | @agent.tool 48 | def fetch_weekly_price_history(ctx: RunContext[str]): 49 | stock = yf.Ticker(ctx.deps) 50 | return stock.history(period='1y', interval='1wk').to_csv() 51 | 52 | @agent.tool 53 | def calculate_rsi_weekly(ctx: RunContext[str]): 54 | stock = yf.Ticker(ctx.deps) 55 | data = stock.history(period='1y', interval='1wk') 56 | delta = data['Close'].diff() 57 | 58 | gain = (delta.where(delta > 0, 0)).fillna(0) 59 | loss = (-delta.where(delta < 0, 0)).fillna(0) 60 | 61 | avg_gain = gain.rolling(window=14, min_periods=1).mean() 62 | avg_loss = loss.rolling(window=14, min_periods=1).mean() 63 | 64 | rs = avg_gain / avg_loss 65 | rsi = 100 - (100 / (1 + rs)) 66 | return rsi.iloc[-1] 67 | 68 | loop = asyncio.new_event_loop() 69 | asyncio.set_event_loop(loop) 70 | 71 | symbol = st.selectbox('Please select a stock symbol', ['AAPL', 'TSLA', 'OXY']) 72 | result = agent.run_sync("Analyze this stock", deps=symbol) 73 | st.markdown(result.data) 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /ai-stock-analysis/requirements.txt: -------------------------------------------------------------------------------- 1 | yfinance 2 | pydantic-ai 3 | asyncio 4 | streamlit -------------------------------------------------------------------------------- /mcp-agent/README.md: -------------------------------------------------------------------------------- 1 | # MCP Agent 2 | An MCP (Model Context Protocol) server and client using FastMCP and LangChain. 3 | 4 | You can watch the video on how it was built on my [YouTube](https://youtu.be/3K39NJbp2IA). 5 | 6 | # Pre-requisites 7 | 8 | Install the dependencies using pip: 9 | 10 | ```bash 11 | pip install -r requirements.txt 12 | ``` 13 | 14 | Generate an OpenAI API key and set the OPENAI_API_KEY environment variable: 15 | 16 | ```bash 17 | export OPENAI_API_KEY=... 18 | ``` 19 | 20 | # Run 21 | Run the application: 22 | 23 | ```bash 24 | python mcp_client.py 25 | ``` -------------------------------------------------------------------------------- /mcp-agent/mcp_client.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | 3 | from langchain_mcp_adapters.tools import load_mcp_tools 4 | from langchain_openai import ChatOpenAI 5 | from langgraph.prebuilt import create_react_agent 6 | from mcp import ClientSession, StdioServerParameters 7 | from mcp.client.stdio import stdio_client 8 | 9 | model = ChatOpenAI(model="gpt-4o") 10 | server_params = StdioServerParameters( 11 | command="python", 12 | args=["mcp_server.py"], 13 | ) 14 | 15 | async def main(): 16 | async with stdio_client(server_params) as (read, write): 17 | async with ClientSession(read, write) as session: 18 | await session.initialize() 19 | tools = await load_mcp_tools(session) 20 | 21 | agent = create_react_agent(model, tools) 22 | agent_response = await agent.ainvoke({"messages":"Analyze how revenue of MSFT is changing over time."}) 23 | print(agent_response) 24 | 25 | if __name__ == "__main__": 26 | asyncio.run(main()) -------------------------------------------------------------------------------- /mcp-agent/mcp_server.py: -------------------------------------------------------------------------------- 1 | import yfinance as yf 2 | from fastmcp import FastMCP 3 | from pandas import DataFrame 4 | 5 | mcp = FastMCP("stocks") 6 | 7 | @mcp.tool() 8 | def fetch_stock_info(symbol: str) -> dict: 9 | """Get Company's general information.""" 10 | stock = yf.Ticker(symbol) 11 | return stock.info 12 | 13 | @mcp.tool() 14 | def fetch_quarterly_financials(symbol: str) -> DataFrame : 15 | """Get stock quarterly financials.""" 16 | stock = yf.Ticker(symbol) 17 | return stock.quarterly_financials.T 18 | 19 | @mcp.tool() 20 | def fetch_annual_financials(symbol: str) -> DataFrame: 21 | """Get stock annual financials.""" 22 | stock = yf.Ticker(symbol) 23 | return stock.financials.T 24 | 25 | if __name__ == "__main__": 26 | mcp.run(transport="stdio") -------------------------------------------------------------------------------- /mcp-agent/requirements.txt: -------------------------------------------------------------------------------- 1 | yfinance 2 | asyncio 3 | langchain-mcp-adapters 4 | langchain-openai 5 | langgraph 6 | fastmcp 7 | --------------------------------------------------------------------------------