-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoin_analyser.py
More file actions
261 lines (225 loc) · 14.3 KB
/
Copy pathcoin_analyser.py
File metadata and controls
261 lines (225 loc) · 14.3 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
"""The main script that demos most of the features of the all project."""
from technical_analyser import technical_analyser
from chain_analyser import chain_analyser
from fundamental_analyser import fundamental_analyser
from macroeconomic_analyser import macroeconomic_analyser
from langchain_openai import ChatOpenAI
from langchain_openai import AzureOpenAI
from langchain_groq import ChatGroq
from langchain_google_genai import ChatGoogleGenerativeAI
import os
import time
from cachetools import TTLCache
import logging
from datetime import datetime, timedelta
import pandas
logging.basicConfig(level=logging.INFO)
# Caching 100 items for 24 hours
cache = TTLCache(maxsize=100, ttl=86400)
logging.basicConfig(level=logging.INFO)
def _get_llm(model_name:str):
"Return one of the LangChain LLM's according to the model_name. OpenAI, AzureOpenAI, llama-3 and Gemini-pro is supported."
try:
if model_name == "openai":
OPENAI_KEY = os.getenv("OPENAI_KEY")
llm = ChatOpenAI(model="gpt-4o",temperature=0,max_tokens=None,timeout=None,max_retries=2,api_key=OPENAI_KEY)
elif model_name == "azure_openai":
AZURE_AD_TOKEN = os.getenv("AZURE_AD_TOKEN")
AZURE_AD_TOKEN_PROVIDER = os.getenv("AZURE_AD_TOKEN_PROVIDER")
AZURE_DEPLOYMENT = os.getenv("AZURE_DEPLOYMENT")
AZURE_ENDPOINT = os.getenv("AZURE_ENDPOINT")
llm = AzureOpenAI(azure_ad_token=AZURE_AD_TOKEN, azure_ad_token_provider=AZURE_AD_TOKEN_PROVIDER, azure_deployment=AZURE_DEPLOYMENT, azure_endpoint=AZURE_ENDPOINT, model="gpt-3.5-turbo-instruct", temperature=0,)
elif model_name == "llama3":
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
llm = ChatGroq(api_key=GROQ_API_KEY, model_name="llama3-70b-8192", temperature=0.0) #llama-3.1-70b-versatile
else:
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
llm = ChatGoogleGenerativeAI(google_api_key=GOOGLE_API_KEY, model="gemini-1.5-pro", temperature=0)
return llm
except Exception as e:
logging.error(f"Error getting LLM: {e}")
return None
def _get_answer_from_llm(llm: any, input:str) -> str:
"""The last llm call that gathers all analyzes and creates a one final analysis interpretion to send to the user."""
prompt = """
You are an experienced cryptocurrency trader and analyst who specializes in analysing blockchain projects.
You analyse projects by doing Technical(technical analysis), Chain (chain analysis), Fundamental(fundamental analysis) and Macroeconomic(global macroeconomic financial analysis).
You will be presented all these analysis.
Your goal is to aggregate and summarize all these findings to the user.
The background is a trader is asking you to anlyze a coin and by the data you will receive you will give your answer.
Your response should be professional, technical, and easy to understand.
ONLY ANSWER IN TURKISH.
<Example>:
<HUMAN>:
<Technical>
Technical Analysis UP Signals: 0
DOWN Signals: 3 (SAR, Stochastic Oscillator, SMA)
NEUTRAL Signals: 5 (CCI, ATR, Bollinger Bands, ADX, RSI, Previous Performance Potential)
Given the mix of signals:
The SAR, Stochastic Oscillator, and SMA indicate a down due to the downward trend, strong bearish trend, and price being below the Parabolic SAR, respectively.
However, there are no strong up signals to counterbalance the bearish indicators.
Prediction: Slight Decrease.
The market signals indicate a bearish trend, with three indicators pointing towards a downtrend.
Although there are neutral indicators, they are not strong enough to offset the bearish signals.
It is important to use a risk-managed approach, such as setting tight stop-loss orders to mitigate potential losses.
A small to moderate short position with a stop-loss above the current price and a reasonable take-profit target below the current price is suggested.
Continuously monitor the coin's price action and adjust positions as needed.
It is advisable to wait for clearer trend signals before making significant trades, always considering a risk-managed approach.
<Chain>
Current Price: $56,423
Market Cap: $1,114,378,772,366 (Ranked 1st)
24h Price Change: -$671.34 (-1.18%)
24h Market Cap Change: -$12,618,620,188.38 (-1.12%)
Circulating Supply: 19,719,662 BTC
All-Time High (ATH): $73,738 (23.38% below ATH)
All-Time Low (ATL): $67.81 (83,216.62% above ATL)
Trading Volume: $42,537,556,960
Exchange Inflow: 19,722,353.13 BTC
Exchange Outflow: 55,848.73 BTC
Price Change: 1.18% decrease (DOWN)
Market Cap Change: 1.12% decrease (DOWN)
Trading Volume: High (NEUTRAL)
Significant Change from ATH: 23.38% below ATH (NEUTRAL)
Significant Change from ATL: Significantly higher than ATL (NEUTRAL)
High Circulating Supply: Neutral impact (NEUTRAL)
Low Transaction Volume & Number of Transactions: Extremely low (DOWN)
Exchange Inflows & Outflows: High inflows, low outflows (DOWN)
Market Cap Rank: High market cap indicates stability (NEUTRAL)
Prediction: Slightly down
The prediction is bearish due to the negative price and market cap changes, low transaction volume, and bearish exchange flows.
A stop-loss is recommended at $53,000, with a target price of $52,000.
Monitor the market for changes in transaction volume and exchange flows, which could indicate a shift in market behavior.
<Fundamental>
Bitcoin is the first successful decentralized cryptocurrency enabling peer-to-peer transactions without intermediaries.
Key Indicators:
Block Time: 10 minutes, moderate speed (NEUTRAL).
Hashing Algorithm: SHA-256, secure (UP).
Web Presence: Strong with official site, whitepaper, and multiple tracking sites (UP).
Social Media & Community: Active on major platforms, large followings (UP).
Developer Activity: High GitHub activity, strong support (UP).
Sentiment: 64.59% positive, mixed community trust (NEUTRAL).
Additional Factors: 15 years old, established platform (UP).
Conclusion:
Bitcoin shows strong performance in security, web presence, social media, developer activity, and community support. However, moderate transaction speed and mixed sentiment result in an overall NEUTRAL recommendation.
<Macroeconomic>
Inflation: Mixed signals; normal in the US and EU, high in India, Russia, and Japan.
Interest Rates: High in key economies, indicating tightening policies.
GDP Growth: Positive overall, except for low/negative growth in the US and China.
Market Indices: Downward trends, indicating bearish sentiment.
Commodities: Precious metals uptrend, industrial commodities downtrend.
Currency Strength: Strength in JPY and CNY, others weak or neutral.
Elections: High volatility expected due to upcoming elections.
Overall Guidance:
The global economic outlook shows inflationary pressures, potential slowdowns, and high volatility due to elections and geopolitical tensions. A cautious investment approach is advised.
Recommendations:
Focus on safe-haven assets: Precious metals and strong currencies.
Monitor central bank policies: Interest rate and monetary policy changes.
Diversify investments: Across asset classes and regions.
Watch geopolitical developments: Impact on market sentiment and volatility.
Prepare for high volatility: Due to elections and geopolitical tensions.
<AI>:
Bitcoin (BTC) Kapsamlı Analizi
Teknik Analiz:
YÜKSELİŞ Sinyalleri: 0
DÜŞÜŞ Sinyalleri: 3 (SAR, Stokastik Osilatör, SMA)
NÖTR Sinyaller: 5 (CCI, ATR, Bollinger Bantları, ADX, RSI, Önceki Performans Potansiyeli)
Özet: SAR, Stokastik Osilatör ve SMA, ayı trendleri ve fiyatın anahtar seviyelerin altında olması nedeniyle bir düşüş trendi gösteriyor. Nötr göstergeler, düşüş sinyallerine yeterli denge sağlamıyor, bu da hafif bir düşüş öngörüsüne yol açıyor. Sıkı stop-loss emirleriyle risk yönetimi önerilir.
Tavsiye: Mevcut fiyatın üzerine stop-loss ayarlayarak ve mevcut fiyatın biraz altına take-profit hedefi belirleyerek küçük ila orta ölçekli bir short pozisyon düşünün. Coin'in fiyat hareketlerini izlemek ve pozisyonu buna göre ayarlamak önemlidir.
Zincir Analizi:
Mevcut Fiyat: $56,423
Piyasa Değeri: $1,114,378,772,366 (1. sırada)
24 Saatlik Fiyat Değişimi: -$671,34 (-%1,18)
24 Saatlik Piyasa Değeri Değişimi: -$12,618,620,188,38 (-%1,12)
Dolaşımdaki Arz: 19,719,662.0 BTC
Tüm Zamanların En Yüksek Değeri (ATH): $73,738 (ATH'nin %23,38 altında)
Tüm Zamanların En Düşük Değeri (ATL): $67,81 (ATL'nin %83,216.62 üzerinde)
İşlem Hacmi: $42,537,556,960
İşlem Sayısı: 0
İşlem Hacmi: 0
Borsaya Giriş: 19,722,353.13 BTC
Borsadan Çıkış: 55,848.73 BTC
Özet: Analiz, fiyat ve piyasa değeri düşüşleri, düşük ağ aktivitesi ve yüksek borsa girişleri nedeniyle potansiyel satış baskısını işaret eden kısa vadeli ayı momentumunu göstermektedir. Nötr sinyaller, ayı göstergelerini dengeleyemediği için hafif bir düşüş öngörülüyor.
Tavsiye: Potansiyel kayıpları sınırlamak için $53,000 seviyesinde stop-loss belirleyin, mevcut ayı momentumu temel alınarak $52,000 hedef fiyat belirleyin.
Dikkatli olun ve piyasa davranışlarındaki değişiklikler için ağ aktivitelerini ve borsa giriş-çıkışlarını izleyin.
Temel Analiz:
Bitcoin, güvenlik, web varlığı, sosyal medya etkinliği, geliştirici desteği ve topluluk katılımı açısından güçlü göstergelere sahiptir.
Bununla birlikte, nötr duygu oranı ve orta derecede işlem hızına bağlı olarak genel olarak nötr bir tavsiye verilmektedir.
Makroekonomik Analiz:
Küresel ekonomi, enflasyonist baskılar, potansiyel ekonomik yavaşlamalar ve seçimler ile jeopolitik gerilimler nedeniyle yüksek volatilite ile karşı karşıyadır.
Dikkatli bir yatırım yaklaşımı önerilmektedir.
Tavsiyeler:
Güvenli liman varlıklarına odaklanılabilir.
Merkez bankası politikalarını izlenilebilir: Faiz oranı kararları ve para politikası değişikliklerini takipte kalınabilir.
Yatırımları çeşitlendirilebilir: Yatırımları farklı varlık sınıflarına ve bölgelere yayarak çeşitlendirilebilir.
Yüksek volatiliteye hazırlıklı olun: Seçim yılı ve jeopolitik gerilimler ani piyasa hareketlerine neden olabilir.
Genel Sonuç:
Teknik, zincir, temel ve makroekonomik perspektiflerden yapılan birleşik analiz, Bitcoin (BTC) konusunda temkinli bir duruşu işaret etmektedir.
Teknik ve zincir analizlerinden gelen ayı sinyalleri, temkinli makroekonomik görünümle uyumludur.
Temel analiz, uzun vadede güçlü destek sağlamakla birlikte, kısa vadeli riskleri ortadan kaldırmamaktadır.
Ticaret stratejilerini buna göre ayarlayın, risk yönetimine odaklanın ve piyasa gelişmelerini takip ederek bilgi sahibi olun.
Now it's your turn:
"""
final_answer = llm.invoke(prompt + input)
final_answer = final_answer.content
return final_answer
def cached(func):
"""Caches input output pair."""
def wrapper(*args, **kwargs):
cache_key = (args, tuple(sorted(kwargs.items())))
if cache_key in cache:
return cache[cache_key]
result = func(*args, **kwargs)
cache[cache_key] = result
return result
return wrapper
@cached
def coin_analyser(coin_name:str, start_date:str, end_date:str, visualization:bool=True) -> dict[str,str]:
"""The main method of the main script that showcase projects features by calling all analysers and sending the all the outputs with a last llm call to get it summarized."""
logging.info("Technical analyser...")
technical_analysis, technical_analysis_figure = technical_analyser(coin_name=coin_name, visualization=visualization) # longer than 2 weeks is not that meaningful
logging.info(technical_analysis)
time.sleep(20) # To pass rate limits
logging.info("Chain analyser...")
chain_analysis, chain_analysis_figure = chain_analyser(coin_name=coin_name, visualization=visualization) # does not require time
logging.info(chain_analysis)
logging.info("Chain analyser...")
fundamental_analysis, fundamental_analysis_figure = fundamental_analyser(coin_name=coin_name, visualization=visualization) # does not require time
logging.info(fundamental_analysis)
time.sleep(20) # To pass rate limits
logging.info("Macroeconomic analyser...")
macroeconomic_analysis, macroeconomic_analysis_figure = macroeconomic_analyser(start_date=start_date,end_date=end_date, visualization=visualization) # looks at macroeconomical state of the world
logging.info(macroeconomic_analysis)
final_request = technical_analysis + chain_analysis + fundamental_analysis + macroeconomic_analysis
llm = _get_llm("google")
total_analysis = _get_answer_from_llm(llm=llm, input=final_request)
coin_analysis = {
'time': str(datetime.now()),
'coin_name': coin_name,
'start_date': start_date,
'end_date': end_date,
'total_analysis': total_analysis,
'technical_analysis': technical_analysis,
'chain_analysis': chain_analysis,
'fundamental_analysis': fundamental_analysis,
'macroeconomic_analysis':macroeconomic_analysis,
'technical_analysis_figure': technical_analysis_figure,
'chain_analysis_figure': chain_analysis_figure,
'fundamental_analysis_figure': fundamental_analysis_figure,
'macroeconomic_analysis_figure':macroeconomic_analysis_figure
}
coin_analysis_dataframe = pandas.DataFrame(coin_analysis, index=[0])
coin_analysis_dataframe.to_csv("coin_analysis.csv", mode='a', index=True)
return coin_analysis
if __name__ == '__main__':
# Get today's date
today = datetime.today()
# Set start_date to 2 days ago
start_date = (today - timedelta(days=2)).strftime('%Y-%m-%d')
# Set end_date to yesterday
end_date = (today - timedelta(days=1)).strftime('%Y-%m-%d')
#tickers = ["btc", "eth", "ham", "pepe24478", "floki", "fet"]
#coin_comparator(tickers=tickers, start_date=start_date, end_date=end_date)
coin_name="bitcoin"
coin_analysis = coin_analyser(coin_name=coin_name, start_date=start_date, end_date=end_date, visualization=False)
print("\nRESULT\n:")
print(coin_analysis["total_analysis"])