---
title: "Build a Data Analysis Agent"
description: "Learn how to create a coding assistant that processes CSV, JSON, and analyzes data with the Autohand Code Agent SDK. Available in TypeScript, Python, Java, Go, Swift, and Rust."
slug: "agent-sdk/tutorials/300-data-analysis-agent"
sidebar:
  label: "Data analysis agent"
seo:
  title: "Data Analysis Agent | Autohand Code"
  description: "Build a data analysis coding assistant with the Autohand Code Agent SDK. Learn how to create agents that process CSV, JSON, and analyze data automatically."
---

In this tutorial, you'll build a data analysis coding assistant that can read data files, perform calculations, generate visualizations, and provide insights. This demonstrates how to use the Agent SDK for data processing tasks.

:::note
**Prerequisites:**

- Completed [Code Reviewer Agent](/agent-sdk/tutorials/100-code-reviewer-agent)
- Node.js 16+ (for TypeScript), Python 3.10+ (for Python), Java 11+ (for Java), Go 1.16+ (for Go), Swift 5.5+ (for Swift), or Rust 1.60+ (for Rust)
- SDK installed for your chosen language
- API key from your LLM provider (set as `AUTOHAND_API_KEY`)
:::

## What You'll Build

A data analysis coding assistant that:

- Reads CSV and JSON data files
- Calculates statistics (mean, median, standard deviation)
- Filters and transforms data
- Generates summary reports
- Creates visualization scripts

## Step 1: Create Sample Data

Create a sample CSV file with sales data in your chosen language:

```ts title="TypeScript"
import * as fs from "fs";
import * as path from "path";

function createSampleData(tmpdir: string): void {
  const csvContent = `date,product,sales,revenue
2024-01-01,Product A,100,1000
2024-01-02,Product B,150,1500
2024-01-03,Product A,200,2000
2024-01-04,Product C,120,1200
2024-01-05,Product B,180,1800`;

  fs.writeFileSync(path.join(tmpdir, "sales_data.csv"), csvContent);
}
```

```python title="Python"
from pathlib import Path

def create_sample_data(tmpdir: str) -> None:
    csv_content = """date,product,sales,revenue
2024-01-01,Product A,100,1000
2024-01-02,Product B,150,1500
2024-01-03,Product A,200,2000
2024-01-04,Product C,120,1200
2024-01-05,Product B,180,1800"""

    Path(tmpdir, "sales_data.csv").write_text(csv_content)
```

```java title="Java"
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

void createSampleData(String tmpdir) throws IOException {
    String csvContent = "date,product,sales,revenue
" +
        "2024-01-01,Product A,100,1000
" +
        "2024-01-02,Product B,150,1500
" +
        "2024-01-03,Product A,200,2000
" +
        "2024-01-04,Product C,120,1200
" +
        "2024-01-05,Product B,180,1800";

    Path file = Paths.get(tmpdir, "sales_data.csv");
    Files.writeString(file, csvContent);
}
```

```go title="Go"
package main

import (
    "os"
    "path/filepath"
)

func createSampleData(tmpdir string) error {
    csvContent := `date,product,sales,revenue
2024-01-01,Product A,100,1000
2024-01-02,Product B,150,1500
2024-01-03,Product A,200,2000
2024-01-04,Product C,120,1200
2024-01-05,Product B,180,1800`

    return os.WriteFile(filepath.Join(tmpdir, "sales_data.csv"), []byte(csvContent), 0644)
}
```

```swift title="Swift"
import Foundation

func createSampleData(tmpdir: String) throws {
    let csvContent = """
date,product,sales,revenue
2024-01-01,Product A,100,1000
2024-01-02,Product B,150,1500
2024-01-03,Product A,200,2000
2024-01-04,Product C,120,1200
2024-01-05,Product B,180,1800
"""
    
    let file = (tmpdir as NSString).appendingPathComponent("sales_data.csv")
    try csvContent.write(toFile: file, atomically: true, encoding: .utf8)
}
```

