-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmacroeconomic_analyser.py
More file actions
550 lines (478 loc) · 26.5 KB
/
Copy pathmacroeconomic_analyser.py
File metadata and controls
550 lines (478 loc) · 26.5 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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
import requests
import yfinance as yf
import pandas as pd
import os
import datetime
from langchain_google_genai import ChatGoogleGenerativeAI
from pytrends.request import TrendReq
from langchain_openai import ChatOpenAI
from langchain_openai import AzureOpenAI
from langchain_groq import ChatGroq
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from dotenv import load_dotenv
import time
import plotly.io as pio
import logging
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
logging.basicConfig(level=logging.INFO)
pytrends = TrendReq()
load_dotenv(".env")
NEWS_API_API_KEY = os.getenv("NEWS_API_API_KEY")
NEWS_DATA_IO_API_KEY = os.getenv("NEWS_DATA_IO_API_KEY")
countries = {
'US': '^GSPC', # S&P 500
'UK': '^FTSE', # FTSE 100
'EU': '^GDAXI', # DAX
'China': '000001.SS', # Shanghai Composite Index
'India': '^BSESN', # BSE Sensex
'Turkey': 'XU100.IS', # BIST100
'Japan': '^N225' # Nikkei 225
}
def _get_indicators(start_date:str, end_date:str) -> tuple:
inflation_rate = get_inflation_rate(start_date=start_date, end_date=end_date)
interest_rates = get_central_bank_interest_rates(start_date=start_date, end_date=end_date)
gdp_growth_rate = get_gdp_growth_rate_last_quarter(start_date=start_date, end_date=end_date)
trends_data = get_google_trends(['bitcoin', 'ethereum'])
commodities_prices = get_commodities_prices(start_date=start_date, end_date=end_date)
market_indices = get_market_indices(start_date=start_date, end_date=end_date)
currency_strength = get_currency_strength(start_date=start_date, end_date=end_date)
query_list = [
'economy AND cryptocurrencies',
'international conflicts AND war',
'cryptocurrency regulatory changes OR cryptocurrency news',
'major cryptocurrency holdings of the corporations OR investments in cryptocurrencies OR ETF approval OR ETF launch',
'blockchain protocol upgrades OR new blockchain applications OR technological advancements blockchain',
]
queries = []
for query in query_list:
articles = _fetch_news(query=query, api_key=NEWS_API_API_KEY, api_key2=NEWS_DATA_IO_API_KEY)
queries.append(articles)
time.sleep(1)
macroeconomic_indicator_dataframes = (inflation_rate, interest_rates, gdp_growth_rate, trends_data, commodities_prices, market_indices, currency_strength, queries)
return macroeconomic_indicator_dataframes
def get_inflation_rate(start_date:str, end_date:str) -> pd.DataFrame:
# Using yfinance to fetch historical data for consumer price index as a substitute for inflation rates
cpi_data = {}
for country, ticker in countries.items():
data = yf.download(ticker, start=start_date, end=end_date, progress=False)
if not data.empty:
# Calculate percentage change in close price as a proxy for inflation rate
inflation_rate = (data['Close'].iloc[-1] - data['Close'].iloc[0]) / data['Close'].iloc[0] * 100
cpi_data[country] = inflation_rate
inflation_rates = pd.DataFrame(list(cpi_data.items()), columns=['Country', 'InflationRate'])
return inflation_rates
def get_central_bank_interest_rates(start_date:str, end_date:str) -> pd.DataFrame:
# Using yfinance to fetch market indices data as a substitute for interest rates
stock_indices = {}
for country, ticker in countries.items():
data = yf.download(ticker, start=start_date, end=end_date, progress=False)
if not data.empty:
# Calculate average close price as a proxy for interest rates
avg_close_price = data['Close'].mean()
stock_indices[country] = avg_close_price
interest_rates = pd.DataFrame(list(stock_indices.items()), columns=['Country', 'InterestRate'])
return interest_rates
def get_gdp_growth_rate_last_quarter(start_date:str, end_date:str) -> pd.DataFrame:
# Using yfinance to fetch historical data for GDP or similar metric to calculate growth rate for last quarter
gdp_growth_data = {}
for country, ticker in countries.items():
data = yf.download(ticker, start=start_date, end=end_date, progress=False)
if not data.empty:
# Calculate percentage growth rate for last quarter
try:
gdp_growth = (data['Close'].iloc[-1] - data['Close'].iloc[-2]) / data['Close'].iloc[-2] * 100
gdp_growth_data[country] = gdp_growth
except IndexError as index_error:
logging.warning(f"An index error occurred: {index_error}")
except Exception as e:
logging.error(f"An error occurred: {e}")
gdp_growth_rate = pd.DataFrame(list(gdp_growth_data.items()), columns=['Country', 'GDPGrowth'])
return gdp_growth_rate
def get_google_trends(keywords: list, timeframe:str='now 7-d'):
pytrends.build_payload(keywords, timeframe=timeframe)
data = pytrends.interest_over_time()
return data
def _fetch_news(query:str, api_key:str, api_key2:str)->list:
page_size = 5
url = f'https://newsapi.org/v2/everything?q={query}&pageSize={page_size}&apiKey={api_key}'
response = requests.get(url)
if response.status_code == 200:
return response.json()['articles']
else:
logging.error(f"Failed to fetch news from NewsAPI: {response.status_code} {response.text} Trying NewsDataIO...")
# Fallback to Newsdata.io
fallback_url = f'https://newsdata.io/api/1/news?apikey={api_key2}&q={query}'
fallback_response = requests.get(fallback_url)
if fallback_response.status_code == 200:
return fallback_response.json()['results']
else:
logging.error(f"Failed to fetch news from both newsapi.org and newsdata.io: {fallback_response.status_code} {fallback_response.text}")
return []
def get_commodities_prices(start_date:str, end_date:str) -> pd.DataFrame:
commodities = {
'Gold': 'GC=F', # Gold Futures
'Oil': 'CL=F', # Crude Oil Futures
'Silver': 'SI=F', # Silver Futures
'Copper': 'HG=F', # Copper Futures
'Wheat': 'ZW=F', # Wheat Futures
'Soybeans': 'ZS=F', # Soybean Futures
'Platinum': 'PL=F', # Platinum Futures
'Palladium': 'PA=F' # Palladium Futures
}
commodities_data = {}
for commodity, ticker in commodities.items():
data = yf.download(ticker, start=start_date, end=end_date, progress=False)
if not data.empty:
commodities_data[commodity] = data['Close'].pct_change() * 100
commodities_df = pd.DataFrame(list(commodities_data.items()), columns=['Commodity', 'Price Change'])
return commodities_df
def get_market_indices(start_date:str,end_date:str) -> pd.DataFrame:
indices = {
'S&P 500': '^GSPC',
'NASDAQ': '^IXIC',
'DAX': '^GDAXI',
'FTSE 100': '^FTSE',
'Nikkei 225': '^N225',
'Euro Stoxx 50': '^STOXX50E',
'VIX': '^VIX', # Volatility Index
'US 10Y Treasury Yield': '^TNX' # US Treasury Yield 10 Years
}
indices_data = {}
for index, ticker in indices.items():
data = yf.download(ticker, start=start_date, end=end_date, progress=False)
if not data.empty:
indices_data[index] = data['Close'].pct_change() * 100
indices_df = pd.DataFrame(list(indices_data.items()), columns=['Index', 'Price Change'])
return indices_df
def get_currency_strength(start_date, end_date) -> pd.DataFrame:
currency_pairs = {
'EURUSD': 'EURUSD=X',
'JPYUSD': 'JPYUSD=X',
'GBPUSD': 'GBPUSD=X',
'CNYUSD': 'CNYUSD=X',
'TRYUSD': 'TRYUSD=X',
'AUDUSD': 'AUDUSD=X',
'CHFUSD': 'CHFUSD=X',
'KRWUSD': 'KRWUSD=X'
}
exchange_rates = {}
for pair, ticker in currency_pairs.items():
data = yf.download(ticker, start=start_date, end=end_date, progress=False)
if not data.empty:
exchange_rates[pair[:3]] = data['Close'].pct_change() * 100
currency_df = pd.DataFrame(list(exchange_rates.items()), columns=['Currency', 'Strength Change'])
return currency_df
def _get_signals(macroeconomic_indicator_dataframes:tuple) -> str:
inflation_rate, interest_rates, gdp_growth_rate, trends_data, commodities_prices, market_indices, currency_strength, queries = macroeconomic_indicator_dataframes
macroeconomic_signals_and_indicators = "\nMacroeconomic Signals:\n"
macroeconomic_signals_and_indicators += "\nInflation Rate Signals\n"
for _, row in inflation_rate.iterrows():
if row['InflationRate'] > 20:
macroeconomic_signals_and_indicators += f"The inflation rate of {row['Country']} is high at {row['InflationRate']}%. DOWN\n"
elif row['InflationRate'] < 0:
macroeconomic_signals_and_indicators += f"The inflation rate of {row['Country']} is low at {row['InflationRate']}%. UP\n"
else:
macroeconomic_signals_and_indicators += f"The inflation rate of {row['Country']} is normal at {row['InflationRate']}%. NEUTRAL\n"
macroeconomic_signals_and_indicators += "\nInterest Rate Signals\n"
for _, row in interest_rates.iterrows():
if row['InterestRate'] > 10000:
macroeconomic_signals_and_indicators += f"The interest rate of {row['Country']} is high at {row['InterestRate']}. UP\n"
elif row['InterestRate'] < 5000:
macroeconomic_signals_and_indicators += f"The interest rate of {row['Country']} is low at {row['InterestRate']}. DOWN\n"
else:
macroeconomic_signals_and_indicators += f"The interest rate of {row['Country']} is normal at {row['InterestRate']}. NEUTRAL\n"
macroeconomic_signals_and_indicators += "\nGDP Growth Rate Signals\n"
for _, row in gdp_growth_rate.iterrows():
if row['GDPGrowth'] >= 0.5:
macroeconomic_signals_and_indicators += f"The GDP growth rate of {row['Country']} is high at {row['GDPGrowth']}%. UP\n"
elif row['GDPGrowth'] < 0.5:
macroeconomic_signals_and_indicators += f"The GDP growth rate of {row['Country']} is low at {row['GDPGrowth']}%. DOWN\n"
else:
macroeconomic_signals_and_indicators += f"The GDP growth rate of {row['Country']} is normal at {row['GDPGrowth']}%. NEUTRAL\n"
macroeconomic_signals_and_indicators += "\nGoogle Trends Signals\n"
if trends_data['bitcoin'].iloc[-1] > 100 and trends_data['ethereum'].iloc[-1] > 10:
macroeconomic_signals_and_indicators += "High interest in Bitcoin and Ethereum. UP\n"
elif trends_data['bitcoin'].iloc[-1] < 50 and trends_data['ethereum'].iloc[-1] < 5:
macroeconomic_signals_and_indicators += "Low interest in Bitcoin and Ethereum. DOWN\n"
else:
macroeconomic_signals_and_indicators += "Mixed interest in Bitcoin and Ethereum. NEUTRAL\n"
macroeconomic_signals_and_indicators += "\nMarket Indices Price Signals\n"
for _, row in market_indices.iterrows():
price_change = row['Price Change'].iloc[-1]
if price_change> 10000:
macroeconomic_signals_and_indicators += f"The price change of {row['Index']} is {price_change}. UP\n"
elif price_change< 5000:
macroeconomic_signals_and_indicators += f"The price change of {row['Index']} is {price_change}. DOWN\n"
else:
macroeconomic_signals_and_indicators += f"The price change of {row['Index']} is {price_change}. NEUTRAL\n"
macroeconomic_signals_and_indicators += "\nElection Year Signal\n"
current_year = datetime.datetime.now().year
if current_year % 4 == 0:
macroeconomic_signals_and_indicators += f"This year {current_year} is an election year where most of the countries do elections. High Volatility\n"
else:
macroeconomic_signals_and_indicators += f"This year {current_year} is not an election year. No comment on Volatility.\n"
macroeconomic_signals_and_indicators += "\nCommodities Prices Change Signal\n"
for _, row in commodities_prices.iterrows():
price_change = row['Price Change'].iloc[-1]
if price_change >= 0.5:
macroeconomic_signals_and_indicators += f"The price change of {row['Commodity']} is {price_change}. UP\n"
elif price_change < 0.5:
macroeconomic_signals_and_indicators += f"The price change of {row['Commodity']} is {price_change}. DOWN\n"
else:
macroeconomic_signals_and_indicators += f"The price change of {row['Commodity']} is {price_change}. NEUTRAL\n"
macroeconomic_signals_and_indicators += "\nCurrency Strength Change Signal\n"
for _, row in currency_strength.iterrows():
strength_change = row['Strength Change'].iloc[-1]
if strength_change > 0.4:
macroeconomic_signals_and_indicators += f"The strength change of {row['Currency']} is {strength_change}. UP\n"
elif strength_change < 0.2:
macroeconomic_signals_and_indicators += f"The strength change of {row['Currency']} is {strength_change}. DOWN\n"
else:
macroeconomic_signals_and_indicators += f"The strength change of {row['Currency']} is {strength_change}. NEUTRAL\n"
macroeconomic_signals_and_indicators += "\nRelated News Articles\n"
for query in queries:
for news in query:
macroeconomic_signals_and_indicators += f"{news['title']}.\n"
return macroeconomic_signals_and_indicators
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, signals):
prompt = """
You are an experienced financial analyser that focuses on macroeconomical analysis.
You will be provided a comprehensive analysis of multiple indicators and signals.
Offer guidance on whether the price go up, down, or remain neutral with the help of these signals.
Your answer tone should be professional and technical yet easy to understand.
ONLY ANSWER IN TURKISH.
<Example 1>:
<HUMAN>:
Macroeconomic Signals:
Inflation Rate Signals
US inflation rate is normal with 19.622963548898117%. NEUTRAL
UK inflation rate is low with -2.794459435544367%. UP
EU inflation rate is normal with 10.725078188335043%. NEUTRAL
China inflation rate is low with -9.806028274777105%. UP
India inflation rate is high with 20.423220224566734%. DOWN
Turkey inflation rate is high with 44.78667852482656%. DOWN
Japan inflation rate is high with 36.20889669289177%. DOWN
Interest Rate Signals
US interest rate is low with 4312.705461357694. DOWN
UK interest rate is normal with 7615.57580953931. NEUTRAL
EU interest rate is high with 15743.392643229166. UP
China interest rate is low with 3166.8546579619983. DOWN
India interest rate is high with 64055.480915178574. UP
Turkey interest rate is low with 2821.4156112972455. DOWN
Japan interest rate is high with 30915.395428417174. UP
GDP Growth Rate Signals
US GDP growth rate is low with 0.07509755941103574%. DOWN
UK GDP growth rate is high with 0.637486525155803%. UP
EU GDP growth rate is high with 0.9520213397443532%. UP
China GDP growth rate is low with -0.16187801502031762%. DOWN
India GDP growth rate is high with 1.1813434207185356%. UP
Turkey GDP growth rate is low with 0.12479279223968566%. DOWN
Japan GDP growth rate is high with 1.5042856359534253%. UP
Google Trends Signals
Mixed interest in Bitcoin and Ethereum. NEUTRAL
Market Indices Price Signals
S&P 500 price change is 0.07509755941104146. DOWN
NASDAQ price change is 0.01716301438894341. DOWN
DAX price change is 0.9520213397443467. DOWN
FTSE 100 price change is 0.637486525155806. DOWN
Nikkei 225 price change is 1.5042856359534174. DOWN
Euro Stoxx 50 price change is 0.8495690546351353. DOWN
VIX price change is 2.0900340647264315. DOWN
US 10Y Treasury Yield price change is -0.6789024496325013. DOWN
Election Year Signal
This year 2024 is an election year where most of the countries do elections. High Volatility
Commodities Prices Change Signal
Gold price change is 1.6084943433625654. UP
Oil price change is 0.9164172353136602. UP
Silver price change is 2.7732172951330902. UP
Copper price change is -0.9665027734902298. DOWN
Wheat price change is -1.2836438923395477. DOWN
Soybeans price change is -2.07106598984772. DOWN
Platinum price change is 0.12100941539465726. DOWN
Palladium price change is -0.19500804708108. DOWN
Currency Strength Change Signal
EUR strength change is 0.059294316174374195. DOWN
JPY strength change is 0.4743261914650576. UP
GBP strength change is 0.2555503062871667. NEUTRAL
CNY strength change is 0.9474790023711543. UP
CAD strength change is -0.010470133724260755. DOWN
AUD strength change is -0.08205419826939897. DOWN
CHF strength change is -0.059930150097098345. DOWN
KRW strength change is 0.41996974021509814. UP
Related News Articles
Did Altcoin Hunters Miss Meme Coin Season? KAI Cat Says Not Even Close..
New Play-to-Earn Token Nears $4 Million in Presale, Combining Gaming, Staking, and Crypto.
Top 3 Crypto Gems with 100x Gains Potential – $PEPU, $CHUANPU, and $PLAY.
The 7 biggest cryptocurrency myths.
The Banana Game May Not Be a Scam But It’s Still Not Worth Your Time.
Israel's many conflicts could soon crack its Iron Dome.
'Serious breaches' of international law committed in Tigray War, watchdog says.
Russia's talking about a 6th-generation fighter jet while its Su-57 sits out the Ukraine war.
Hamas leader believes civilian deaths are ‘necessary sacrifices’ in Israeli war, leaked letters show.
Meet NATO's next chief, the 'Trump whisperer' and fierce critic of Vladimir Putin.
Crypto Market Pullback Expected to Bounce Back Soon, PlayDoge Presale Still Going Strong.
US Presidential debate impacts political memecoin market.
VanEck SOL ETF Filing – Expert Predicts Solana Price’s Next Move.
Crypto Resurgence: Navigating The Boom In Cryptocurrency Investments.
Crypto Firms Must Report Info On Trades To IRS Under New Anti-Tax Evasion Rule.
Top 3 Meme Coins to Buy in June to 100x Your Investment – $WAI, $DAWGZ, and $PLAY.
Experts Bullish On Ethereum ETFs Launching July 4, Predicting Potential Surge Beyond $7,000.
Why FTX’s Generous Bankruptcy Payouts Still Leave Some Creditors Cold.
US Bitcoin Spot ETFs Milestone: 25,729 BTC Acquired In A Week.
Bitcoin Firm And University Of Austin Partner For $5 Million Endowment Fund.
Top Gainer Today: Fetch.ai (FET) Price Keeps Rallying – What Is the Reason for Its Continued Surge?.
The Backbone of Cybersecurity: Hardware Security Modules.
Valuing Crypto Assets: Navigating The New Financial Frontier.
This Altcoin Gem Will Overtake Solana, Predicts Arthur Hayes.
Solana Eyes $200 Rebound As New Adoption-Driving Technology Debuts.
<AI>:
Enflasyon Oranı Sinyalleri
ABD: %19.62 ile normal (NÖTR)
Birleşik Krallık: % -2.79 ile düşük (YÜKSELİŞ)
AB: %10.72 ile normal (NÖTR)
Çin: % -9.81 ile düşük (YÜKSELİŞ)
Hindistan: %20.42 ile yüksek (DÜŞÜŞ)
Türkiye: %44.79 ile yüksek (DÜŞÜŞ)
Japonya: %36.21 ile yüksek (DÜŞÜŞ)
Faiz Oranı Sinyalleri
ABD: 4312.71 ile düşük (DÜŞÜŞ)
Birleşik Krallık: 7615.58 ile normal (NÖTR)
AB: 15743.39 ile yüksek (YÜKSELİŞ)
Çin: 3166.85 ile düşük (DÜŞÜŞ)
Hindistan: 64055.48 ile yüksek (YÜKSELİŞ)
Türkiye: 2821.42 ile düşük (DÜŞÜŞ)
Japonya: 30915.40 ile yüksek (YÜKSELİŞ)
GSYH Büyüme Oranı Sinyalleri
ABD: %0.08 ile düşük (DÜŞÜŞ)
Birleşik Krallık: %0.64 ile yüksek (YÜKSELİŞ)
AB: %0.95 ile yüksek (YÜKSELİŞ)
Çin: % -0.16 ile düşük (DÜŞÜŞ)
Hindistan: %1.18 ile yüksek (YÜKSELİŞ)
Türkiye: %0.12 ile düşük (DÜŞÜŞ)
Japonya: %1.50 ile yüksek (YÜKSELİŞ)
Piyasa Endeksleri Fiyat Sinyalleri
S&P 500: % -0.08 (DÜŞÜŞ)
NASDAQ: % -0.02 (DÜŞÜŞ)
DAX: %0.95 (DÜŞÜŞ)
FTSE 100: %0.64 (DÜŞÜŞ)
Nikkei 225: %1.50 (DÜŞÜŞ)
Euro Stoxx 50: %0.85 (DÜŞÜŞ)
VIX: %2.09 (DÜŞÜŞ)
ABD 10Y Hazine Tahvili Getirisi: % -0.68 (DÜŞÜŞ)
Emtia Fiyat Değişim Sinyalleri
Altın: %1.61 (YÜKSELİŞ)
Petrol: %0.92 (YÜKSELİŞ)
Gümüş: %2.77 (YÜKSELİŞ)
Bakır: % -0.97 (DÜŞÜŞ)
Buğday: % -1.28 (DÜŞÜŞ)
Soya Fasulyesi: % -2.07 (DÜŞÜŞ)
Platin: %0.12 (DÜŞÜŞ)
Paladyum: % -0.20 (DÜŞÜŞ)
Para Birimi Güç Değişim Sinyalleri
EUR: % -0.06 (DÜŞÜŞ)
JPY: %0.47 (YÜKSELİŞ)
GBP: %0.26 (NÖTR)
CNY: %0.95 (YÜKSELİŞ)
TRY: % -0.01 (DÜŞÜŞ)
AUD: % -0.08 (DÜŞÜŞ)
CHF: % -0.06 (DÜŞÜŞ)
KRW: %0.42 (YÜKSELİŞ)
Ek Faktörler
Google Trends: Bitcoin ve Ethereum’a karmaşık ilgi (NÖTR)
Seçim Yılı: Birçok ülkede seçimler nedeniyle yüksek volatilite bekleniyor.
İlgili Haberler: Jeopolitik gerilimler, kripto para gelişmeleri ve ekonomik politika değişikliklerine yüksek odaklanma.
Ekonomik Durum Özeti
Küresel Enflasyon: ABD ve AB gibi büyük ekonomilerde normal oranlar, ancak Hindistan, Rusya ve Japonya’da yüksek oranlar enflasyonist baskıları gösteriyor.
Faiz Oranları: AB, Hindistan ve Japonya gibi kilit ekonomilerde yüksek faiz oranları, bu bölgelerde enflasyonu kontrol altına almak için sıkı bir para politikası duruşu olduğunu gösteriyor.
GSYH Büyümesi: ABD ve Çin hariç çoğu bölgede genel olarak pozitif büyüme, bu iki ülkede ise düşük veya negatif büyüme potansiyel ekonomik yavaşlamalara işaret ediyor.
Piyasa Endeksleri: Başlıca endekslerde aşağı yönlü eğilimler, ayı piyasası hissiyatı ve potansiyel ekonomik yavaşlamaları gösteriyor.
Emtialar: Kıymetli metallerde yükseliş eğilimi, güvenli liman varlıklarına yönelimi işaret ederken, bakır gibi endüstriyel emtialarda düşüş eğilimi potansiyel endüstriyel yavaşlamaları gösteriyor.
Para Birimi Gücü: JPY ve CNY’de belirgin güç, diğer ana para birimlerinde ise zayıflık veya nötr durumlar.
Genel Rehberlik
Küresel ekonomik durum, bazı bölgelerde ekonomik güç ve büyüme belirtileri görülürken, diğerlerinde yavaşlama ve enflasyonist baskıların olduğu karmaşık sinyallerle karakterizedir.
Ana endişe alanları arasında birkaç büyük ekonomideki yüksek enflasyon ve piyasa endekslerindeki ayı piyasası eğilimleri yer alıyor. Jeopolitik manzara, yaklaşan seçimler ve jeopolitik gerilimler, küresel ekonomik görünümde ekstra bir volatilite katmanı eklemektedir.
Yatırım stratejileri, kıymetli metaller gibi güvenli liman varlıklarına odaklanmalı ve sanayi üretimine bağlı hisse senetleri ve emtialarda temkinli olunmalıdır. Bu karmaşık ekonomik ortamda merkez bankası politikalarının ve jeopolitik gelişmelerin izlenmesi kritik olacaktır.
Now it's your turn:
"""
final_answer = llm.invoke(prompt + signals)
final_answer = final_answer.content
return final_answer
def visualize_data(macroeconomic_indicator_dataframes) -> go.Figure:
inflation_rate, interest_rates, gdp_growth_rate, trends_data, commodities_prices, market_indices, currency_strength, _ = macroeconomic_indicator_dataframes
# Create subplots
fig = make_subplots(
rows=3, cols=2,
subplot_titles=(
"Inflation Rate",
"Interest Rates",
"GDP Growth Rate",
"Google Trends",
"Commodities Prices",
"Currency Strength"
)
)
# Inflation Rate
fig.add_trace(
go.Scatter(x=inflation_rate['Country'], y=inflation_rate['InflationRate'], mode='lines+markers', name='Inflation Rate'),
row=1, col=1
)
# Interest Rates
fig.add_trace(
go.Scatter(x=interest_rates['Country'], y=interest_rates['InterestRate'], mode='lines+markers', name='Interest Rates'),
row=1, col=2
)
# GDP Growth Rate
fig.add_trace(
go.Scatter(x=gdp_growth_rate['Country'], y=gdp_growth_rate['GDPGrowth'], mode='lines+markers', name='GDP Growth Rate'),
row=2, col=1
)
# Google Trends
for keyword in trends_data.columns:
fig.add_trace(
go.Scatter(x=trends_data.index, y=trends_data[keyword], mode='lines', name=keyword),
row=2, col=2
)
# Update layout
fig.update_layout(
height=900, width=1200, title_text="Macroeconomic Indicators and Signals",
margin=dict(l=50, r=50, b=50, t=100), # Adjust margins to improve layout
showlegend=False # Hide legend if it causes overlap
)
return fig
def macroeconomic_analyser(start_date, end_date, visualization:bool=True) -> tuple[str,str]:
macroeconomic_indicator_dataframes = _get_indicators(start_date=start_date, end_date=end_date)
macroeconomic_signals = _get_signals(macroeconomic_indicator_dataframes)
fig_html = None
if visualization:
fig = visualize_data(macroeconomic_indicator_dataframes)
fig_html = pio.to_html(fig, full_html=True)
llm = _get_llm(model_name="llama3")
final_answer = get_answer_from_llm(llm=llm,signals=macroeconomic_signals)
return final_answer, fig_html
if __name__ == '__main__':
macroeconomic_analysis = macroeconomic_analyser(start_date='2023-01-13', end_date='2024-01-13')
print(macroeconomic_analysis)