کد بنویس حمایت و مقاومت ها رو بصورت دقیق نشان دهد بخصوص حمایت و مقاومت های مهم را با رنگ…
- User
کد بنویس حمایت و مقاومت ها رو بصورت دقیق نشان دهد بخصوص حمایت و مقاومت های مهم را با رنگ دیگه
Assistant
برای نمایش دقیق سطوح حمایت و مقاومت، یک اندیکاتور پایتون با استفاده از کتابخانههای تحلیل تکنیکال مینویسم:
import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.signal import argrelextrema import yfinance as yf class SupportResistanceDetector: def __init__(self, data, window=20, min_touches=2, tolerance=0.02): """ data: DataFrame با ستونهای OHLC window: پنجره برای یافتن نقاط اکسترمم min_touches: حداقل تعداد برخورد برای تایید سطح tolerance: درصد تولرانس برای گروهبندی سطوح """ self.data = data self.window = window self.min_touches = min_touches self.tolerance = tolerance self.support_levels = [] self.resistance_levels = [] def find_pivot_points(self): """یافتن نقاط چرخش (پیوت)""" # نقاط کف محلی (حمایت بالقوه) self.data['pivot_low'] = self.data['Low'][ (self.data['Low'] == self.data['Low'].rolling(window=self.window, center=True).min()) ] # نقاط سقف محلی (مقاومت بالقوه) self.data['pivot_high'] = self.data['High'][ (self.data['High'] == self.data['High'].rolling(window=self.window, center=True).max()) ] def cluster_levels(self, levels): """گروهبندی سطوح نزدیک به هم""" if len(levels) == 0: return [] levels = sorted(levels) clusters = [] current_cluster = [levels[0]] for level in levels[1:]: if abs(level - current_cluster[-1]) / current_cluster[-1] <= self.tolerance: current_cluster.append(level) else: clusters.append(current_cluster) current_cluster = [level] clusters.append(current_cluster) # میانگین هر کلاستر و تعداد برخوردها final_levels = [] for cluster in clusters: if len(cluster) >= self.min_touches: avg_level = np.mean(cluster) strength = len(cluster) final_levels.append({'level': avg_level, 'strength': strength}) return final_levels def calculate_levels(self): """محاسبه سطوح حمایت و مقاومت""" self.find_pivot_points() # جمعآوری سطوح حمایت support_prices = self.data['pivot_low'].dropna().tolist() self.support_levels = self.cluster_levels(support_prices) # جمعآوری سطوح مقاومت resistance_prices = self.data['pivot_high'].dropna().tolist() self.resistance_levels = self.cluster_levels(resistance_prices) # مرتبسازی بر اساس قدرت self.support_levels = sorted(self.support_levels, key=lambda x: x['strength'], reverse=True) self.resistance_levels = sorted(self.resistance_levels, key=lambda x: x['strength'], reverse=True) def plot_levels(self, last_n_days=100): """رسم نمودار با سطوح حمایت و مقاومت""" fig, ax = plt.subplots(figsize=(15, 8)) # رسم نمودار قیمت recent_data = self.data.tail(last_n_days) ax.plot(recent_data.index, recent_data['Close'], 'k-', linewidth=1.5, label='قیمت') # رسم کندلها for idx, row in recent_data.iterrows(): color = 'green' if row['Close'] > row['Open'] else 'red' ax.plot([idx, idx], [row['Low'], row['High']], color=color, linewidth=0.5) ax.plot([idx, idx], [row['Open'], row['Close']], color=color, linewidth=3) # رسم سطوح حمایت for i, support in enumerate(self.support_levels[:5]): # 5 سطح مهم level = support['level'] strength = support['strength'] # رنگ بر اساس قدرت if i < 2: # دو سطح اول (مهمترین) color = 'darkgreen' linewidth = 3 alpha = 0.9 else: color = 'green' linewidth = 2 alpha = 0.6 ax.axhline(y=level, color=color, linestyle='--', linewidth=linewidth, alpha=alpha, label=f'حمایت {level:.2f} (قدرت: {strength})') # رسم سطوح مقاومت for i, resistance in enumerate(self.resistance_levels[:5]): # 5 سطح مهم level = resistance['level'] strength = resistance['strength'] # رنگ بر اساس قدرت if i < 2: # دو سطح اول (مهمترین) color = 'darkred' linewidth = 3 alpha = 0.9 else: color = 'red' linewidth = 2 alpha = 0.6 ax.axhline(y=level, color=color, linestyle='--', linewidth=linewidth, alpha=alpha, label=f'مقاومت {level:.2f} (قدرت: {strength})') # تنظیمات نمودار ax.set_title('سطوح حمایت و مقاومت', fontsize=16, fontweight='bold') ax.set_xlabel('تاریخ', fontsize=12) ax.set_ylabel('قیمت', fontsize=12) ax.legend(loc='best', fontsize=10) ax.grid(True, alpha=0.3) plt.tight_layout() plt.show() def get_current_levels(self, current_price): """دریافت نزدیکترین سطوح به قیمت فعلی""" nearest_support = None nearest_resistance = None # نزدیکترین حمایت for support in self.support_levels: if support['level'] < current_price: nearest_support = support break # نزدیکترین مقاومت for resistance in self.resistance_levels: if resistance['level'] > current_price: nearest_resistance = resistance break return nearest_support, nearest_resistance # مثال استفاده def main(): # دانلود دادهها ticker = "AAPL" # میتوانید نماد دلخواه را جایگزین کنید data = yf.download(ticker, start="2023-01-01", end="2024-12-31") # ایجاد شیء تحلیلگر sr_detector = SupportResistanceDetector(data, window=20, min_touches=3, tolerance=0.015) # محاسبه سطوح sr_detector.calculate_levels() # نمایش سطوح مهم print("=== سطوح حمایت مهم ===") for i, support in enumerate(sr_detector.support_levels[:5]): print(f"{i+1}. سطح: ${support['level']:.2f} - قدرت: {support['strength']}") print("\n=== سطوح مقاومت مهم ===") for i, resistance in enumerate(sr_detector.resistance_levels[:5]): print(f"{i+1}. سطح: ${resistance['level']:.2f} - قدرت: {resistance['strength']}") # قیمت فعلی current_price = data['Close'].iloc[-1] print(f"\nقیمت فعلی: ${current_price:.2f}") # نزدیکترین سطوح nearest_support, nearest_resistance = sr_detector.get_current_levels(current_price) if nearest_support: print(f"نزدیکترین حمایت: ${nearest_support['level']:.2f}") if nearest_resistance: print(f"نزدیکترین مقاومت: ${nearest_resistance['level']:.2f}") # رسم نمودار sr_detector.plot_levels(last_n_days=120) if __name__ == "__main__": main()ویژگیهای کلیدی این کد:
-
تشخیص خودکار سطوح: با استفاده از نقاط پیوت (کف و سقفهای محلی)
-
گروهبندی هوشمند: سطوح نزدیک به هم را گروهبندی میکند
-
رتبهبندی بر اساس قدرت: سطوحی که بیشتر لمس شدهاند، قویتر هستند
-
رنگبندی متفاوت:
- حمایتهای مهم: سبز تیره با خط ضخیمتر
- حمایتهای معمولی: سبز روشن
- مقاومتهای مهم: قرمز تیره با خط ضخیمتر
- مقاومتهای معمولی: قرمز روشن
-
قابلیت تنظیم پارامترها:
window: اندازه پنجره برای یافتن نقاط چرخشmin_touches: حداقل برخورد برای تایید سطحtolerance: میزان تولرانس برای گروهبندی
برای استفاده، ابتدا کتابخانههای مورد نیاز را نصب کنید:
pip install pandas numpy matplotlib scipy yfinance-
- User
روی چارت نشان دهد
Assistant
برای نمایش سطوح حمایت و مقاومت روی چارت تعاملی، از کتابخانه Plotly استفاده میکنم که امکانات بهتری برای نمایش چارتهای مالی دارد:
import pandas as pd import numpy as np import plotly.graph_objects as go from plotly.subplots import make_subplots import yfinance as yf from scipy.signal import argrelextrema class InteractiveSupportResistance: def __init__(self, symbol, period="6mo"): self.symbol = symbol self.data = yf.download(symbol, period=period) self.support_levels = [] self.resistance_levels = [] def calculate_pivot_points(self, window=10): """محاسبه نقاط پیوت""" # پیدا کردن نقاط کف (حمایت) self.data['pivot_low'] = self.data['Low'].iloc[ argrelextrema(self.data['Low'].values, np.less_equal, order=window)[0] ] # پیدا کردن نقاط سقف (مقاومت) self.data['pivot_high'] = self.data['High'].iloc[ argrelextrema(self.data['High'].values, np.greater_equal, order=window)[0] ] def find_support_resistance(self, min_touches=2, tolerance_pct=1.5): """یافتن سطوح حمایت و مقاومت""" self.calculate_pivot_points() # جمعآوری همه نقاط پیوت lows = self.data['pivot_low'].dropna() highs = self.data['pivot_high'].dropna() # تابع برای گروهبندی سطوح def cluster_levels(levels, tolerance): if len(levels) == 0: return [] levels_sorted = sorted(levels) clusters = [] current_cluster = [levels_sorted[0]] for level in levels_sorted[1:]: if abs(level - np.mean(current_cluster)) / np.mean(current_cluster) * 100 <= tolerance: current_cluster.append(level) else: if len(current_cluster) >= min_touches: clusters.append({ 'level': np.mean(current_cluster), 'count': len(current_cluster), 'strength': len(current_cluster) / len(levels) * 100 }) current_cluster = [level] if len(current_cluster) >= min_touches: clusters.append({ 'level': np.mean(current_cluster), 'count': len(current_cluster), 'strength': len(current_cluster) / len(levels) * 100 }) return clusters # محاسبه سطوح self.support_levels = cluster_levels(lows.tolist(), tolerance_pct) self.resistance_levels = cluster_levels(highs.tolist(), tolerance_pct) # مرتبسازی بر اساس قدرت self.support_levels.sort(key=lambda x: x['strength'], reverse=True) self.resistance_levels.sort(key=lambda x: x['strength'], reverse=True) def create_interactive_chart(self): """ایجاد چارت تعاملی با Plotly""" fig = make_subplots(rows=2, cols=1, shared_xaxes=True, vertical_spacing=0.03, row_heights=[0.7, 0.3], subplot_titles=(f'{self.symbol} - سطوح حمایت و مقاومت', 'حجم معاملات')) # اضافه کردن کندل استیک fig.add_trace(go.Candlestick( x=self.data.index, open=self.data['Open'], high=self.data['High'], low=self.data['Low'], close=self.data['Close'], name='قیمت', increasing_line_color='green', decreasing_line_color='red' ), row=1, col=1) # اضافه کردن میانگین متحرک self.data['MA20'] = self.data['Close'].rolling(window=20).mean() self.data['MA50'] = self.data['Close'].rolling(window=50).mean() fig.add_trace(go.Scatter( x=self.data.index, y=self.data['MA20'], name='MA20', line=dict(color='blue', width=1) ), row=1, col=1) fig.add_trace(go.Scatter( x=self.data.index, y=self.data['MA50'], name='MA50', line=dict(color='orange', width=1) ), row=1, col=1) # اضافه کردن سطوح حمایت for i, support in enumerate(self.support_levels[:5]): # 5 سطح مهم level = support['level'] strength = support['strength'] # تنظیم رنگ و ضخامت بر اساس قدرت if i < 2: # دو سطح اول (قویترین) color = 'darkgreen' width = 3 dash = 'solid' else: color = 'lightgreen' width = 2 dash = 'dash' fig.add_hline( y=level, line_color=color, line_width=width, line_dash=dash, annotation_text=f"حمایت: {level:.2f} (قدرت: {strength:.1f}%)", annotation_position="left", row=1, col=1 ) # اضافه کردن ناحیه حمایت fig.add_hrect( y0=level * 0.995, y1=level * 1.005, fillcolor=color, opacity=0.1, line_width=0, row=1, col=1 ) # اضافه کردن سطوح مقاومت for i, resistance in enumerate(self.resistance_levels[:5]): # 5 سطح مهم level = resistance['level'] strength = resistance['strength'] # تنظیم رنگ و ضخامت بر اساس قدرت if i < 2: # دو سطح اول (قویترین) color = 'darkred' width = 3 dash = 'solid' else: color = 'lightcoral' width = 2 dash = 'dash' fig.add_hline( y=level, line_color=color, line_width=width, line_dash=dash, annotation_text=f"مقاومت: {level:.2f} (قدرت: {strength:.1f}%)", annotation_position="right", row=1, col=1 ) # اضافه کردن ناحیه مقاومت fig.add_hrect( y0=level * 0.995, y1=level * 1.005, fillcolor=color, opacity=0.1, line_width=0, row=1, col=1 ) # اضافه کردن حجم معاملات colors = ['red' if close < open else 'green' for close, open in zip(self.data['Close'], self.data['Open'])] fig.add_trace(go.Bar( x=self.data.index, y=self.data['Volume'], name='حجم', marker_color=colors, showlegend=False ), row=2, col=1) # تنظیمات چارت fig.update_layout( title=f'تحلیل تکنیکال {self.symbol}', yaxis_title='قیمت', xaxis_rangeslider_visible=False, height=800, template='plotly_white', hovermode='x unified', legend=dict( yanchor="top", y=0.99, xanchor="left", x=0.01, bgcolor="rgba(255, 255, 255, 0.8)" ) ) # تنظیمات محور Y برای حجم fig.update_yaxes(title_text="حجم", row=2, col=1) # اضافه کردن ابزارهای تعاملی fig.update_xaxes( rangeselector=dict( buttons=list([ dict(count=1, label="1 ماه", step="month", stepmode="backward"), dict(count=3, label="3 ماه", step="month", stepmode="backward"), dict(count=6, label="6 ماه", step="month", stepmode="backward"), dict(count=1, label="YTD", step="year", stepmode="todate"), dict(count=1, label="1 سال", step="year", stepmode="backward"), dict(step="all", label="همه") ]) ), rangeslider=dict(visible=False), type="date" ) return fig def analyze_current_position(self): """تحلیل موقعیت فعلی قیمت""" current_price = self.data['Close'].iloc[-1] # پیدا کردن نزدیکترین سطوح nearest_support = None nearest_resistance = None for support in self.support_levels: if support['level'] < current_price: nearest_support = support break for resistance in self.resistance_levels: if resistance['level'] > current_price: nearest_resistance = resistance break analysis = { 'current_price': current_price, 'nearest_support': nearest_support, 'nearest_resistance': nearest_resistance, 'support_distance': (current_price - nearest_support['level']) / current_price * 100 if nearest_support else None, 'resistance_distance': (nearest_resistance['level'] - current_price) / current_price * 100 if nearest_resistance else None } return analysis # استفاده از کلاس def main(): # ایجاد نمونه از کلاس analyzer = InteractiveSupportResistance('AAPL', period='6mo') # محاسبه سطوح analyzer.find_support_resistance(min_touches=2, tolerance_pct=1.5) # تحلیل موقعیت فعلی analysis = analyzer.analyze_current_position() print(f"=== تحلیل {analyzer.symbol} ===") print(f"قیمت فعلی: ${analysis['current_price']:.2f}") if analysis['nearest_support']: print(f"\nنزدیکترین حمایت: ${analysis['nearest_support']['level']:.2f}") print(f"فاصله تا حمایت: {analysis['support_distance']:.2f}%") print(f"قدرت حمایت: {analysis['nearest_support']['strength']:.1f}%") if analysis['nearest_resistance']: print(f"\nنزدیکترین مقاومت: ${analysis['nearest_resistance']['level']:.2f}") print(f"فاصله تا مقاومت: {analysis['resistance_distance']:.2f}%") print(f"قدرت مقاومت: {analysis['nearest_resistance']['strength']:.1f}%") # ایجاد و نمایش چارت fig = analyzer.create_interactive_chart() fig.show() # ذخیره چارت به صورت HTML fig.write_html("support_resistance_chart.html") print("\nچارت در فایل 'support_resistance_chart.html' ذخیره شد.") if __name__ == "__main__": main()برای اجرای این کد، ابتدا کتابخانههای مورد نیاز را نصب کنید:
pip install plotly yfinance pandas numpy scipyویژگیهای این چارت تعاملی:
- کندل استیک: نمایش کامل OHLC
- میانگینهای متحرک: MA20 و MA50
- سطوح حمایت و مقاومت با رنگبندی:
- سطوح قوی: خط پررنگ و ضخیم
- سطوح ضعیفتر: خط کمرنگ و نازکتر
- نواحی حمایت/مقاومت: هایلایت ناحیه اطراف هر سطح
- حجم معاملات: در پایین چارت
- ابزارهای تعاملی:
- زوم و پن
- انتخاب بازه زمانی
- نمایش جزئیات با هاور
- ذخیره به صورت HTML: برای مشاهده در مرورگر
چارت ایجاد شده کاملاً تعاملی است و میتوانید با آن کار کنید.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.