[GH-ISSUE #69] AI writer for finance Technical Analysis(TA) - Basic #391

Closed
opened 2026-03-13 20:14:21 +03:00 by kerem · 3 comments
Owner

Originally created by @AJaySi on GitHub (May 15, 2024).
Original GitHub issue: https://github.com/AJaySi/ALwrity/issues/69

Originally assigned to: @AJaySi on GitHub.

Conducting Stock Technical Analysis (TA) with Python and ChatGPT

Methodology for Stock TA Analysis with Python and ChatGPT:

Data Acquisition and Indicator Computation:

  1. Employ yfinance to extract historical stock price data for your chosen asset.
  2. Utilize pandas_ta to calculate a suite of technical indicators, providing a comprehensive analytical foundation.

ChatGPT Prompt Construction:

  1. Extract indicator values for the most recent trading day.
  2. Structure a precise ChatGPT prompt, embedding these indicators as input parameters.

ChatGPT-Driven Interpretation and Forecasting:

  1. Engage ChatGPT to analyze the provided indicators, identifying potential trading signals and patterns.
  2. Leverage ChatGPT's predictive capabilities to forecast future stock price trends based on the analyzed data.

Visualizing Insights for Enhanced Understanding:

  1. Generate additional charts to visualize historical indicator trends.
    • This visual representation aids in validating ChatGPT's interpretations and identifying potential divergences or confirmations.
Originally created by @AJaySi on GitHub (May 15, 2024). Original GitHub issue: https://github.com/AJaySi/ALwrity/issues/69 Originally assigned to: @AJaySi on GitHub. ## Conducting Stock Technical Analysis (TA) with Python and ChatGPT ### Methodology for Stock TA Analysis with Python and ChatGPT: #### Data Acquisition and Indicator Computation: 1. **Employ `yfinance` to extract historical stock price data** for your chosen asset. 2. **Utilize `pandas_ta` to calculate a suite of technical indicators**, providing a comprehensive analytical foundation. #### ChatGPT Prompt Construction: 1. **Extract indicator values** for the most recent trading day. 2. **Structure a precise ChatGPT prompt**, embedding these indicators as input parameters. #### ChatGPT-Driven Interpretation and Forecasting: 1. **Engage ChatGPT to analyze the provided indicators**, identifying potential trading signals and patterns. 2. **Leverage ChatGPT's predictive capabilities to forecast future stock price trends** based on the analyzed data. #### Visualizing Insights for Enhanced Understanding: 1. **Generate additional charts to visualize historical indicator trends**. - This visual representation aids in validating ChatGPT's interpretations and identifying potential divergences or confirmations.
kerem closed this issue 2026-03-13 20:14:26 +03:00
Author
Owner

@AJaySi commented on GitHub (May 15, 2024):

sys_prompt = f"""
You are a seasoned Technical Analysis (TA) expert, rivaling legends like Charles Dow, John Bollinger, and Alan Andrews. Your deep understanding of market dynamics, coupled with mastery of technical indicators, allows you to decipher complex patterns and offer precise predictions.

Your expertise extends to practical tools like the pandas_ta module, enabling you to extract valuable insights from raw data.

Objective:
Analyze the provided technical indicators for {symbol} on its last trading day and predict its price movement over the next few trading sessions.

Instructions:

  1. Identify Potential Trading Signals: Highlight specific indicators suggesting bullish, bearish, or neutral signals. Explain the rationale behind each signal, referencing historical patterns or comparable market scenarios.
  2. Detect Patterns and Divergences: Analyze the interplay between different indicators. Detect patterns like moving average crossovers, candlestick formations, or divergences between price action and indicators. Explain the significance of each pattern.
  3. Price Movement Prediction: Based on your analysis, provide a clear prediction for {symbol}'s price movement in the next few days. State the expected direction (up, down, sideways) and potential price targets if identifiable.
  4. Risk Assessment: Briefly discuss any potential risks or factors that could invalidate your predictions, promoting a balanced and informed perspective.

Technical Indicators for {symbol} on the Last Trading Day:
{last_day_summary}

Remember, your analysis should be detailed, insightful, and actionable for traders seeking to capitalize on market movements.
"""

print(sys_prompt)

<!-- gh-comment-id:2111521893 --> @AJaySi commented on GitHub (May 15, 2024): sys_prompt = f""" You are a seasoned Technical Analysis (TA) expert, rivaling legends like Charles Dow, John Bollinger, and Alan Andrews. Your deep understanding of market dynamics, coupled with mastery of technical indicators, allows you to decipher complex patterns and offer precise predictions. Your expertise extends to practical tools like the pandas_ta module, enabling you to extract valuable insights from raw data. **Objective:** Analyze the provided technical indicators for {symbol} on its last trading day and predict its price movement over the next few trading sessions. **Instructions:** 1. **Identify Potential Trading Signals:** Highlight specific indicators suggesting bullish, bearish, or neutral signals. Explain the rationale behind each signal, referencing historical patterns or comparable market scenarios. 2. **Detect Patterns and Divergences:** Analyze the interplay between different indicators. Detect patterns like moving average crossovers, candlestick formations, or divergences between price action and indicators. Explain the significance of each pattern. 3. **Price Movement Prediction:** Based on your analysis, provide a clear prediction for {symbol}'s price movement in the next few days. State the expected direction (up, down, sideways) and potential price targets if identifiable. 4. **Risk Assessment:** Briefly discuss any potential risks or factors that could invalidate your predictions, promoting a balanced and informed perspective. **Technical Indicators for {symbol} on the Last Trading Day:** {last_day_summary} Remember, your analysis should be detailed, insightful, and actionable for traders seeking to capitalize on market movements. """ print(sys_prompt)
Author
Owner

@AJaySi commented on GitHub (May 15, 2024):

An example run for Alibaba stocks, symbol BABA:

[2024-05-15 12:41:42,361-INFO-finance_data_researcher-96]- Stock data fetched for BABA from 2024-01-16 12:41:39.355513 to 2024-05-15 12:41:39.355513

[2024-05-15 12:41:42,404-INFO-finance_data_researcher-47]- Technical indicators calculated successfully.

[2024-05-15 12:41:42,404-INFO-finance_data_researcher-71]- Last day summary extracted.

Summary of Technical Indicators for the Last Day:

Adj Close                  79.510002

MACD_12_26_9                2.265277

MACD_histogram_12_26_9      0.453024

RSI_14                     56.460648

BBL_5_2.0                  76.105134

BBM_5_2.0                  80.414000

BBU_5_2.0                  84.722866

SMA_20                     76.333501

EMA_50                     75.265963

OBV_in_million            270.830800

STOCHk_14_3_3              76.023236

STOCHd_14_3_3              79.611220

ADX_14                     25.889151

WILLR_14                  -49.039732

CMF_20                      0.319653

PSARl_0.02_0.2             77.355657

PSARs_0.02_0.2                   NaN

Name: 2024-05-14 00:00:00, dtype: float64

INFO|ai_financial_writer.py:52:gen_finta_report| Generating Financial Technical report..

INFO|main_text_generation.py:102:get_api_key| Using API key for google

INFO|main_text_generation.py:38:llm_text_gen| Using Google Gemini Pro text generation model.

INFO|gemini_pro_text.py:30:gemini_text_response| Temp: 0.6, MaxTokens: 4096, TopP: 0.9, N: 1

**1. Potential Trading Signals:**

* **Bullish Signals:**

* MACD Histogram (0.453024) is positive and rising, indicating bullish momentum.

    * RSI (56.4

60648) is above 50, suggesting a bullish trend.

    * OBV (270.830800) is trending higher, confirming bullish volume.

* **Bearish Signals:**

    * Bollinger Bands (BBU at 84.7

22866) are wide, indicating high volatility and potential for a pullback.

    * PSAR (PSARl at 77.355657) is below the current price, indicating a potential downtrend.

    * Williams %R (-49.039732) is in the oversold zone, suggesting a potential correction.

* **Neutral Signals:**

    * Stochastic Oscillator (STOCHk and STOCHd above 70) is in the overbought zone, indicating a potential loss of momentum.

    * Average Directional Index (ADX

 at 25.889151) is above 25, suggesting a strong trend, but the direction is unclear.

**2. Patterns and Divergences:**

* **Moving Average Crossover:** The 50-day EMA (75.265963) is below the 20-day SMA (76.333501), indicating a potential bearish crossover.

* **Divergence:** The RSI is trending higher while the price action is consolidating, suggesting a potential bullish divergence.

**3. Price Movement Prediction:**

Based on the analysis above, I predict that BABA will experience a **sideways to slightly bearish** movement in the next few trading sessions.

* The bullish signals suggest that there is still some underlying strength in the trend.

* However, the bearish signals and patterns indicate that a pullback or correction is likely.

* The overbought Stochastic Oscillator and the potential bearish crossover in the moving averages support this view.

**Potential Price Targets:**

* **Upside:** If the bullish momentum continues, BABA could retest the Bollinger Band upper boundary (BBU at 84.722866).

* **Down

side:** If the bearish signals prevail, BABA could retrace to the Bollinger Band lower boundary (BBL at 76.105134) or even lower.

**4. Risk Assessment:**

* **Potential Invalidating Factors:**

    * A strong positive earnings report or other positive news could invalidate the bearish prediction and drive prices higher.

    * A sharp increase in volatility could lead to a breakout in either direction.

* **Recommendations:**

    * Traders should monitor the price action closely and adjust their positions accordingly.

    * Consider using stop-loss orders to manage risk.

    * Wait for confirmation of a trend reversal before entering new positions.
<!-- gh-comment-id:2111822966 --> @AJaySi commented on GitHub (May 15, 2024): ``` An example run for Alibaba stocks, symbol BABA: [2024-05-15 12:41:42,361-INFO-finance_data_researcher-96]- Stock data fetched for BABA from 2024-01-16 12:41:39.355513 to 2024-05-15 12:41:39.355513 [2024-05-15 12:41:42,404-INFO-finance_data_researcher-47]- Technical indicators calculated successfully. [2024-05-15 12:41:42,404-INFO-finance_data_researcher-71]- Last day summary extracted. Summary of Technical Indicators for the Last Day: Adj Close 79.510002 MACD_12_26_9 2.265277 MACD_histogram_12_26_9 0.453024 RSI_14 56.460648 BBL_5_2.0 76.105134 BBM_5_2.0 80.414000 BBU_5_2.0 84.722866 SMA_20 76.333501 EMA_50 75.265963 OBV_in_million 270.830800 STOCHk_14_3_3 76.023236 STOCHd_14_3_3 79.611220 ADX_14 25.889151 WILLR_14 -49.039732 CMF_20 0.319653 PSARl_0.02_0.2 77.355657 PSARs_0.02_0.2 NaN Name: 2024-05-14 00:00:00, dtype: float64 INFO|ai_financial_writer.py:52:gen_finta_report| Generating Financial Technical report.. INFO|main_text_generation.py:102:get_api_key| Using API key for google INFO|main_text_generation.py:38:llm_text_gen| Using Google Gemini Pro text generation model. INFO|gemini_pro_text.py:30:gemini_text_response| Temp: 0.6, MaxTokens: 4096, TopP: 0.9, N: 1 **1. Potential Trading Signals:** * **Bullish Signals:** * MACD Histogram (0.453024) is positive and rising, indicating bullish momentum. * RSI (56.4 60648) is above 50, suggesting a bullish trend. * OBV (270.830800) is trending higher, confirming bullish volume. * **Bearish Signals:** * Bollinger Bands (BBU at 84.7 22866) are wide, indicating high volatility and potential for a pullback. * PSAR (PSARl at 77.355657) is below the current price, indicating a potential downtrend. * Williams %R (-49.039732) is in the oversold zone, suggesting a potential correction. * **Neutral Signals:** * Stochastic Oscillator (STOCHk and STOCHd above 70) is in the overbought zone, indicating a potential loss of momentum. * Average Directional Index (ADX at 25.889151) is above 25, suggesting a strong trend, but the direction is unclear. **2. Patterns and Divergences:** * **Moving Average Crossover:** The 50-day EMA (75.265963) is below the 20-day SMA (76.333501), indicating a potential bearish crossover. * **Divergence:** The RSI is trending higher while the price action is consolidating, suggesting a potential bullish divergence. **3. Price Movement Prediction:** Based on the analysis above, I predict that BABA will experience a **sideways to slightly bearish** movement in the next few trading sessions. * The bullish signals suggest that there is still some underlying strength in the trend. * However, the bearish signals and patterns indicate that a pullback or correction is likely. * The overbought Stochastic Oscillator and the potential bearish crossover in the moving averages support this view. **Potential Price Targets:** * **Upside:** If the bullish momentum continues, BABA could retest the Bollinger Band upper boundary (BBU at 84.722866). * **Down side:** If the bearish signals prevail, BABA could retrace to the Bollinger Band lower boundary (BBL at 76.105134) or even lower. **4. Risk Assessment:** * **Potential Invalidating Factors:** * A strong positive earnings report or other positive news could invalidate the bearish prediction and drive prices higher. * A sharp increase in volatility could lead to a breakout in either direction. * **Recommendations:** * Traders should monitor the price action closely and adjust their positions accordingly. * Consider using stop-loss orders to manage risk. * Wait for confirmation of a trend reversal before entering new positions. ```
Author
Owner

@AJaySi commented on GitHub (May 15, 2024):

TBD - Advanced.
1). The idea now is to include Finance articles from google finance and tavily, metaphor.
2). RAG the info for agents to write articles on.

<!-- gh-comment-id:2112092907 --> @AJaySi commented on GitHub (May 15, 2024): TBD - Advanced. 1). The idea now is to include Finance articles from google finance and tavily, metaphor. 2). RAG the info for agents to write articles on.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
starred/ALwrity#391
No description provided.