Hands-On Guide: Exporting Python Market Data to CSV Files for Analysis
When running automated market scanners or price trackers, viewing terminal output in real time is helpful, but preserving that data for historical review, spreadsheet analysis, or offline testing is even better. Python's built-in CSV module allows you to save polled price data directly to structured files on your mobile device.
In this hands-on tutorial, we will build a lightweight Python script that logs polled market metrics into a local CSV spreadsheet.
---------------------------------------------------
1. Why Store Data in CSV Format?
Comma-Separated Values (CSV) is a universal data format. By saving your script's output to a CSV file:
• You can transfer the log files easily to a desktop spreadsheet program (like Microsoft Excel or Google Sheets) for charting.
• You maintain an offline historical record of market movements captured during your mobile scanner runs.
• It requires zero external database setup, making it lightweight enough to run smoothly in Termux.
---------------------------------------------------
2. Complete Python CSV Logger Script
Open your terminal or development environment, create a new file named csv_logger.py, and paste the following code:
import time
import requests
import csv
import os
# Configuration
SYMBOL = "VOLATILITY_10"
CSV_FILENAME = "market_data_log.csv"
SCAN_INTERVAL = 30 # Seconds
def initialize_csv():
"""Creates the CSV file and writes headers if it doesn't already exist."""
if not os.path.exists(CSV_FILENAME):
with open(CSV_FILENAME, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["Timestamp", "Symbol", "Price"])
print(f"Initialized new CSV log file: {CSV_FILENAME}")
def log_to_csv(timestamp, symbol, price):
"""Appends a new price entry to the CSV log file."""
try:
with open(CSV_FILENAME, mode='a', newline='') as file:
writer = csv.writer(file)
writer.writerow([timestamp, symbol, price])
print(f"Logged to CSV: {timestamp} | {symbol} | {price}")
except Exception as e:
print(f"Error writing to CSV: {e}")
def fetch_price():
"""Simulated price retrieval function."""
url = f"https://api.example.com/v1/ticker?symbol={SYMBOL}"
try:
response = requests.get(url, timeout=5)
if response.status_code == 200:
data = response.json()
return float(data.get("price", 0.0))
except Exception as e:
print(f"Network error: {e}")
return None
def main():
print(f"--- Starting CSV Market Logger for {SYMBOL} ---")
initialize_csv()
while True:
current_price = fetch_price()
if current_price:
timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
log_to_csv(timestamp, SYMBOL, current_price)
time.sleep(SCAN_INTERVAL)
if __name__ == "__main__":
main()
---------------------------------------------------
3. Running and Locating Your CSV Files in Termux
1. Save your file in nano (Ctrl + O, Enter, Ctrl + X).
2. Execute your logger script:
python csv_logger.py
3. To view or export your collected data files later from Termux, you can check your working directory using the `ls` command or copy files to your phone's shared storage.
---------------------------------------------------
Final Thoughts
Adding CSV export functionality bridges the gap between simple script automation and actionable data collection. You can accumulate clean datasets directly from your mobile device.
Stay tuned for our next guide as we power toward our content milestone!
Comments
Post a Comment