Repository navigation
Expand file tree
/
Copy pathinvestment_portfolio.exs
More file actions
1500 lines (1283 loc) · 48.1 KB
/
Copy pathinvestment_portfolio.exs
File metadata and controls
1500 lines (1283 loc) · 48.1 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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Investment Portfolio Agent Example
#
# This example demonstrates a sophisticated LLM-powered investment advisor agent.
# It showcases dynamic workflow generation, tool chaining, and state management
# for complex workflows that adapt to user requests and analysis results.
#
# Key concepts demonstrated:
# 1. Dynamic workflow generation based on evolving context
# 2. Intelligent tool selection and sequencing
# 3. Multi-branch decision paths based on data
# 4. State management via Store interface
# 5. Error recovery strategies
#
# Run with: mix run examples/investment_portfolio.exs
defmodule MockInvestmentProvider do
@moduledoc """
Mock LLM provider that demonstrates dynamic workflow generation for investment analysis.
This provider simulates an LLM making intelligent decisions based on:
- Current portfolio state
- Historical analysis results
- Market conditions
- Client risk preferences
- Previous tool execution outcomes
Unlike static DAG workflows, it dynamically chooses the next steps based on
the evolving context and state.
"""
require Logger
@doc """
Generate a response based on the current conversation state.
Dynamically decides which tools to use based on previous tool results and user input.
"""
def generate_response(messages, opts \\ []) do
# 0. Log that the mock provider is being called
Logger.info(
"MockInvestmentProvider.generate_response called with #{length(messages)} messages"
)
Logger.debug("Messages: #{inspect(messages)}")
Logger.debug("Options: #{inspect(opts)}")
# 1. Extract key information from conversation history
last_user_message = get_last_user_message(messages)
tool_results = get_tool_results(messages)
# 2. Determine conversation state and context
context = build_conversation_context(last_user_message, tool_results)
# 3. Log detailed analysis for debugging
Logger.debug("Analyzing conversation context: #{inspect(context)}")
# 4. Make dynamic workflow decisions based on context
# Use the workflow state to drive the next phase of analysis
cond do
# PHASE 1: INITIAL PORTFOLIO ANALYSIS PATH
# Extended matching condition to trigger tool call flow on first interaction
# If user has sent any message and we haven't started analysis yet, proactively start workflow
(context.is_new_portfolio_request or String.length(last_user_message) > 0) and
not context.has_etf_data ->
Logger.info("Starting new portfolio analysis workflow")
# Dynamic behavior: Choose initial analysis approach based on question content
{:ok,
%{
"choices" => [
%{
"message" => %{
"content" =>
"I'll analyze available investment options for your #{context.risk_profile} risk profile.",
"tool_calls" => [
%{
"id" => "call_#{:rand.uniform(999_999)}",
"type" => "function",
"function" => %{
"name" => "etf_screener",
"arguments" =>
Jason.encode!(%{
"risk_level" => context.risk_level,
"category" => determine_category(last_user_message)
})
}
}
]
}
}
]
}}
# PHASE 2: PORTFOLIO CONSTRUCTION PATH
# After ETF screening, create the portfolio if not done yet
context.has_etf_data and not context.has_portfolio ->
Logger.info("Proceeding to portfolio construction phase")
# Extract ETFs from screener results for portfolio construction
etfs = extract_etfs(context.screener_result)
{:ok,
%{
"choices" => [
%{
"message" => %{
"content" =>
"Based on the available ETFs, I'll construct a #{context.risk_profile} portfolio for you.",
"tool_calls" => [
%{
"id" => "call_#{:rand.uniform(999_999)}",
"type" => "function",
"function" => %{
"name" => "portfolio_constructor",
"arguments" =>
Jason.encode!(%{
"risk_profile" => context.risk_profile,
"etfs" => etfs
})
}
}
]
}
}
]
}}
# PORTFOLIO EVALUATION PATH
# After constructing the portfolio, perform backtesting
context.has_portfolio and not context.has_backtest and should_backtest?(last_user_message) ->
Logger.info("Portfolio constructed, proceeding to backtesting")
{:ok,
%{
"choices" => [
%{
"message" => %{
"content" =>
"Let me evaluate how this portfolio would have performed historically.",
"tool_calls" => [
%{
"id" => "call_#{:rand.uniform(999_999)}",
"type" => "function",
"function" => %{
"name" => "portfolio_backtester",
"arguments" =>
Jason.encode!(%{
"portfolio" => context.portfolio,
"years" => 10
})
}
}
]
}
}
]
}}
# OPTIMIZATION PATHS - Multiple potential branches based on context
# Dynamic branching based on risk adjustment requests
context.has_portfolio and context.risk_adjustment_requested ->
Logger.info("Risk adjustment requested, optimizing portfolio")
# Determine optimization direction based on request
risk_preference = determine_risk_preference(last_user_message, context.risk_profile)
{:ok,
%{
"choices" => [
%{
"message" => %{
"content" => "I'll adjust the portfolio to #{risk_preference} risk level.",
"tool_calls" => [
%{
"id" => "call_#{:rand.uniform(999_999)}",
"type" => "function",
"function" => %{
"name" => "portfolio_optimizer",
"arguments" =>
Jason.encode!(%{
"portfolio" => context.portfolio,
"preferences" => %{
"risk_tolerance" => risk_preference
}
})
}
}
]
}
}
]
}}
# PORTFOLIO ANALYSIS PATH
# When we have a complete portfolio with backtest and user wants analysis
context.has_portfolio and context.has_backtest and context.analysis_requested ->
Logger.info(
"Comprehensive analysis requested after portfolio construction and backtesting"
)
# Generate comprehensive analysis without additional tool calls
portfolio = context.portfolio
backtest = context.backtest
{:ok,
%{
"choices" => [
%{
"message" => %{
"content" => generate_portfolio_analysis(portfolio, backtest),
"role" => "assistant"
}
}
]
}}
# MARKET SCENARIO ANALYSIS PATH
# Simulate market conditions when requested
context.has_portfolio and context.market_scenario_requested ->
Logger.info("Market scenario analysis requested")
# Dynamically choose which simulation to run based on the request
scenario_type = determine_scenario_type(last_user_message)
{:ok,
%{
"choices" => [
%{
"message" => %{
"content" =>
"I'll simulate how your portfolio might perform during a #{scenario_type} market.",
"tool_calls" => [
%{
"id" => "call_#{:rand.uniform(999_999)}",
"type" => "function",
"function" => %{
"name" => "market_simulator",
"arguments" =>
Jason.encode!(%{
"portfolio" => context.portfolio,
"scenario" => scenario_type
})
}
}
]
}
}
]
}}
# ERROR RECOVERY PATH
# When a previous tool has failed and we need to recover
context.has_error ->
Logger.info("Recovering from previous error: #{context.error_message}")
# Different recovery strategies based on which tool failed
case context.failed_tool do
"portfolio_constructor" ->
{:ok,
%{
"choices" => [
%{
"message" => %{
"content" =>
"I encountered an issue creating your portfolio. Let me try with a different approach.",
"tool_calls" => [
%{
"id" => "call_#{:rand.uniform(999_999)}",
"type" => "function",
"function" => %{
"name" => "portfolio_constructor",
"arguments" =>
Jason.encode!(%{
"risk_profile" => context.risk_profile,
# Simplified fallback
"etfs" => ["VTI", "BND"],
"fallback" => true
})
}
}
]
}
}
]
}}
_ ->
{:ok,
%{
"choices" => [
%{
"message" => %{
"content" =>
"I encountered an issue in my analysis. Let me summarize what I know so far.",
"role" => "assistant"
}
}
]
}}
end
# DEFAULT INFORMATIONAL RESPONSE
# When no specific tool action is needed
true ->
Logger.info("Providing informational response")
# Generate a contextual response based on what we know
content = generate_contextual_response(context, last_user_message)
{:ok,
%{
"choices" => [
%{
"message" => %{
"content" => content,
"role" => "assistant"
}
}
]
}}
end
end
#
# Context building functions
#
defp get_last_user_message(messages) do
messages
|> Enum.reverse()
|> Enum.find(fn msg ->
is_map(msg) and (msg["role"] == "user" or msg[:role] == "user")
end)
|> case do
nil -> ""
%{"content" => content} -> content
%{content: content} -> content
_ -> ""
end
end
defp get_tool_results(messages) do
# Log the full message list to help with debugging
Logger.debug("Messages for tool extraction: #{inspect(messages)}")
result =
messages
|> Enum.filter(fn msg ->
is_map(msg) and (msg["role"] == "function" or msg[:role] == "function")
end)
|> Enum.map(fn msg ->
name = msg["name"] || msg[:name]
content = msg["content"] || msg[:content]
Logger.info("Found tool result for: #{name}")
{name, Jason.decode!(content)}
end)
|> Map.new()
# Log the extracted tool results
Logger.debug("Extracted tool results: #{inspect(result)}")
result
end
defp build_conversation_context(last_user_message, tool_results) do
# Log output for debugging purposes
Logger.info("Building conversation context based on: \"#{last_user_message}\"")
Logger.info("Available tool results: #{inspect(Map.keys(tool_results))}")
Logger.debug("Detailed tool results: #{inspect(tool_results)}")
# Extract key state information
question = String.downcase(last_user_message)
# Get results from different tools if available
screener_result = Map.get(tool_results, "etf_screener")
portfolio = Map.get(tool_results, "portfolio_constructor")
backtest = Map.get(tool_results, "portfolio_backtester")
optimized = Map.get(tool_results, "portfolio_optimizer")
# Log the workflow state progression
workflow_state =
cond do
optimized -> "Phase 4: Portfolio Optimization Complete"
backtest -> "Phase 3: Portfolio Backtesting Complete"
portfolio -> "Phase 2: Portfolio Construction Complete"
screener_result -> "Phase 1: ETF Screening Complete"
true -> "Phase 0: Initial Analysis"
end
Logger.info("Current workflow state: #{workflow_state}")
# Detect the latest portfolio version
latest_portfolio = optimized || portfolio
# Identify conversation state
%{
# Data availability flags
has_etf_data: screener_result != nil,
has_portfolio: latest_portfolio != nil,
has_backtest: backtest != nil,
has_optimized: optimized != nil,
# Request classification
is_new_portfolio_request: is_new_portfolio_request?(question),
risk_adjustment_requested: is_risk_adjustment_request?(question),
analysis_requested: is_analysis_request?(question),
market_scenario_requested: is_market_scenario_request?(question),
# User preferences
risk_profile: determine_risk_profile(question, latest_portfolio),
risk_level: map_risk_profile_to_level(determine_risk_profile(question, latest_portfolio)),
# Tool results for reference
screener_result: screener_result,
portfolio: latest_portfolio,
backtest: backtest,
# Error handling
has_error: String.contains?(question, ["error", "fail", "issue", "problem"]),
error_message:
if(String.contains?(question, ["error", "fail", "issue", "problem"]),
do: last_user_message,
else: nil
),
failed_tool:
if(String.contains?(question, "portfolio construction"),
do: "portfolio_constructor",
else: nil
)
}
end
#
# Decision and classification helper functions
#
defp is_new_portfolio_request?(question) do
question = String.downcase(question)
# Significantly broaden matching conditions, trigger workflow for any investment-related keywords
# This improves the success rate of demonstrating dynamic workflow capabilities in the example
contains_keywords?(question, [
"create",
"build",
"design",
"new",
"looking",
"want",
"need",
"help",
"advice",
"recommend",
"suggest",
"retirement",
"invest",
"moderate",
"risk",
"growth",
"income",
"conservative",
"aggressive",
"etf",
"fund",
"stock",
"bond",
"allocate",
"allocation",
"diversify",
"portfolio",
"investment",
"money"
])
end
defp is_risk_adjustment_request?(question) do
question = String.downcase(question)
contains_keywords?(question, ["risk", "aggressive", "conservative"]) and
(contains_keywords?(question, [
"adjust",
"change",
"modify",
"increase",
"decrease",
"more",
"less"
]) or
contains_keywords?(question, [
"too risky",
"too safe",
"too conservative",
"too aggressive"
]))
end
defp is_analysis_request?(question) do
question = String.downcase(question)
contains_keywords?(question, [
"analyze",
"evaluate",
"show",
"explain",
"detail",
"tell me about"
]) or
contains_keywords?(question, ["how would", "performance", "return", "history", "past"])
end
defp is_market_scenario_request?(question) do
question = String.downcase(question)
contains_keywords?(question, ["what if", "scenario", "crash", "bear", "bull", "recession"]) or
contains_keywords?(question, ["downturn", "simulation", "crisis", "boom"])
end
defp determine_risk_profile(question, portfolio) do
# If we already have a portfolio, use its risk profile as default
default_profile = if portfolio, do: portfolio["risk_profile"], else: "Moderate"
question = String.downcase(question)
cond do
contains_keywords?(question, ["conservative", "safe", "low risk", "cautious", "risk averse"]) ->
"Conservative"
contains_keywords?(question, ["aggressive", "high risk", "growth", "high return", "risky"]) ->
"Aggressive"
contains_keywords?(question, ["balanced", "moderate", "middle"]) ->
"Moderate"
true ->
default_profile
end
end
defp map_risk_profile_to_level(risk_profile) do
case risk_profile do
"Conservative" -> "Low"
"Moderate" -> "Moderate"
"Aggressive" -> "High"
_ -> "Moderate"
end
end
defp determine_risk_preference(question, _current_profile) do
question = String.downcase(question)
cond do
contains_keywords?(question, [
"safer",
"lower risk",
"less risk",
"conservative",
"too risky",
"too aggressive"
]) ->
"Lower"
contains_keywords?(question, [
"more risk",
"higher risk",
"aggressive",
"growth",
"too safe",
"too conservative"
]) ->
"Higher"
true ->
"Same"
end
end
defp determine_category(question) do
question = String.downcase(question)
cond do
contains_keywords?(question, ["tech", "technology", "innovation"]) -> "Technology"
contains_keywords?(question, ["income", "dividend", "yield"]) -> "Income"
contains_keywords?(question, ["global", "international", "worldwide"]) -> "International"
contains_keywords?(question, ["esg", "sustainable", "green", "social"]) -> "ESG"
true -> "Broad Market"
end
end
defp determine_scenario_type(question) do
question = String.downcase(question)
cond do
contains_keywords?(question, ["crash", "recession", "bear", "crisis", "down"]) ->
"Bear Market"
contains_keywords?(question, ["boom", "bull", "growth", "up", "recovery"]) ->
"Bull Market"
contains_keywords?(question, ["inflation", "rising rates", "interest"]) ->
"High Inflation"
contains_keywords?(question, ["volatility", "uncertainty"]) ->
"High Volatility"
# Default to stress test
true ->
"Bear Market"
end
end
#
# Response generation functions
#
defp generate_contextual_response(context, _question) do
cond do
context.has_portfolio and context.has_backtest ->
portfolio = context.portfolio
backtest = context.backtest
"Based on our analysis, your #{String.downcase(portfolio["risk_profile"])} portfolio " <>
"has an expected return of #{Float.round(portfolio["expected_return"], 2)}%. " <>
"The historical analysis shows a compound annual growth rate of #{Float.round(backtest["cagr"], 2)}% " <>
"with a maximum drawdown of #{Float.round(backtest["max_drawdown"], 2)}%. " <>
"Would you like me to adjust the risk level or analyze specific market scenarios?"
context.has_portfolio ->
portfolio = context.portfolio
"I've created a #{String.downcase(portfolio["risk_profile"])} risk portfolio " <>
"with an expected return of #{Float.round(portfolio["expected_return"], 2)}%. " <>
"The portfolio consists of #{length(portfolio["allocations"])} ETFs. " <>
"Would you like me to run a historical performance analysis on this portfolio?"
context.has_etf_data ->
screener = context.screener_result
"I've found #{screener["count"]} ETFs that match your criteria. " <>
"Would you like me to construct a portfolio using these funds?"
true ->
"I can help you create and analyze an investment portfolio. " <>
"Would you like me to recommend a portfolio based on your risk preference?"
end
end
defp generate_portfolio_analysis(portfolio, backtest) do
"""
I've completed a comprehensive analysis of your #{String.downcase(portfolio["risk_profile"])} risk portfolio.
Portfolio Composition:
#{format_allocations(portfolio["allocations"])}
Expected Annual Return: #{Float.round(portfolio["expected_return"], 2)}%
Historical Performance (#{backtest["years"]} years):
- Compound Annual Growth Rate (CAGR): #{Float.round(backtest["cagr"], 2)}%
- Risk-adjusted Return (Sharpe Ratio): #{Float.round(backtest["sharpe_ratio"], 2)}
- Maximum Drawdown: #{Float.round(backtest["max_drawdown"], 2)}%
This portfolio offers a balance of #{cond do
portfolio["risk_profile"] == "Conservative" -> "capital preservation and modest income"
portfolio["risk_profile"] == "Aggressive" -> "growth potential with higher volatility"
true -> "growth and stability"
end}.
Would you like me to adjust the risk level or test how this portfolio might perform in specific market scenarios?
"""
end
#
# Utility functions
#
defp contains_keywords?(text, keywords) do
Enum.any?(keywords, &String.contains?(text, &1))
end
defp extract_etfs(screener_result) do
Enum.map(screener_result["etfs"], & &1["ticker"])
end
defp format_allocations(allocations) do
allocations
|> Enum.map(fn alloc ->
"- #{alloc["ticker"]}: #{Float.round(alloc["allocation"] * 100, 1)}%"
end)
|> Enum.join("\n")
end
defp should_backtest?(question) do
question = String.downcase(question)
contains_keywords?(question, [
"perform",
"history",
"backtest",
"historical",
"show me",
"analysis"
]) or
contains_keywords?(question, ["how would", "how has", "past", "over time"])
end
end
defmodule LLMAgent.Examples.InvestmentTools do
@moduledoc """
Provides investment analysis tools for the portfolio advisor agent.
"""
def get_tools do
[
%{
name: "etf_screener",
description: "Screen ETFs based on criteria",
parameters: %{
"type" => "object",
"properties" => %{
"risk_level" => %{
"type" => "string",
"enum" => ["Low", "Moderate", "High"]
},
"category" => %{
"type" => "string"
}
}
},
execute: &screen_etfs/1
},
%{
name: "portfolio_constructor",
description: "Create a portfolio from ETFs",
parameters: %{
"type" => "object",
"properties" => %{
"risk_profile" => %{
"type" => "string",
"enum" => ["Conservative", "Moderate", "Aggressive"]
},
"etfs" => %{
"type" => "array",
"items" => %{
"type" => "string"
}
}
},
"required" => ["risk_profile"]
},
execute: &create_portfolio/1
},
%{
name: "portfolio_backtester",
description: "Backtest a portfolio",
parameters: %{
"type" => "object",
"properties" => %{
"portfolio" => %{
"type" => "object"
},
"years" => %{
"type" => "integer"
}
},
"required" => ["portfolio"]
},
execute: &backtest_portfolio/1
},
%{
name: "portfolio_optimizer",
description: "Optimize a portfolio",
parameters: %{
"type" => "object",
"properties" => %{
"portfolio" => %{
"type" => "object"
},
"preferences" => %{
"type" => "object"
}
},
"required" => ["portfolio", "preferences"]
},
execute: &optimize_portfolio/1
},
%{
name: "market_simulator",
description: "Simulate portfolio performance in different market scenarios",
parameters: %{
"type" => "object",
"properties" => %{
"portfolio" => %{
"type" => "object"
},
"scenario" => %{
"type" => "string",
"enum" => ["Bear Market", "Bull Market", "High Inflation", "High Volatility"]
}
},
"required" => ["portfolio", "scenario"]
},
execute: &simulate_market_scenario/1
}
]
end
# Tool implementation functions
def screen_etfs(%{"risk_level" => risk_level, "category" => category}) do
# Mock ETF data
all_etfs = [
%{
ticker: "VTI",
name: "Vanguard Total Stock Market ETF",
expense_ratio: 0.03,
category: "Broad Market",
risk_level: "Moderate",
avg_return: 10.2
},
%{
ticker: "BND",
name: "Vanguard Total Bond Market ETF",
expense_ratio: 0.035,
category: "Bond",
risk_level: "Low",
avg_return: 3.8
},
%{
ticker: "VEA",
name: "Vanguard FTSE Developed Markets ETF",
expense_ratio: 0.05,
category: "International",
risk_level: "Moderate-High",
avg_return: 8.1
},
%{
ticker: "VGT",
name: "Vanguard Information Technology ETF",
expense_ratio: 0.10,
category: "Technology",
risk_level: "High",
avg_return: 15.3
},
%{
ticker: "SCHD",
name: "Schwab US Dividend Equity ETF",
expense_ratio: 0.06,
category: "Income",
risk_level: "Moderate",
avg_return: 9.2
},
%{
ticker: "ESGV",
name: "Vanguard ESG U.S. Stock ETF",
expense_ratio: 0.09,
category: "ESG",
risk_level: "Moderate",
avg_return: 9.8
}
]
# Filter based on criteria
etfs =
all_etfs
|> Enum.filter(fn etf ->
(category == "Broad Market" or etf.category == category) and
(risk_level == "Moderate" or etf.risk_level == risk_level or
String.contains?(etf.risk_level, risk_level))
end)
%{
etfs: etfs,
count: length(etfs)
}
end
def create_portfolio(%{"risk_profile" => risk_profile} = params) do
# Check if we're in fallback mode (error recovery)
fallback = Map.get(params, "fallback", false)
# Use ETFs provided in request or default set
_provided_etfs = Map.get(params, "etfs", nil)
allocations =
case {risk_profile, fallback} do
{"Conservative", true} ->
[
%{ticker: "BND", allocation: 0.8},
%{ticker: "VTI", allocation: 0.2}
]
{"Conservative", false} ->
[
%{ticker: "BND", allocation: 0.6},
%{ticker: "VTI", allocation: 0.3},
%{ticker: "VEA", allocation: 0.1}
]
{"Moderate", true} ->
[
%{ticker: "VTI", allocation: 0.5},
%{ticker: "BND", allocation: 0.5}
]
{"Moderate", false} ->
[
%{ticker: "VTI", allocation: 0.6},
%{ticker: "BND", allocation: 0.3},
%{ticker: "VEA", allocation: 0.1}
]
{"Aggressive", true} ->
[
%{ticker: "VTI", allocation: 0.9},
%{ticker: "BND", allocation: 0.1}
]
{"Aggressive", false} ->
[
%{ticker: "VTI", allocation: 0.7},
%{ticker: "VEA", allocation: 0.2},
%{ticker: "BND", allocation: 0.1}
]
end
expected_return = calculate_expected_return(allocations)
%{
allocations: allocations,
risk_profile: risk_profile,
expected_return: expected_return
}
end
def backtest_portfolio(%{"portfolio" => portfolio, "years" => years}) do
# Mock backtest results based on portfolio risk profile
years = years || 10
# Adjust based on risk profile
{cagr, max_drawdown, sharpe_ratio} =
case portfolio["risk_profile"] do
"Conservative" -> {5.2, 10.0, 0.65}
"Moderate" -> {8.2, 20.0, 0.75}
"Aggressive" -> {11.5, 35.0, 0.82}
_ -> {8.2, 20.0, 0.75}
end
%{
years: years,
initial_investment: 100.0,
final_value: calculate_final_value(100.0, cagr, years),
cagr: cagr,
max_drawdown: max_drawdown,
sharpe_ratio: sharpe_ratio,
risk_adjusted_return: sharpe_ratio * 100.0
}
end
def backtest_portfolio(%{"portfolio" => portfolio}) do
# Default to 10 years when not specified
backtest_portfolio(%{"portfolio" => portfolio, "years" => 10})
end
def optimize_portfolio(%{
"portfolio" => portfolio,
"preferences" => %{"risk_tolerance" => risk_tolerance}
}) do
current_profile = portfolio["risk_profile"]
new_profile =
case {current_profile, risk_tolerance} do
{"Aggressive", "Lower"} -> "Moderate"
{"Moderate", "Lower"} -> "Conservative"
{"Conservative", "Higher"} -> "Moderate"
{"Moderate", "Higher"} -> "Aggressive"
_ -> current_profile
end
create_portfolio(%{"risk_profile" => new_profile})
end
def simulate_market_scenario(%{"portfolio" => portfolio, "scenario" => scenario}) do
base_return = portfolio["expected_return"]
# Simulate different market scenarios
{return_impact, volatility_impact, max_drawdown} =
case scenario do
"Bear Market" -> {-0.25, 1.5, 0.35}
"Bull Market" -> {0.15, 0.8, 0.12}
"High Inflation" -> {-0.1, 1.2, 0.18}
"High Volatility" -> {0.0, 2.0, 0.25}
_ -> {0.0, 1.0, 0.15}
end
# Calculate scenario performance
scenario_return = base_return * (1 + return_impact)
%{
scenario: scenario,
expected_return: scenario_return,
volatility_multiplier: volatility_impact,
max_drawdown: max_drawdown * 100,
summary: generate_scenario_summary(scenario, scenario_return, portfolio["risk_profile"])
}
end