投资收益计算器 | KMP鸿蒙财富增长智能助手
本文介绍了一个基于Kotlin Multiplatform框架开发的跨平台投资收益计算器。该工具支持多种投资计算方式,包括单利、复利、定期定额投资等核心功能,并提供收益分析、风险评估和投资对比等增值功能。通过KMP技术,计算器可在Android、iOS、Web和OpenHarmony等多平台运行,实现代码复用。文档详细阐述了投资基础概念、核心计算方法、Kotlin实现代码以及ArkTS调用示例,帮

目录
概述
在现代社会,投资理财已成为个人财富管理的重要组成部分。无论是股票投资、基金定投、还是房产投资,准确计算投资收益对于制定合理的投资策略至关重要。投资收益计算器是帮助投资者理解投资回报、评估投资效果、优化投资组合的重要工具。本文档介绍如何在 Kotlin Multiplatform (KMP) 框架下,结合 OpenHarmony 鸿蒙操作系统,实现一个功能完整的投资收益计算器。
投资收益计算器是一个综合性的财务分析工具,它不仅能够计算各种投资方式的收益,还能够进行风险评估、生成投资报告、提供理财建议。通过KMP框架的跨端能力,这个工具可以在Android、iOS、Web和OpenHarmony等多个平台上运行,为投资者提供了一个强大的投资决策辅助工具。
投资理财的重要性
投资理财在现代生活中的重要性日益凸显:
- 财富增值:通过投资,可以让闲置资金产生收益,实现财富增值。
- 抵抗通胀:投资收益可以抵消通货膨胀对购买力的侵蚀。
- 实现目标:通过合理的投资规划,可以实现购房、教育、养老等人生目标。
- 风险管理:通过分散投资,可以降低投资风险。
- 财务自由:通过长期投资,可以逐步实现财务自由。
工具的核心价值
投资收益计算器提供以下价值:
- 多种计算方式:支持一次性投资、定期定额投资、复利计算等
- 详细的收益分析:计算总收益、年化收益率、投资回报率等
- 风险评估:评估投资的风险程度,提供风险提示
- 投资对比:支持不同投资方案的对比,帮助选择最优方案
- 可视化展示:以图表形式展示投资收益变化趋势
- 跨平台支持:一份代码可在多个平台运行,提高开发效率
投资理财基础
核心概念
本金(Principal):投资者投入的初始资金。
收益(Return):投资产生的利润,等于最终价值减去本金。
收益率(Return Rate):收益与本金的比例,通常用百分比表示。
年化收益率(Annual Return Rate):按年计算的平均收益率。
复利(Compound Interest):利息再投资产生的利息,即"利生利"。
风险(Risk):投资可能产生损失的可能性。
常见的投资方式
一次性投资:一次性投入全部资金,然后等待收益。
定期定额投资(DCA):定期投入固定金额,分散投资风险。
复利投资:将收益再投资,产生复利效应。
分期投资:分多次投入资金,逐步建立投资组合。
重要的计算公式
单利公式:最终价值 = 本金 × (1 + 利率 × 时间)
复利公式:最终价值 = 本金 × (1 + 利率)^时间
定期定额投资公式:最终价值 = 定期投入金额 × [((1 + 利率)^时间 - 1) / 利率]
核心计算方法
1. 单利计算
计算不考虑复利效应的投资收益。适用于某些债券、存款等产品。
2. 复利计算
计算考虑复利效应的投资收益。适用于股票、基金等长期投资。
3. 定期定额计算
计算定期投入固定金额的投资收益。适用于基金定投等投资方式。
4. 加权平均收益率
计算多个投资项目的综合收益率。
5. 风险调整收益
考虑风险因素的收益计算。
6. 投资对比分析
对比不同投资方案的收益和风险。
Kotlin 源代码
// InvestmentCalculator.kt
import java.time.LocalDateTime
import kotlin.math.pow
data class Investment(
val id: String,
val name: String,
val principal: Double,
val annualRate: Double,
val years: Int,
val investmentType: String,
val riskLevel: String,
val timestamp: String
)
data class InvestmentResult(
val investmentId: String,
val investmentName: String,
val principal: Double,
val finalValue: Double,
val totalReturn: Double,
val returnRate: Double,
val annualizedReturn: Double,
val yearlyBreakdown: List<Pair<Int, Double>>,
val timestamp: String
)
data class PortfolioMetrics(
val totalInvestment: Double,
val totalValue: Double,
val totalReturn: Double,
val averageReturnRate: Double,
val weightedAnnualReturn: Double,
val riskScore: Double,
val diversificationScore: Double
)
data class ComparisonResult(
val scenario1: InvestmentResult,
val scenario2: InvestmentResult,
val betterScenario: String,
val differenceFactor: Double
)
class InvestmentCalculator {
private val investments = mutableListOf<Investment>()
private val results = mutableListOf<InvestmentResult>()
private var investmentIdCounter = 0
// 计算单利收益
fun calculateSimpleInterest(
name: String,
principal: Double,
annualRate: Double,
years: Int,
riskLevel: String = "MEDIUM"
): InvestmentResult {
val id = "INV${++investmentIdCounter}"
val investment = Investment(
id = id,
name = name,
principal = principal,
annualRate = annualRate,
years = years,
investmentType = "SIMPLE_INTEREST",
riskLevel = riskLevel,
timestamp = LocalDateTime.now().toString()
)
investments.add(investment)
// 单利计算:最终价值 = 本金 × (1 + 利率 × 时间)
val finalValue = principal * (1 + annualRate * years)
val totalReturn = finalValue - principal
val returnRate = (totalReturn / principal) * 100
val annualizedReturn = returnRate / years
val yearlyBreakdown = mutableListOf<Pair<Int, Double>>()
for (year in 1..years) {
val yearValue = principal * (1 + annualRate * year)
yearlyBreakdown.add(Pair(year, yearValue))
}
val result = InvestmentResult(
investmentId = id,
investmentName = name,
principal = principal,
finalValue = finalValue,
totalReturn = totalReturn,
returnRate = returnRate,
annualizedReturn = annualizedReturn,
yearlyBreakdown = yearlyBreakdown,
timestamp = LocalDateTime.now().toString()
)
results.add(result)
return result
}
// 计算复利收益
fun calculateCompoundInterest(
name: String,
principal: Double,
annualRate: Double,
years: Int,
compoundFrequency: Int = 1,
riskLevel: String = "MEDIUM"
): InvestmentResult {
val id = "INV${++investmentIdCounter}"
val investment = Investment(
id = id,
name = name,
principal = principal,
annualRate = annualRate,
years = years,
investmentType = "COMPOUND_INTEREST",
riskLevel = riskLevel,
timestamp = LocalDateTime.now().toString()
)
investments.add(investment)
// 复利计算:最终价值 = 本金 × (1 + 利率/复利频率)^(复利频率×时间)
val ratePerPeriod = annualRate / compoundFrequency
val periods = compoundFrequency * years
val finalValue = principal * (1 + ratePerPeriod).pow(periods)
val totalReturn = finalValue - principal
val returnRate = (totalReturn / principal) * 100
val annualizedReturn = returnRate / years
val yearlyBreakdown = mutableListOf<Pair<Int, Double>>()
for (year in 1..years) {
val yearPeriods = compoundFrequency * year
val yearValue = principal * (1 + ratePerPeriod).pow(yearPeriods)
yearlyBreakdown.add(Pair(year, yearValue))
}
val result = InvestmentResult(
investmentId = id,
investmentName = name,
principal = principal,
finalValue = finalValue,
totalReturn = totalReturn,
returnRate = returnRate,
annualizedReturn = annualizedReturn,
yearlyBreakdown = yearlyBreakdown,
timestamp = LocalDateTime.now().toString()
)
results.add(result)
return result
}
// 计算定期定额投资
fun calculateRegularInvestment(
name: String,
monthlyAmount: Double,
annualRate: Double,
years: Int,
riskLevel: String = "MEDIUM"
): InvestmentResult {
val id = "INV${++investmentIdCounter}"
val totalPrincipal = monthlyAmount * 12 * years
val investment = Investment(
id = id,
name = name,
principal = totalPrincipal,
annualRate = annualRate,
years = years,
investmentType = "REGULAR_INVESTMENT",
riskLevel = riskLevel,
timestamp = LocalDateTime.now().toString()
)
investments.add(investment)
// 定期定额投资计算
val monthlyRate = annualRate / 12
val months = years * 12
// 最终价值 = 月投入 × [((1 + 月利率)^月数 - 1) / 月利率]
val finalValue = if (monthlyRate > 0) {
monthlyAmount * (((1 + monthlyRate).pow(months) - 1) / monthlyRate)
} else {
monthlyAmount * months
}
val totalReturn = finalValue - totalPrincipal
val returnRate = (totalReturn / totalPrincipal) * 100
val annualizedReturn = returnRate / years
val yearlyBreakdown = mutableListOf<Pair<Int, Double>>()
for (year in 1..years) {
val yearMonths = year * 12
val yearValue = if (monthlyRate > 0) {
monthlyAmount * (((1 + monthlyRate).pow(yearMonths) - 1) / monthlyRate)
} else {
monthlyAmount * yearMonths
}
yearlyBreakdown.add(Pair(year, yearValue))
}
val result = InvestmentResult(
investmentId = id,
investmentName = name,
principal = totalPrincipal,
finalValue = finalValue,
totalReturn = totalReturn,
returnRate = returnRate,
annualizedReturn = annualizedReturn,
yearlyBreakdown = yearlyBreakdown,
timestamp = LocalDateTime.now().toString()
)
results.add(result)
return result
}
// 获取投资组合指标
fun getPortfolioMetrics(): PortfolioMetrics {
if (investments.isEmpty()) {
return PortfolioMetrics(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
}
val totalInvestment = investments.sumOf { it.principal }
val totalValue = results.sumOf { it.finalValue }
val totalReturn = totalValue - totalInvestment
val averageReturnRate = if (investments.isNotEmpty()) {
results.map { it.returnRate }.average()
} else {
0.0
}
val weightedAnnualReturn = results.mapIndexed { index, result ->
val weight = investments[index].principal / totalInvestment
result.annualizedReturn * weight
}.sum()
val riskScore = calculateRiskScore()
val diversificationScore = calculateDiversificationScore()
return PortfolioMetrics(
totalInvestment = totalInvestment,
totalValue = totalValue,
totalReturn = totalReturn,
averageReturnRate = averageReturnRate,
weightedAnnualReturn = weightedAnnualReturn,
riskScore = riskScore,
diversificationScore = diversificationScore
)
}
// 计算风险评分
private fun calculateRiskScore(): Double {
val riskWeights = mapOf("LOW" to 1.0, "MEDIUM" to 2.0, "HIGH" to 3.0)
val totalRisk = investments.sumOf { investment ->
val weight = investment.principal / investments.sumOf { it.principal }
val riskValue = riskWeights[investment.riskLevel] ?: 2.0
weight * riskValue
}
return minOf(totalRisk, 3.0)
}
// 计算多样化评分
private fun calculateDiversificationScore(): Double {
if (investments.size <= 1) return 0.0
val typeDistribution = investments
.groupingBy { it.investmentType }
.eachCount()
val diversificationRatio = typeDistribution.size.toDouble() / investments.size
return diversificationRatio * 100
}
// 对比两个投资方案
fun compareInvestments(result1: InvestmentResult, result2: InvestmentResult): ComparisonResult {
val betterScenario = if (result1.finalValue > result2.finalValue) {
result1.investmentName
} else {
result2.investmentName
}
val differenceFactor = maxOf(result1.finalValue, result2.finalValue) /
minOf(result1.finalValue, result2.finalValue)
return ComparisonResult(
scenario1 = result1,
scenario2 = result2,
betterScenario = betterScenario,
differenceFactor = differenceFactor
)
}
// 获取所有投资结果
fun getResults(): List<InvestmentResult> {
return results.toList()
}
// 生成投资报告
fun generateInvestmentReport(): Map<String, Any> {
val metrics = getPortfolioMetrics()
return mapOf(
"timestamp" to LocalDateTime.now().toString(),
"metrics" to metrics,
"investments" to investments.toList(),
"results" to results.toList(),
"recommendations" to generateRecommendations(metrics)
)
}
// 生成建议
private fun generateRecommendations(metrics: PortfolioMetrics): List<String> {
val recommendations = mutableListOf<String>()
if (metrics.riskScore > 2.5) {
recommendations.add("💡 投资组合风险较高,建议增加低风险投资品种")
}
if (metrics.diversificationScore < 50) {
recommendations.add("💡 投资多样化程度不足,建议增加不同类型的投资")
}
if (metrics.weightedAnnualReturn < 5) {
recommendations.add("💡 年化收益率较低,建议考虑提高投资比例或选择更高收益的产品")
}
if (metrics.totalReturn > metrics.totalInvestment * 0.5) {
recommendations.add("💡 投资收益良好,建议继续保持当前投资策略")
}
return recommendations
}
// 清空数据
fun clearData() {
investments.clear()
results.clear()
}
}
fun main() {
val calculator = InvestmentCalculator()
// 计算复利投资
val result1 = calculator.calculateCompoundInterest(
name = "股票基金",
principal = 100000.0,
annualRate = 0.08,
years = 10
)
// 计算定期定额投资
val result2 = calculator.calculateRegularInvestment(
name = "基金定投",
monthlyAmount = 2000.0,
annualRate = 0.07,
years = 10
)
// 获取投资组合指标
val metrics = calculator.getPortfolioMetrics()
println("投资组合指标:")
println("总投资: ${String.format("%.2f", metrics.totalInvestment)}")
println("总价值: ${String.format("%.2f", metrics.totalValue)}")
println("总收益: ${String.format("%.2f", metrics.totalReturn)}")
println("平均收益率: ${String.format("%.2f", metrics.averageReturnRate)}%")
// 对比投资方案
val comparison = calculator.compareInvestments(result1, result2)
println("\n投资对比:")
println("更优方案: ${comparison.betterScenario}")
println("收益差异倍数: ${String.format("%.2f", comparison.differenceFactor)}")
// 生成报告
val report = calculator.generateInvestmentReport()
println("\n投资报告已生成")
}
Kotlin代码说明:这个Kotlin实现提供了完整的投资收益计算功能。InvestmentCalculator 类能够计算单利、复利、定期定额投资等多种投资方式的收益。通过使用数据类和数学计算,代码既简洁又准确。系统支持多维度的投资分析,从单个投资项目的详细收益到整个投资组合的风险评估,为投资者提供了全面的投资决策支持。
JavaScript 编译代码
// InvestmentCalculator.js
class Investment {
constructor(id, name, principal, annualRate, years, investmentType, riskLevel, timestamp) {
this.id = id;
this.name = name;
this.principal = principal;
this.annualRate = annualRate;
this.years = years;
this.investmentType = investmentType;
this.riskLevel = riskLevel;
this.timestamp = timestamp;
}
}
class InvestmentResult {
constructor(investmentId, investmentName, principal, finalValue, totalReturn, returnRate, annualizedReturn, yearlyBreakdown, timestamp) {
this.investmentId = investmentId;
this.investmentName = investmentName;
this.principal = principal;
this.finalValue = finalValue;
this.totalReturn = totalReturn;
this.returnRate = returnRate;
this.annualizedReturn = annualizedReturn;
this.yearlyBreakdown = yearlyBreakdown;
this.timestamp = timestamp;
}
}
class PortfolioMetrics {
constructor(totalInvestment, totalValue, totalReturn, averageReturnRate, weightedAnnualReturn, riskScore, diversificationScore) {
this.totalInvestment = totalInvestment;
this.totalValue = totalValue;
this.totalReturn = totalReturn;
this.averageReturnRate = averageReturnRate;
this.weightedAnnualReturn = weightedAnnualReturn;
this.riskScore = riskScore;
this.diversificationScore = diversificationScore;
}
}
class InvestmentCalculator {
constructor() {
this.investments = [];
this.results = [];
this.investmentIdCounter = 0;
}
calculateSimpleInterest(name, principal, annualRate, years, riskLevel = "MEDIUM") {
const id = `INV${++this.investmentIdCounter}`;
const investment = new Investment(
id, name, principal, annualRate, years, "SIMPLE_INTEREST", riskLevel, new Date().toISOString()
);
this.investments.push(investment);
const finalValue = principal * (1 + annualRate * years);
const totalReturn = finalValue - principal;
const returnRate = (totalReturn / principal) * 100;
const annualizedReturn = returnRate / years;
const yearlyBreakdown = [];
for (let year = 1; year <= years; year++) {
const yearValue = principal * (1 + annualRate * year);
yearlyBreakdown.push([year, yearValue]);
}
const result = new InvestmentResult(
id, name, principal, finalValue, totalReturn, returnRate, annualizedReturn, yearlyBreakdown, new Date().toISOString()
);
this.results.push(result);
return result;
}
calculateCompoundInterest(name, principal, annualRate, years, compoundFrequency = 1, riskLevel = "MEDIUM") {
const id = `INV${++this.investmentIdCounter}`;
const investment = new Investment(
id, name, principal, annualRate, years, "COMPOUND_INTEREST", riskLevel, new Date().toISOString()
);
this.investments.push(investment);
const ratePerPeriod = annualRate / compoundFrequency;
const periods = compoundFrequency * years;
const finalValue = principal * Math.pow(1 + ratePerPeriod, periods);
const totalReturn = finalValue - principal;
const returnRate = (totalReturn / principal) * 100;
const annualizedReturn = returnRate / years;
const yearlyBreakdown = [];
for (let year = 1; year <= years; year++) {
const yearPeriods = compoundFrequency * year;
const yearValue = principal * Math.pow(1 + ratePerPeriod, yearPeriods);
yearlyBreakdown.push([year, yearValue]);
}
const result = new InvestmentResult(
id, name, principal, finalValue, totalReturn, returnRate, annualizedReturn, yearlyBreakdown, new Date().toISOString()
);
this.results.push(result);
return result;
}
calculateRegularInvestment(name, monthlyAmount, annualRate, years, riskLevel = "MEDIUM") {
const id = `INV${++this.investmentIdCounter}`;
const totalPrincipal = monthlyAmount * 12 * years;
const investment = new Investment(
id, name, totalPrincipal, annualRate, years, "REGULAR_INVESTMENT", riskLevel, new Date().toISOString()
);
this.investments.push(investment);
const monthlyRate = annualRate / 12;
const months = years * 12;
const finalValue = monthlyRate > 0
? monthlyAmount * ((Math.pow(1 + monthlyRate, months) - 1) / monthlyRate)
: monthlyAmount * months;
const totalReturn = finalValue - totalPrincipal;
const returnRate = (totalReturn / totalPrincipal) * 100;
const annualizedReturn = returnRate / years;
const yearlyBreakdown = [];
for (let year = 1; year <= years; year++) {
const yearMonths = year * 12;
const yearValue = monthlyRate > 0
? monthlyAmount * ((Math.pow(1 + monthlyRate, yearMonths) - 1) / monthlyRate)
: monthlyAmount * yearMonths;
yearlyBreakdown.push([year, yearValue]);
}
const result = new InvestmentResult(
id, name, totalPrincipal, finalValue, totalReturn, returnRate, annualizedReturn, yearlyBreakdown, new Date().toISOString()
);
this.results.push(result);
return result;
}
getPortfolioMetrics() {
if (this.investments.length === 0) {
return new PortfolioMetrics(0, 0, 0, 0, 0, 0, 0);
}
const totalInvestment = this.investments.reduce((sum, inv) => sum + inv.principal, 0);
const totalValue = this.results.reduce((sum, res) => sum + res.finalValue, 0);
const totalReturn = totalValue - totalInvestment;
const averageReturnRate = this.results.reduce((sum, res) => sum + res.returnRate, 0) / this.results.length;
const weightedAnnualReturn = this.results.reduce((sum, result, index) => {
const weight = this.investments[index].principal / totalInvestment;
return sum + (result.annualizedReturn * weight);
}, 0);
const riskScore = this.calculateRiskScore();
const diversificationScore = this.calculateDiversificationScore();
return new PortfolioMetrics(
totalInvestment, totalValue, totalReturn, averageReturnRate, weightedAnnualReturn, riskScore, diversificationScore
);
}
calculateRiskScore() {
const riskWeights = { "LOW": 1.0, "MEDIUM": 2.0, "HIGH": 3.0 };
const totalPrincipal = this.investments.reduce((sum, inv) => sum + inv.principal, 0);
const totalRisk = this.investments.reduce((sum, investment) => {
const weight = investment.principal / totalPrincipal;
const riskValue = riskWeights[investment.riskLevel] || 2.0;
return sum + (weight * riskValue);
}, 0);
return Math.min(totalRisk, 3.0);
}
calculateDiversificationScore() {
if (this.investments.length <= 1) return 0;
const typeSet = new Set(this.investments.map(inv => inv.investmentType));
const diversificationRatio = typeSet.size / this.investments.length;
return diversificationRatio * 100;
}
compareInvestments(result1, result2) {
const betterScenario = result1.finalValue > result2.finalValue ? result1.investmentName : result2.investmentName;
const differenceFactor = Math.max(result1.finalValue, result2.finalValue) / Math.min(result1.finalValue, result2.finalValue);
return {
scenario1: result1,
scenario2: result2,
betterScenario: betterScenario,
differenceFactor: differenceFactor
};
}
getResults() {
return this.results;
}
generateInvestmentReport() {
const metrics = this.getPortfolioMetrics();
return {
timestamp: new Date().toISOString(),
metrics: metrics,
investments: this.investments,
results: this.results,
recommendations: this.generateRecommendations(metrics)
};
}
generateRecommendations(metrics) {
const recommendations = [];
if (metrics.riskScore > 2.5) {
recommendations.push("💡 投资组合风险较高,建议增加低风险投资品种");
}
if (metrics.diversificationScore < 50) {
recommendations.push("💡 投资多样化程度不足,建议增加不同类型的投资");
}
if (metrics.weightedAnnualReturn < 5) {
recommendations.push("💡 年化收益率较低,建议考虑提高投资比例或选择更高收益的产品");
}
if (metrics.totalReturn > metrics.totalInvestment * 0.5) {
recommendations.push("💡 投资收益良好,建议继续保持当前投资策略");
}
return recommendations;
}
clearData() {
this.investments = [];
this.results = [];
}
}
// 使用示例
const calculator = new InvestmentCalculator();
const result1 = calculator.calculateCompoundInterest("股票基金", 100000, 0.08, 10);
const result2 = calculator.calculateRegularInvestment("基金定投", 2000, 0.07, 10);
const metrics = calculator.getPortfolioMetrics();
console.log("投资组合指标:");
console.log("总投资:", metrics.totalInvestment.toFixed(2));
console.log("总价值:", metrics.totalValue.toFixed(2));
console.log("总收益:", metrics.totalReturn.toFixed(2));
console.log("平均收益率:", metrics.averageReturnRate.toFixed(2), "%");
const comparison = calculator.compareInvestments(result1, result2);
console.log("\n投资对比:");
console.log("更优方案:", comparison.betterScenario);
console.log("收益差异倍数:", comparison.differenceFactor.toFixed(2));
const report = calculator.generateInvestmentReport();
console.log("\n投资报告已生成");
JavaScript代码说明:JavaScript版本是Kotlin代码的直接转译。我们使用ES6的class语法定义各个类,使用数学函数进行计算。整体逻辑和算法与Kotlin版本保持一致,确保跨平台的一致性。JavaScript的灵活性使得代码更加简洁,同时保持了清晰的结构和完整的功能。
ArkTS 调用代码
// InvestmentCalculatorPage.ets
import { InvestmentCalculator } from './InvestmentCalculator';
@Entry
@Component
struct InvestmentCalculatorPage {
@State investmentName: string = '';
@State principal: number = 100000;
@State annualRate: number = 8;
@State years: number = 10;
@State investmentType: string = 'compound';
@State selectedTab: number = 0;
@State results: Array<any> = [];
@State metrics: any = null;
@State comparison: any = null;
@State isLoading: boolean = false;
@State errorMessage: string = '';
@State monthlyAmount: number = 2000;
@State report: any = null;
private calculator: InvestmentCalculator = new InvestmentCalculator();
private investmentTypes = ['compound', 'simple', 'regular'];
calculateInvestment() {
if (!this.investmentName.trim()) {
this.errorMessage = '请输入投资名称';
return;
}
this.isLoading = true;
this.errorMessage = '';
try {
let result;
const rate = this.annualRate / 100;
if (this.investmentType === 'compound') {
result = this.calculator.calculateCompoundInterest(
this.investmentName,
this.principal,
rate,
this.years
);
} else if (this.investmentType === 'simple') {
result = this.calculator.calculateSimpleInterest(
this.investmentName,
this.principal,
rate,
this.years
);
} else {
result = this.calculator.calculateRegularInvestment(
this.investmentName,
this.monthlyAmount,
rate,
this.years
);
}
this.results = this.calculator.getResults();
this.metrics = this.calculator.getPortfolioMetrics();
AlertDialog.show({ message: '投资计算完成' });
} catch (error) {
this.errorMessage = '计算失败: ' + error.message;
} finally {
this.isLoading = false;
}
}
compareInvestments() {
if (this.results.length < 2) {
this.errorMessage = '需要至少两个投资方案进行对比';
return;
}
this.isLoading = true;
try {
this.comparison = this.calculator.compareInvestments(this.results[0], this.results[1]);
} catch (error) {
this.errorMessage = '对比失败: ' + error.message;
} finally {
this.isLoading = false;
}
}
generateReport() {
this.isLoading = true;
try {
this.report = this.calculator.generateInvestmentReport();
} catch (error) {
this.errorMessage = '生成报告失败: ' + error.message;
} finally {
this.isLoading = false;
}
}
formatCurrency(value: number): string {
return '¥' + value.toFixed(2);
}
build() {
Column() {
Text('投资收益计算器')
.fontSize(24)
.fontWeight(FontWeight.Bold)
.margin({ top: 20, bottom: 20 })
Tabs({ barPosition: BarPosition.Start }) {
TabContent() {
Column() {
Text('投资计算').fontSize(14).fontWeight(FontWeight.Bold).margin({ bottom: 15 })
Text('投资名称:').fontSize(12).margin({ bottom: 5 })
TextInput({ placeholder: '股票基金' })
.value(this.investmentName)
.onChange((value: string) => { this.investmentName = value; })
.height(40).padding(10).border({ width: 1, color: '#cccccc' }).margin({ bottom: 15 })
Text('投资类型:').fontSize(12).margin({ bottom: 5 })
Select([
{ value: '复利投资' },
{ value: '单利投资' },
{ value: '定期定额' }
])
.value(this.investmentType === 'compound' ? '复利投资' : (this.investmentType === 'simple' ? '单利投资' : '定期定额'))
.onSelect((index: number, value?: string) => {
this.investmentType = index === 0 ? 'compound' : (index === 1 ? 'simple' : 'regular');
})
.margin({ bottom: 15 })
if (this.investmentType === 'regular') {
Text('月投入金额(元):').fontSize(12).margin({ bottom: 5 })
TextInput({ placeholder: '2000' })
.type(InputType.Number)
.value(this.monthlyAmount.toString())
.onChange((value: string) => { this.monthlyAmount = parseFloat(value) || 2000; })
.height(40).padding(10).border({ width: 1, color: '#cccccc' }).margin({ bottom: 15 })
} else {
Text('本金(元):').fontSize(12).margin({ bottom: 5 })
TextInput({ placeholder: '100000' })
.type(InputType.Number)
.value(this.principal.toString())
.onChange((value: string) => { this.principal = parseFloat(value) || 100000; })
.height(40).padding(10).border({ width: 1, color: '#cccccc' }).margin({ bottom: 15 })
}
Row() {
Column() {
Text('年化收益率(%):').fontSize(12).margin({ bottom: 5 })
TextInput({ placeholder: '8' })
.type(InputType.Number)
.value(this.annualRate.toString())
.onChange((value: string) => { this.annualRate = parseFloat(value) || 8; })
.height(40).padding(10).border({ width: 1, color: '#cccccc' })
}
.flex(1)
Column() {
Text('投资年限(年):').fontSize(12).margin({ bottom: 5 })
TextInput({ placeholder: '10' })
.type(InputType.Number)
.value(this.years.toString())
.onChange((value: string) => { this.years = parseInt(value) || 10; })
.height(40).padding(10).border({ width: 1, color: '#cccccc' })
}
.flex(1)
.margin({ left: 10 })
}
.margin({ bottom: 15 })
Button('计算收益').width('100%').height(40).margin({ bottom: 15 })
.onClick(() => { this.calculateInvestment(); }).enabled(!this.isLoading)
if (this.errorMessage) {
Text(this.errorMessage).fontSize(12).fontColor('#F44336').margin({ bottom: 15 })
}
}
.padding(15)
}
.tabBar('📝 投资计算')
TabContent() {
Column() {
if (this.metrics) {
Text('投资指标').fontSize(16).fontWeight(FontWeight.Bold).margin({ bottom: 15 })
Row() {
Column() {
Text('总投资').fontSize(11).fontColor('#999999')
Text(this.formatCurrency(this.metrics.totalInvestment)).fontSize(16)
.fontWeight(FontWeight.Bold).fontColor('#2196F3').margin({ top: 5 })
}
.flex(1).alignItems(HorizontalAlign.Center).padding(15).backgroundColor('#F5F5F5').borderRadius(5)
Column() {
Text('总价值').fontSize(11).fontColor('#999999')
Text(this.formatCurrency(this.metrics.totalValue)).fontSize(16)
.fontWeight(FontWeight.Bold).fontColor('#4CAF50').margin({ top: 5 })
}
.flex(1).alignItems(HorizontalAlign.Center).padding(15).backgroundColor('#F5F5F5').borderRadius(5)
.margin({ left: 10 })
Column() {
Text('总收益').fontSize(11).fontColor('#999999')
Text(this.formatCurrency(this.metrics.totalReturn)).fontSize(16)
.fontWeight(FontWeight.Bold).fontColor('#FF9800').margin({ top: 5 })
}
.flex(1).alignItems(HorizontalAlign.Center).padding(15).backgroundColor('#F5F5F5').borderRadius(5)
.margin({ left: 10 })
}
.margin({ bottom: 15 })
Column() {
Row() {
Text('平均收益率:').fontSize(12)
Text(`${this.metrics.averageReturnRate.toFixed(2)}%`).fontSize(12)
.fontWeight(FontWeight.Bold).fontColor('#2196F3')
}
.margin({ bottom: 10 })
Row() {
Text('加权年化收益:').fontSize(12)
Text(`${this.metrics.weightedAnnualReturn.toFixed(2)}%`).fontSize(12)
.fontWeight(FontWeight.Bold)
}
.margin({ bottom: 10 })
Row() {
Text('风险评分:').fontSize(12)
Text(this.metrics.riskScore.toFixed(2)).fontSize(12)
.fontWeight(FontWeight.Bold).fontColor('#F44336')
}
}
.padding(10).backgroundColor('#F5F5F5').borderRadius(5)
} else {
Text('请先进行投资计算').fontSize(12).fontColor('#999999')
}
}
.padding(15)
}
.tabBar('📊 投资指标')
TabContent() {
Column() {
Button('对比投资方案').width('100%').height(40).margin({ bottom: 15 })
.onClick(() => { this.compareInvestments(); })
if (this.comparison) {
Text('投资对比').fontSize(16).fontWeight(FontWeight.Bold).margin({ bottom: 15 })
Column() {
Row() {
Text('方案1:').fontSize(12).fontWeight(FontWeight.Bold)
Text(this.comparison.scenario1.investmentName).fontSize(12).flex(1)
Text(this.formatCurrency(this.comparison.scenario1.finalValue)).fontSize(12)
.fontWeight(FontWeight.Bold).fontColor('#2196F3')
}
.padding(10).margin({ bottom: 10 }).backgroundColor('#F5F5F5').borderRadius(5)
Row() {
Text('方案2:').fontSize(12).fontWeight(FontWeight.Bold)
Text(this.comparison.scenario2.investmentName).fontSize(12).flex(1)
Text(this.formatCurrency(this.comparison.scenario2.finalValue)).fontSize(12)
.fontWeight(FontWeight.Bold).fontColor('#4CAF50')
}
.padding(10).margin({ bottom: 10 }).backgroundColor('#F5F5F5').borderRadius(5)
Row() {
Text('更优方案:').fontSize(12).fontWeight(FontWeight.Bold)
Text(this.comparison.betterScenario).fontSize(12).flex(1)
.fontColor('#FF9800').fontWeight(FontWeight.Bold)
}
.padding(10).backgroundColor('#F5F5F5').borderRadius(5)
}
}
}
.padding(15)
}
.tabBar('⚖️ 方案对比')
TabContent() {
Column() {
Button('生成报告').width('100%').height(40).margin({ bottom: 15 })
.onClick(() => { this.generateReport(); })
if (this.report) {
Text('投资报告').fontSize(16).fontWeight(FontWeight.Bold).margin({ bottom: 15 })
if (this.report.recommendations && this.report.recommendations.length > 0) {
Text('优化建议:').fontSize(14).fontWeight(FontWeight.Bold).margin({ bottom: 10 })
Column() {
ForEach(this.report.recommendations, (rec: string, index: number) => {
Row() {
Text('•').fontSize(14).fontWeight(FontWeight.Bold).margin({ right: 10 })
Text(rec).fontSize(11).flex(1)
}
.padding(10).margin({ bottom: 8 }).backgroundColor('#E8F5E9').borderRadius(5)
}, (rec: string, index: number) => index.toString())
}
}
}
}
.padding(15)
}
.tabBar('📈 报告')
}
.width('100%')
.flex(1)
}
.padding(10)
.width('100%')
.height('100%')
}
}
ArkTS代码说明:这个ArkTS实现展示了如何在OpenHarmony应用中集成投资收益计算器。通过使用标签页组件,用户可以在投资计算、查看投资指标、对比投资方案和生成报告之间切换。UI设计直观,提供了良好的用户体验。每个标签页都有不同的功能,用户可以全面地了解投资收益情况和优化建议。
计算指标详解
收益指标
总收益:最终价值减去本金,即投资产生的利润。
收益率:总收益与本金的比例,通常用百分比表示。
年化收益率:按年计算的平均收益率,便于不同期限投资的对比。
加权年化收益:考虑投资金额权重的综合年化收益率。
风险指标
风险评分:基于投资类型和金额的综合风险评估。
多样化评分:投资组合的多样化程度,分散风险的能力。
投资对比指标
收益差异倍数:两个投资方案最终价值的比值。
优劣方案:根据收益确定更优的投资方案。
实战应用
应用场景1:个人理财规划
普通投资者可以使用这个工具规划自己的投资组合,比较不同投资方案的收益,制定合理的投资策略。通过定期定额投资,可以实现长期财富积累。
应用场景2:养老金规划
通过计算不同投资方案的长期收益,可以评估是否能够满足养老需求,提前做好养老金规划。
应用场景3:教育基金规划
为孩子的教育做准备,通过投资收益计算器可以了解需要投入多少资金才能达到教育基金目标。
应用场景4:财务顾问工具
财务顾问可以使用这个工具为客户提供专业的投资建议,帮助客户选择最适合的投资方案。
总结
投资收益计算器是现代个人理财中的重要工具。通过KMP框架和OpenHarmony操作系统的结合,我们可以实现一个功能完整、高效可靠的投资收益计算工具。
这个工具不仅能够计算各种投资方式的收益,还能够进行风险评估、生成投资报告、提供理财建议。通过本文介绍的Kotlin实现、JavaScript编译和ArkTS调用,开发者可以快速构建自己的投资理财系统。
在实际应用中,投资收益计算的价值远不止于此。从个人理财规划到财务顾问工具,从养老金规划到教育基金规划,投资收益计算都发挥着重要的作用。通过持续学习和优化,可以构建更加科学和高效的投资决策系统。
掌握好投资收益计算的方法和工具,对于提升个人财务管理能力和实现财务目标都有重要的帮助。通过这个工具的学习和使用,希望能够帮助投资者更好地理解投资,优化投资策略,实现财务自由。欢迎加入开源鸿蒙跨平台社区:https://openharmonycrossplatform.csdn.net
更多推荐

所有评论(0)