```rust title="Rust"
use std::fs;
use std::path::Path;

fn create_sample_data(tmpdir: &str) -> std::io::Result<()> {
    let csv_content = r#"date,product,sales,revenue
2024-01-01,Product A,100,1000
2024-01-02,Product B,150,1500
2024-01-03,Product A,200,2000
2024-01-04,Product C,120,1200
2024-01-05,Product B,180,1800"#;

    fs::write(Path::new(tmpdir).join("sales_data.csv"), csv_content)?;
    Ok(())
}
```

## Step 2: Create Data Analysis Agent

Create an agent with data analysis capabilities in your chosen language:

```ts title="TypeScript"
import { Agent, Runner } from "@autohandai/agent-sdk";
import { OpenRouterProvider } from "@autohandai/agent-sdk";

const dataAnalyst = new Agent(
  "Data Analyst",
  "You are a data analysis expert. Read CSV files, calculate statistics (mean, median, standard deviation), filter data, and provide insights. Create summary reports and Python scripts for visualizations using matplotlib or plotly.",
  ["read_file", "write_file", "bash"],
  10
);

dataAnalyst.setProvider(
  new OpenRouterProvider(
    process.env.AUTOHAND_API_KEY!,
    "z-ai/glm-5.2"
  )
);
```

```python title="Python"
from autohand_agent_sdk import Agent, Runner, OpenRouterProvider

data_analyst = Agent(
    name="Data Analyst",
    instructions="You are a data analysis expert. Read CSV files, calculate statistics (mean, median, standard deviation), filter data, and provide insights. Create summary reports and Python scripts for visualizations using matplotlib or plotly.",
    tools=["read_file", "write_file", "bash"],
    max_turns=10
)

data_analyst.set_provider(OpenRouterProvider(
    api_key=os.getenv("AUTOHAND_API_KEY"),
    model="z-ai/glm-5.2"
))
```

```java title="Java"
import ai.autohand.agent.sdk.*;
import ai.autohand.agent.sdk.providers.*;

Agent dataAnalyst = new Agent(
    "Data Analyst",
    "You are a data analysis expert. Read CSV files, calculate statistics (mean, median, standard deviation), filter data, and provide insights. Create summary reports and Python scripts for visualizations using matplotlib or plotly.",
    DefaultToolRegistry.getTools("read_file", "write_file", "bash"),
    10
);

dataAnalyst.setProvider(new OpenRouterProvider(
    System.getenv("AUTOHAND_API_KEY"),
    "z-ai/glm-5.2"
));
```

```go title="Go"
package main

import (
    "os"
    "github.com/autohandai/agentsdk-go/pkg/autohand"
)

dataAnalyst := autohand.Agent{
    Name:         "Data Analyst",
    Instructions: "You are a data analysis expert. Read CSV files, calculate statistics (mean, median, standard deviation), filter data, and provide insights. Create summary reports and Python scripts for visualizations using matplotlib or plotly.",
    Tools:        []autohand.Tool{autohand.ReadFile, autohand.WriteFile, autohand.Bash},
    MaxTurns:     10,
}

provider := autohand.NewOpenRouterProvider(
    os.Getenv("AUTOHAND_API_KEY"),
    "z-ai/glm-5.2",
)
dataAnalyst.Provider = &provider
```

```swift title="Swift"
import AutohandAgentSDK

let dataAnalyst = Agent(
    name: "Data Analyst",
    instructions: "You are a data analysis expert. Read CSV files, calculate statistics (mean, median, standard deviation), filter data, and provide insights. Create summary reports and Python scripts for visualizations using matplotlib or plotly.",
    tools: [.readFile, .writeFile, .bash],
    maxTurns: 10
)

dataAnalyst.provider = try OpenRouterProvider(
    apiKey: ProcessInfo.processInfo.environment["AUTOHAND_API_KEY"] ?? "your-api-key",
    model: "z-ai/glm-5.2"
)
```

