toolcall-2.json•20.7 kB
{"jsonrpc": "2.0", "method": "initialize", "params": {"clientInfo": {"name": "Llama Agent", "version": "0.1"}, "protocolVersion": "2024-11-05", "capabilities": { "tools": { "subscribe": true, "listChanged": true }, "resource": { "subscribe": true, "listChanged": true } }}, "id": 1}{"jsonrpc": "2.0", "method": "notifications/initialized", "params": {}, "id": 8899}{"method":"tools/call","params":{"name":"code-to-tree","arguments":{"code":"/**\n * FinancialDataProcessor - A hypothetical C++ application for financial data analysis\n * Demonstrates various C++ features, STL usage, templates, and modern C++ techniques\n * Note: This is a synthetic example and isn't intended to be compiled as-is\n */\n\n#include <algorithm>\n#include <array>\n#include <chrono>\n#include <concepts>\n#include <deque>\n#include <filesystem>\n#include <fstream>\n#include <functional>\n#include <future>\n#include <iomanip>\n#include <iostream>\n#include <iterator>\n#include <map>\n#include <memory>\n#include <mutex>\n#include <numeric>\n#include <optional>\n#include <queue>\n#include <random>\n#include <regex>\n#include <set>\n#include <shared_mutex>\n#include <sstream>\n#include <stack>\n#include <string>\n#include <string_view>\n#include <thread>\n#include <tuple>\n#include <type_traits>\n#include <unordered_map>\n#include <unordered_set>\n#include <variant>\n#include <vector>\n\nnamespace financial_analyzer {\n\n// Forward declarations\nclass MarketData;\nclass StockPrice;\nclass Portfolio;\nclass FinancialInstrument;\n\n// Type definitions for improved readability\nusing TimePoint = std::chrono::system_clock::time_point;\nusing StockSymbol = std::string;\nusing Price = double;\nusing Quantity = int;\nusing TransactionID = std::string;\n\n// Custom exception class\nclass FinancialDataException : public std::exception {\nprivate:\n std::string message;\n\npublic:\n explicit FinancialDataException(std::string_view msg) : message(msg) {}\n const char* what() const noexcept override { return message.c_str(); }\n};\n\n// Concepts for type constraints\ntemplate<typename T>\nconcept Numerical = std::is_arithmetic_v<T>;\n\ntemplate<typename T>\nconcept TimeSeries = requires(T t) {\n { t.getTimestamp() } -> std::convertible_to<TimePoint>;\n { t.getValue() } -> std::convertible_to<double>;\n};\n\n// CRTP for static polymorphism\ntemplate<typename Derived>\nclass InstrumentBase {\npublic:\n double calculateRisk() const {\n return static_cast<const Derived*>(this)->riskImplementation();\n }\n\n virtual ~InstrumentBase() = default;\n\nprotected:\n virtual double riskImplementation() const = 0;\n};\n\n// Utility template functions\ntemplate<Numerical T>\nT calculateMovingAverage(const std::vector<T>& data, size_t window) {\n if (data.size() < window) {\n throw FinancialDataException(\"Insufficient data for moving average calculation\");\n }\n \n return std::accumulate(data.end() - window, data.end(), T{}) / static_cast<T>(window);\n}\n\ntemplate<typename Container, typename Predicate>\nauto filterData(const Container& container, Predicate predicate) {\n Container result;\n std::copy_if(container.begin(), container.end(), std::back_inserter(result), predicate);\n return result;\n}\n\n// Event system using observer pattern\nclass Observable;\n\nclass Observer {\npublic:\n virtual void update(Observable* sender, const std::string& event, const std::any& data) = 0;\n virtual ~Observer() = default;\n};\n\nclass Observable {\nprivate:\n std::vector<Observer*> observers;\n std::mutex observerMutex;\n\npublic:\n void addObserver(Observer* observer) {\n std::lock_guard<std::mutex> lock(observerMutex);\n observers.push_back(observer);\n }\n\n void removeObserver(Observer* observer) {\n std::lock_guard<std::mutex> lock(observerMutex);\n auto it = std::find(observers.begin(), observers.end(), observer);\n if (it != observers.end()) {\n observers.erase(it);\n }\n }\n\n void notifyObservers(const std::string& event, const std::any& data = {}) {\n std::lock_guard<std::mutex> lock(observerMutex);\n for (auto observer : observers) {\n observer->update(this, event, data);\n }\n }\n\n virtual ~Observable() = default;\n};\n\n// Enumeration for trade types\nenum class TradeType {\n BUY,\n SELL,\n SHORT,\n COVER\n};\n\n// Class for handling financial instruments\nclass FinancialInstrument : public InstrumentBase<FinancialInstrument> {\nprivate:\n StockSymbol symbol;\n std::string name;\n std::optional<double> beta;\n std::vector<Price> historicalPrices;\n mutable std::shared_mutex dataMutex;\n\npublic:\n FinancialInstrument(StockSymbol symbol, std::string name) \n : symbol(std::move(symbol)), name(std::move(name)) {}\n\n void addPricePoint(Price price) {\n std::unique_lock lock(dataMutex);\n historicalPrices.push_back(price);\n }\n\n std::vector<Price> getPriceHistory() const {\n std::shared_lock lock(dataMutex);\n return historicalPrices;\n }\n\n double calculateVolatility() const {\n std::shared_lock lock(dataMutex);\n if (historicalPrices.size() < 2) {\n return 0.0;\n }\n\n std::vector<double> returns;\n returns.reserve(historicalPrices.size() - 1);\n \n for (size_t i = 1; i < historicalPrices.size(); ++i) {\n double dailyReturn = historicalPrices[i] / historicalPrices[i-1] - 1.0;\n returns.push_back(dailyReturn);\n }\n \n double mean = std::accumulate(returns.begin(), returns.end(), 0.0) / returns.size();\n \n double squaredSum = std::transform_reduce(\n returns.begin(), returns.end(),\n 0.0,\n std::plus<>(),\n [mean](double x) { return std::pow(x - mean, 2); }\n );\n \n return std::sqrt(squaredSum / (returns.size() - 1));\n }\n\n void setBeta(double value) {\n std::unique_lock lock(dataMutex);\n beta = value;\n }\n\n std::optional<double> getBeta() const {\n std::shared_lock lock(dataMutex);\n return beta;\n }\n\n double riskImplementation() const override {\n std::shared_lock lock(dataMutex);\n return beta.value_or(1.0) * calculateVolatility();\n }\n\n const StockSymbol& getSymbol() const { return symbol; }\n const std::string& getName() const { return name; }\n};\n\n// Transaction structure\nstruct Transaction {\n TransactionID id;\n StockSymbol symbol;\n TradeType type;\n Quantity quantity;\n Price price;\n TimePoint timestamp;\n\n Transaction(TransactionID id, StockSymbol symbol, TradeType type, \n Quantity quantity, Price price)\n : id(std::move(id)), symbol(std::move(symbol)), type(type),\n quantity(quantity), price(price), \n timestamp(std::chrono::system_clock::now()) {}\n\n double getValue() const {\n return price * quantity;\n }\n\n std::string toString() const {\n std::ostringstream oss;\n oss << \"Transaction[\" << id << \"]: \";\n \n switch (type) {\n case TradeType::BUY: oss << \"BUY \"; break;\n case TradeType::SELL: oss << \"SELL \"; break;\n case TradeType::SHORT: oss << \"SHORT \"; break;\n case TradeType::COVER: oss << \"COVER \"; break;\n }\n \n oss << quantity << \" \" << symbol << \" @ $\" \n << std::fixed << std::setprecision(2) << price\n << \" (Total: $\" << getValue() << \")\";\n \n return oss.str();\n }\n};\n\n// Portfolio class for managing instruments\nclass Portfolio : public Observable {\nprivate:\n std::string name;\n std::unordered_map<StockSymbol, Quantity> holdings;\n std::vector<Transaction> transactions;\n mutable std::shared_mutex portfolioMutex;\n\npublic:\n explicit Portfolio(std::string name) : name(std::move(name)) {}\n\n void executeTransaction(Transaction transaction) {\n std::unique_lock lock(portfolioMutex);\n \n // Update holdings based on transaction type\n switch (transaction.type) {\n case TradeType::BUY:\n case TradeType::COVER:\n holdings[transaction.symbol] += transaction.quantity;\n break;\n case TradeType::SELL:\n case TradeType::SHORT:\n holdings[transaction.symbol] -= transaction.quantity;\n break;\n }\n \n transactions.push_back(transaction);\n lock.unlock();\n \n // Notify observers\n notifyObservers(\"transaction\", transaction);\n }\n\n Quantity getHolding(const StockSymbol& symbol) const {\n std::shared_lock lock(portfolioMutex);\n auto it = holdings.find(symbol);\n return (it != holdings.end()) ? it->second : 0;\n }\n\n std::map<StockSymbol, Quantity> getAllHoldings() const {\n std::shared_lock lock(portfolioMutex);\n return std::map<StockSymbol, Quantity>(holdings.begin(), holdings.end());\n }\n\n double calculateTotalValue(const std::unordered_map<StockSymbol, Price>& currentPrices) const {\n std::shared_lock lock(portfolioMutex);\n \n return std::transform_reduce(\n holdings.begin(), holdings.end(),\n 0.0,\n std::plus<>(),\n [¤tPrices](const auto& holding) {\n auto priceIt = currentPrices.find(holding.first);\n if (priceIt != currentPrices.end()) {\n return priceIt->second * holding.second;\n }\n return 0.0;\n }\n );\n }\n\n std::vector<Transaction> getTransactionHistory() const {\n std::shared_lock lock(portfolioMutex);\n return transactions;\n }\n\n std::vector<Transaction> filterTransactions(\n std::function<bool(const Transaction&)> predicate) const {\n std::shared_lock lock(portfolioMutex);\n std::vector<Transaction> result;\n std::copy_if(transactions.begin(), transactions.end(), \n std::back_inserter(result), predicate);\n return result;\n }\n\n const std::string& getName() const { return name; }\n};\n\n// MarketData class for handling real-time data\nclass MarketData : public Observable {\nprivate:\n std::unordered_map<StockSymbol, Price> currentPrices;\n std::unordered_map<StockSymbol, std::deque<Price>> priceHistory;\n std::mutex dataMutex;\n std::atomic<bool> running{false};\n std::jthread workerThread;\n size_t historySize = 100;\n\n void simulateMarketChanges() {\n std::random_device rd;\n std::mt19937 gen(rd());\n std::normal_distribution<> priceChange(0.0, 0.01); // Mean 0, std dev 0.01\n \n while (running) {\n {\n std::lock_guard<std::mutex> lock(dataMutex);\n for (auto& [symbol, price] : currentPrices) {\n double change = 1.0 + priceChange(gen);\n price *= change;\n \n auto& history = priceHistory[symbol];\n history.push_back(price);\n if (history.size() > historySize) {\n history.pop_front();\n }\n \n notifyObservers(\"price_update\", std::make_pair(symbol, price));\n }\n }\n \n std::this_thread::sleep_for(std::chrono::seconds(1));\n }\n }\n\npublic:\n MarketData() = default;\n \n ~MarketData() {\n stopSimulation();\n }\n\n void addInstrument(const StockSymbol& symbol, Price initialPrice) {\n std::lock_guard<std::mutex> lock(dataMutex);\n currentPrices[symbol] = initialPrice;\n priceHistory[symbol] = {initialPrice};\n }\n\n std::optional<Price> getCurrentPrice(const StockSymbol& symbol) const {\n std::lock_guard<std::mutex> lock(dataMutex);\n auto it = currentPrices.find(symbol);\n if (it != currentPrices.end()) {\n return it->second;\n }\n return std::nullopt;\n }\n\n std::vector<Price> getPriceHistory(const StockSymbol& symbol) const {\n std::lock_guard<std::mutex> lock(dataMutex);\n auto it = priceHistory.find(symbol);\n if (it != priceHistory.end()) {\n return std::vector<Price>(it->second.begin(), it->second.end());\n }\n return {};\n }\n\n void startSimulation() {\n if (!running.exchange(true)) {\n workerThread = std::jthread([this](std::stop_token stoken) {\n this->simulateMarketChanges();\n });\n }\n }\n\n void stopSimulation() {\n running.store(false);\n if (workerThread.joinable()) {\n workerThread.request_stop();\n workerThread.join();\n }\n }\n\n void setHistorySize(size_t size) {\n historySize = size;\n }\n};\n\n// Analysis tools\nclass MarketAnalyzer {\npublic:\n template<typename Container>\n static auto calculateMovingAverages(const Container& prices, size_t window) {\n if (prices.size() < window) {\n return Container{};\n }\n \n Container result;\n result.reserve(prices.size() - window + 1);\n \n for (size_t i = 0; i <= prices.size() - window; ++i) {\n double sum = std::accumulate(prices.begin() + i, prices.begin() + i + window, 0.0);\n result.push_back(sum / window);\n }\n \n return result;\n }\n \n static std::pair<double, double> calculateLinearRegression(\n const std::vector<double>& x, const std::vector<double>& y) {\n if (x.size() != y.size() || x.empty()) {\n throw FinancialDataException(\"Invalid data for linear regression\");\n }\n \n double n = static_cast<double>(x.size());\n double sum_x = std::accumulate(x.begin(), x.end(), 0.0);\n double sum_y = std::accumulate(y.begin(), y.end(), 0.0);\n \n double sum_xy = 0.0;\n double sum_xx = 0.0;\n \n for (size_t i = 0; i < x.size(); ++i) {\n sum_xy += x[i] * y[i];\n sum_xx += x[i] * x[i];\n }\n \n double slope = (n * sum_xy - sum_x * sum_y) / (n * sum_xx - sum_x * sum_x);\n double intercept = (sum_y - slope * sum_x) / n;\n \n return {slope, intercept};\n }\n \n static double calculateCorrelation(\n const std::vector<double>& x, const std::vector<double>& y) {\n if (x.size() != y.size() || x.size() < 2) {\n throw FinancialDataException(\"Invalid data for correlation calculation\");\n }\n \n double n = static_cast<double>(x.size());\n double sum_x = std::accumulate(x.begin(), x.end(), 0.0);\n double sum_y = std::accumulate(y.begin(), y.end(), 0.0);\n \n double sum_xy = 0.0;\n double sum_xx = 0.0;\n double sum_yy = 0.0;\n \n for (size_t i = 0; i < x.size(); ++i) {\n sum_xy += x[i] * y[i];\n sum_xx += x[i] * x[i];\n sum_yy += y[i] * y[i];\n }\n \n double numerator = n * sum_xy - sum_x * sum_y;\n double denominator = std::sqrt((n * sum_xx - sum_x * sum_x) * (n * sum_yy - sum_y * sum_y));\n \n return numerator / denominator;\n }\n};\n\n// Logger with template metaprogramming\nenum class LogLevel {\n DEBUG,\n INFO,\n WARNING,\n ERROR\n};\n\ntemplate<LogLevel level>\nclass Logger {\nprivate:\n static inline std::mutex logMutex;\n static inline std::ofstream logFile;\n \n static std::string levelToString() {\n if constexpr (level == LogLevel::DEBUG)\n return \"DEBUG\";\n else if constexpr (level == LogLevel::INFO)\n return \"INFO\";\n else if constexpr (level == LogLevel::WARNING)\n return \"WARNING\";\n else if constexpr (level == LogLevel::ERROR)\n return \"ERROR\";\n else\n return \"UNKNOWN\";\n }\n\npublic:\n static void initialize(const std::string& filename) {\n std::lock_guard<std::mutex> lock(logMutex);\n logFile.open(filename, std::ios::app);\n }\n \n template<typename... Args>\n static void log(const std::string& format, Args&&... args) {\n if (!logFile.is_open()) {\n return;\n }\n \n std::lock_guard<std::mutex> lock(logMutex);\n \n auto now = std::chrono::system_clock::now();\n auto now_time_t = std::chrono::system_clock::to_time_t(now);\n auto now_tm = std::localtime(&now_time_t);\n \n char time_buffer[80];\n std::strftime(time_buffer, sizeof(time_buffer), \"%Y-%m-NaN %H:%M:%S\", now_tm);\n \n logFile << \"[\" << time_buffer << \"][\" << levelToString() << \"]: \";\n \n if constexpr (sizeof...(args) == 0) {\n logFile << format;\n } else {\n // This is a simplified implementation; a real logger would use something\n // like fmt::format or a custom formatter\n std::ostringstream message;\n message << format;\n ((message << \" \" << std::forward<Args>(args)), ...);\n logFile << message.str();\n }\n \n logFile << std::endl;\n }\n \n static void close() {\n std::lock_guard<std::mutex> lock(logMutex);\n if (logFile.is_open()) {\n logFile.close();\n }\n }\n};\n\n// Example usage function\nvoid runExample() {\n // Initialize logger\n Logger<LogLevel::INFO>::initialize(\"financial_analyzer.log\");\n Logger<LogLevel::INFO>::log(\"Financial analyzer starting\");\n \n // Create market data instance\n MarketData marketData;\n \n // Add some financial instruments\n marketData.addInstrument(\"AAPL\", 150.0);\n marketData.addInstrument(\"MSFT\", 250.0);\n marketData.addInstrument(\"GOOGL\", 2000.0);\n marketData.addInstrument(\"AMZN\", 3000.0);\n \n // Create instruments\n FinancialInstrument apple(\"AAPL\", \"Apple Inc.\");\n FinancialInstrument microsoft(\"MSFT\", \"Microsoft Corporation\");\n \n apple.setBeta(1.2);\n microsoft.setBeta(0.9);\n \n // Create portfolio\n Portfolio portfolio(\"Tech Portfolio\");\n \n // Execute some transactions\n portfolio.executeTransaction({\"TX001\", \"AAPL\", TradeType::BUY, 10, 150.0});\n portfolio.executeTransaction({\"TX002\", \"MSFT\", TradeType::BUY, 5, 250.0});\n \n // Start market simulation\n marketData.startSimulation();\n \n // Wait for some data to be generated\n std::this_thread::sleep_for(std::chrono::seconds(5));\n \n // Get current prices\n auto applePrice = marketData.getCurrentPrice(\"AAPL\");\n auto microsoftPrice = marketData.getCurrentPrice(\"MSFT\");\n \n if (applePrice && microsoftPrice) {\n Logger<LogLevel::INFO>::log(\"Current prices - AAPL:\", *applePrice, \n \"MSFT:\", *microsoftPrice);\n }\n \n // Get price history\n auto applePriceHistory = marketData.getPriceHistory(\"AAPL\");\n \n // Calculate moving averages\n auto movingAverages = MarketAnalyzer::calculateMovingAverages(applePriceHistory, 3);\n \n Logger<LogLevel::INFO>::log(\"Apple price moving averages calculated\");\n \n // Calculate portfolio value\n std::unordered_map<StockSymbol, Price> currentPrices;\n if (applePrice) currentPrices[\"AAPL\"] = *applePrice;\n if (microsoftPrice) currentPrices[\"MSFT\"] = *microsoftPrice;\n \n double portfolioValue = portfolio.calculateTotalValue(currentPrices);\n Logger<LogLevel::INFO>::log(\"Portfolio value:\", portfolioValue);\n \n // Stop simulation\n marketData.stopSimulation();\n \n // Clean up\n Logger<LogLevel::INFO>::log(\"Financial analyzer shutting down\");\n Logger<LogLevel::INFO>::close();\n}\n\n} // namespace financial_analyzer\n\n// Main function\nint main() {\n try {\n financial_analyzer::runExample();\n } catch (const std::exception& e) {\n std::cerr << \"Error: \" << e.what() << std::endl;\n return 1;\n }\n \n return 0;\n}","lang":"cpp"}},"jsonrpc":"2.0","id":5}