File size: 4,330 Bytes
2de8f47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import openai
import pandas as pd
import numpy as np
from typing import Dict, List, Optional
import json
import logging

logger = logging.getLogger(__name__)

class ForecastingAIAssistant:
    """AI assistant for forecasting tasks using GenAI."""
    
    def __init__(self, api_key: str, model_name: str = "gpt-3.5-turbo"):
        self.api_key = api_key
        self.model_name = model_name
        openai.api_key = api_key
    
    def generate_forecast_interpretation(self, data_summary: Dict, 
                                       forecast_results: Dict,
                                       metrics: Dict) -> str:
        """Generate comprehensive interpretation of forecasting results."""
        try:
            prompt = f"""
            As a senior data scientist with 35 years of experience, provide a comprehensive analysis of these forecasting results:
            
            Data Summary: {json.dumps(data_summary, indent=2)}
            Forecast Results: {json.dumps(forecast_results, indent=2)}
            Performance Metrics: {json.dumps(metrics, indent=2)}
            
            Please provide:
            1. Key insights about the forecast quality
            2. Potential business implications
            3. Limitations of the current approach
            4. Recommendations for improvement
            5. Any anomalies or patterns worth noting
            
            Write in a professional yet accessible tone suitable for both technical and business audiences.
            """
            
            response = openai.ChatCompletion.create(
                model=self.model_name,
                messages=[
                    {"role": "system", "content": "You are a senior data scientist with expertise in time series forecasting."},
                    {"role": "user", "content": prompt}
                ],
                temperature=0.3,
                max_tokens=1000
            )
            
            return response.choices[0].message.content
        except Exception as e:
            logger.error(f"Error generating interpretation: {str(e)}")
            return f"Interpretation generation failed: {str(e)}"
    
    def generate_business_recommendations(self, business_context: str,
                                        forecast_results: Dict,
                                        historical_data: pd.Series) -> str:
        """Generate business recommendations based on forecasts."""
        try:
            # Create historical data summary
            hist_summary = {
                "period": f"{historical_data.index.min()} to {historical_data.index.max()}" if hasattr(historical_data, 'index') else "N/A",
                "data_points": len(historical_data),
                "mean_value": historical_data.mean(),
                "trend": "upward" if historical_data.iloc[-1] > historical_data.iloc[0] else "downward" if len(historical_data) > 1 else "stable"
            }
            
            prompt = f"""
            Based on the forecasting results and business context, provide actionable recommendations:
            
            Business Context: {business_context}
            Forecast Results: {json.dumps(forecast_results, indent=2)}
            Historical Trends: {json.dumps(hist_summary, indent=2)}
            
            Provide specific, actionable recommendations including:
            1. Operational adjustments
            2. Risk mitigation strategies
            3. Opportunities to capitalize on
            4. Timeline considerations
            5. Key metrics to monitor
            
            Tailor recommendations to the specific business context.
            """
            
            response = openai.ChatCompletion.create(
                model=self.model_name,
                messages=[
                    {"role": "system", "content": "You are a business strategy consultant with expertise in data-driven decision making."},
                    {"role": "user", "content": prompt}
                ],
                temperature=0.3,
                max_tokens=1000
            )
            
            return response.choices[0].message.content
        except Exception as e:
            logger.error(f"Error generating recommendations: {str(e)}")
            return f"Recommendation generation failed: {str(e)}"