```rust title="Rust"
use autohand_agents::{AgentBuilder, Runner};
use autohand_agents::providers::ProviderFactory;
use autohand_agents::config::ConfigLoader;

let mut data_analyst = AgentBuilder::new()
    .name("Data Analyst")
    .instructions("You are a data analysis expert. Read CSV files, calculate statistics (mean, median, standard deviation), filter data, and provide insights. Create summary reports and Python scripts for visualizations using matplotlib or plotly.")
    .tools(vec![Tool::ReadFile, Tool::WriteFile, Tool::Bash])
    .max_turns(10)
    .build()?;

let config = ConfigLoader::from_env()?;
let provider = ProviderFactory::from_env(&config.provider)?;
data_analyst.set_provider(provider);
```

## Step 3: Run Analysis

Run the data analysis agent on your sample data in your chosen language:

```ts title="TypeScript"
const result = await Runner.run(
  dataAnalyst,
  "Read the sales_data.csv file. Calculate the total sales, average revenue, and identify the best-selling product. Create a summary report and a Python script to visualize the data."
);

console.log(result.finalOutput);
```

```python title="Python"
result = Runner.run(
    data_analyst,
    "Read the sales_data.csv file. Calculate the total sales, average revenue, and identify the best-selling product. Create a summary report and a Python script to visualize the data."
)

print(result.final_output)
```

```java title="Java"
String result = Runner.run(
    dataAnalyst,
    "Read the sales_data.csv file. Calculate the total sales, average revenue, and identify the best-selling product. Create a summary report and a Python script to visualize the data."
);

System.out.println(result);
```

```go title="Go"
result, err := autohand.Runner.Run(&dataAnalyst, "Read the sales_data.csv file. Calculate the total sales, average revenue, and identify the best-selling product. Create a summary report and a Python script to visualize the data.")
if err != nil {
    log.Fatal(err)
}
fmt.Println(result)
```

```swift title="Swift"
let result = try Runner.run(
    dataAnalyst,
    "Read the sales_data.csv file. Calculate the total sales, average revenue, and identify the best-selling product. Create a summary report and a Python script to visualize the data."
)

print(result)
```

```rust title="Rust"
let result = Runner::run(&data_analyst, "Read the sales_data.csv file. Calculate the total sales, average revenue, and identify the best-selling product. Create a summary report and a Python script to visualize the data.").await?;
println!("{}", result.final_output);
```

## Key Concepts

**File Processing**

Using READ\_FILE to read CSV and JSON data files for analysis.

**Statistical Analysis**

The agent calculates statistics and provides data insights automatically.

**Report Generation**

Using WRITE\_FILE to create summary reports and analysis outputs.

**Visualization Scripts**

The agent can generate Python scripts for data visualization.

## Complete Example

Here's the complete example with cleanup:

```ts
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import { Agent, Runner } from "@autohandai/agent-sdk";

async function main() {
  const tmpdir = fs.mkdtempSync(path.join(os.tmpdir(), "data-agent-example-"));
  const oldCwd = process.cwd();
  try {
    fs.writeFileSync(path.join(tmpdir, "sales_data.csv"), "date,product,revenue\n2024-01-01,A,1000\n2024-01-02,B,1500\n");
    const agent = new Agent("Data Analyst", "Analyze CSV files and write concise reports.", ["read_file", "write_file", "bash"], 10);
    process.chdir(tmpdir);
    const result = await Runner.run(agent, "Read sales_data.csv and write a short revenue summary.");
    console.log(result.finalOutput);
  } finally {
    process.chdir(oldCwd);
    fs.rmSync(tmpdir, { recursive: true, force: true });
  }
}

main();
```

## Real-World Applications

This pattern can be applied to:

- **Business intelligence:** Analyze sales, revenue, and customer data
- **Log analysis:** Parse and analyze server logs for insights
- **Financial reporting:** Generate financial summaries and reports
- **Scientific data:** Process experimental data and generate plots
- **Market research:** Analyze survey data and customer feedback

## Next Steps

**[📁 View the Example](https://github.com/autohandai/agent-sdk-typescript/tree/main/examples)**

See the complete example in the SDK repositories.

**[📊 Documentation Generator](/agent-sdk/tutorials/400-code-modernization)**

Learn how to build agents that generate documentation from code.

**[📚 Explore More](/agent-sdk/overview)**

Check out all examples in the SDK repositories.
