Python tool for Amazon sales rank trend analysis

Building a Python Tool for Amazon Sales Rank Trend Analysis

By John Smith | July 13, 2025

Building a Python Tool for Amazon Sales Rank Trend Analysis

In the competitive world of Amazon e-commerce, understanding product performance is critical. Sales rank is a key indicator, and tracking its trends can provide valuable insights for competitive analysis, inventory management, and overall market research. This blog post will guide you through building a Python tool to analyze Amazon sales rank trends using the SellerMagnet API, a robust and enterprise-grade solution for accessing Amazon data.

Why Sales Rank Trend Analysis Matters

Analyzing sales rank trends allows businesses to:

  • Identify top-performing products: Spot products with consistently high sales ranks.
  • Monitor competitor performance: Track changes in competitors' sales ranks to understand their strategies.
  • Optimize inventory: Predict demand fluctuations and adjust inventory levels accordingly.
  • Assess market trends: Identify emerging trends and capitalize on new opportunities.

Introducing the SellerMagnet API

The SellerMagnet API provides a comprehensive solution for accessing real-time and historical Amazon data. With its enterprise-grade infrastructure, you can rely on its stability and accuracy for critical business decisions. It offers various endpoints, including the Amazon Product Statistics endpoint, which is crucial for sales rank trend analysis.

Setting Up Your Python Environment

Before diving into the code, ensure you have Python installed along with the necessary libraries. We'll primarily use the requests library to interact with the SellerMagnet API.

pip install requests

Fetching Sales Rank Data with the SellerMagnet API

The Amazon Product Statistics endpoint allows you to retrieve detailed statistics for a specific Amazon product, including its sales rank history. Here’s how you can use it:

API Endpoint:

/amazon-product-statistics

Method:

GET

Parameters:

  • asin (required): The Amazon Standard Identification Number (ASIN) of the product.
  • marketplaceId (required): The Marketplace ID (e.g., "A1PA6795UKMFR9" for Amazon.de). You can use Get Amazon Marketplaces endpoint to find marketplaces.
  • api_key (required): Your SellerMagnet API key.
  • graphs (optional): Set to true to generate visually graphs for history data

Python Code Example:


import requests

api_key = "YOUR_API_KEY"
asin = "B08N5WRWNW"
marketplace_id = "A1PA6795UKMFR9"  # Amazon.de

url = f"https://sellermagnet-api.com/amazon-product-statistics?asin={asin}&marketplaceId={marketplace_id}&api_key={api_key}"

try:
    response = requests.get(url)
    response.raise_for_status()  # Raise HTTPError for bad responses (4xx or 5xx)
    data = response.json()

    if data['success']:
        sales_rank_history = data['data']['salesRankHistory']
        print("Sales Rank History:")
        for timestamp, rank in sales_rank_history:
            print(f"  {timestamp}: {rank}")
    else:
        print("Error fetching data:", data.get('errors', 'Unknown error'))

except requests.exceptions.RequestException as e:
    print(f"Request failed: {e}")
except (KeyError, TypeError) as e:
    print(f"Error parsing data: {e}")

Example Response:


{
  "success": true,
  "data": {
    "asin": "B0CLTBHXWQ",
    "amazonPrice": 44999,
    "bestSellerRank": 15,
    "buyBoxPrice": 41800,
    "buyBoxFulfillment": "FBM",
    "buyBoxSellerIdHistory": [
      [
        "2025-06-14 17:08:00",
        "A2I59UVTUWUFH0"
      ]
    ],
    "salesRankHistory": [
      [
        "2025-06-14T01:58:00",
        15
      ],
      [
        "2025-06-13T23:58:00",
        14
      ],
      [
        "2025-06-13T21:58:00",
        14
      ]
    ],
    "trackingSince": "2023-12-30"
  }
}

Analyzing the Data

Once you retrieve the sales rank history, you can analyze the data to identify trends. Here are a few basic analysis techniques:

  • Calculate Moving Averages: Smooth out short-term fluctuations to reveal underlying trends.
  • Identify Peaks and Valleys: Pinpoint significant changes in sales rank.
  • Visualize the Data: Use libraries like matplotlib or seaborn to create charts and graphs.

Calculating Moving Averages Example:


import pandas as pd
import requests

api_key = "YOUR_API_KEY"
asin = "B08N5WRWNW"
marketplace_id = "A1PA6795UKMFR9"  # Amazon.de

url = f"https://sellermagnet-api.com/amazon-product-statistics?asin={asin}&marketplaceId={marketplace_id}&api_key={api_key}"

response = requests.get(url)
data = response.json()

sales_rank_history = data['data']['salesRankHistory']

# Convert the data to a Pandas DataFrame for easier analysis
df = pd.DataFrame(sales_rank_history, columns=['Timestamp', 'SalesRank'])
df['Timestamp'] = pd.to_datetime(df['Timestamp'])
df['SalesRank'] = pd.to_numeric(df['SalesRank'])
df.set_index('Timestamp', inplace=True)

# Calculate a 7-day moving average
ddf['MovingAverage'] = df['SalesRank'].rolling(window=7).mean()

print(df.tail())

Visualizing Sales Rank Trends

Visualizing your sales rank data will make it easier to spot trends and anomalies. You can use libraries such as matplotlib and seaborn to create informative charts.

Visualization Example:


import matplotlib.pyplot as plt
import pandas as pd
import requests

api_key = "YOUR_API_KEY"
asin = "B08N5WRWNW"
marketplace_id = "A1PA6795UKMFR9"  # Amazon.de

url = f"https://sellermagnet-api.com/amazon-product-statistics?asin={asin}&marketplaceId={marketplace_id}&api_key={api_key}&graphs=true"

response = requests.get(url)
data = response.json()


if 'data' in data and 'graphs' in data['data'] and data['data']['graphs']:
    rank_trend_data = data['data']['graphs']['rankTrend']

    # Convert the rank trend data to a Pandas DataFrame for easier plotting
    df = pd.DataFrame(rank_trend_data)
    df['timestamp'] = pd.to_datetime(df['timestamp'])
    df.set_index('timestamp', inplace=True)

    # Plotting the sales rank trend
    plt.figure(figsize=(12, 6))
    plt.plot(df['rank'], label='Sales Rank')
    plt.xlabel('Time')
    plt.ylabel('Sales Rank')
    plt.title('Sales Rank Trend Over Time')
    plt.legend()
    plt.grid(True)
    plt.gca().invert_yaxis()  # Invert the y-axis to show better ranks on top

    plt.tight_layout()
    plt.show()
else:
    print("No graph data available in the response.")

Advanced Use Cases and API Integrations

The SellerMagnet API offers several other endpoints that can complement your sales rank analysis:

Integrate these endpoints to build a holistic view of product and market dynamics. For instance, combine sales rank data with pricing information to identify optimal pricing strategies.

Enhance Your Tool with DataPipeline

SellerMagnet's DataPipeline allows you to automate the data collection process. Schedule regular API calls to gather sales rank data and store it in a database for long-term analysis. This eliminates manual data fetching and ensures you always have the latest information at your fingertips.

Conclusion

Building a Python tool for Amazon sales rank trend analysis empowers businesses to make data-driven decisions, optimize their strategies, and stay ahead of the competition. By leveraging the SellerMagnet API, you can access accurate, reliable, and real-time data, enabling you to unlock valuable insights and drive growth. Start your journey today with our free trial!

Don't forget to check out our Documentation and Code Examples for more inspiration on how to use SellerMagnet's API. For any questions, please feel free to Contact our expert team.

Back to Blog