Use Python and ChatGPT to fill the gaps of TradeStation

Merge Equity Curves 2.0

Exporting Strategy Performance XML files that use 15 years of 5-minute bars can be cumbersome.  Using Maestro can be cumbersome too.   I know there are great programs out there that will quickly analyze the XML files and do what we are about to do plus a bunch more.  But if you want to do it yourself, try working with 224,377 KB files.

If you want to do a quick merge of equity curves of different markets or systems use this simple method.   That is if you have Python, MatPlotLib and Pandas installed on your computer.  Installing these are really simple and everybody is doing it.   I created this script with the help of a paid version of ChatGPT.

Using Python et al. to plot combined equity curve.

Steps:

1,)  Create a folder on you C drive:  C:\Data

2.)  Put this code into your strategy code.  Make sure you change the output file name for each market/system combo that the strategy is applied to.

if t = sessionEndtime(0,1) then
begin
print(file("C:\Data\Sysname-NQ.csv"),d+19000000:8:0,",",netProfit + Openpositionprofit);
end;
Code snippet to output daily equity

This will create a csv file that looks like this.

20100201,1960.00
20100202,2790.00
20100203,2330.00
20100204,-2290.00
20100205,-3740.00
20100208,-3970.00
20100209,-2360.00
20100210,-3020.00
20100211,-630.00

3.)  Copy and paste the following code into your favorite Python IDE or IDLE.

import tkinter as tk
from tkinter import filedialog
import pandas as pd
import matplotlib.pyplot as plt
import os

def extract_market_name(filename):
"""Extracts the market name from the filename formatted as 'system-market.csv'."""
return os.path.splitext(filename)[0].split('-')[-1]

def load_equity_data(files):
"""Loads and aligns equity data from multiple CSV files."""
data_dict = {}

for file in files:
market = extract_market_name(os.path.basename(file))
df = pd.read_csv(file, header=None, names=["Date", market], dtype={0: str, 1: float})
df["Date"] = pd.to_datetime(df["Date"], format='%Y%m%d')
data_dict[market] = df.set_index("Date")

combined_df = pd.concat(data_dict.values(), axis=1, join='outer').fillna(method='ffill').fillna(method='bfill')
combined_df["Total Equity"] = combined_df.sum(axis=1)
return combined_df

def calculate_metrics(equity_curve):
"""Calculates total profit and maximum drawdown from the equity curve."""
total_profit = equity_curve.iloc[-1] - equity_curve.iloc[0]
peak = equity_curve.cummax()
drawdown = peak - equity_curve
max_drawdown = drawdown.max()
return total_profit, max_drawdown, drawdown

def calculate_correlation(df):
"""Calculates and prints the correlation matrix of equity curves."""
correlation_matrix = df.corr()
print("\n--- Correlation Matrix ---")
print(correlation_matrix.to_string())
print("\n--------------------------")

def plot_equity_and_drawdown(df, drawdown):
"""Plots the combined equity curve and drawdown as separate subplots."""
fig, ax = plt.subplots(2, 1, figsize=(12, 8), sharex=True)

# Plot equity curves
ax[0].set_title("Equity Curve")
ax[0].set_ylabel("Equity Value")
for column in df.columns[:-1]: # Exclude "Total Equity"
ax[0].plot(df.index, df[column], linestyle='dotted', alpha=0.6, label=f"{column} (Individual)")
ax[0].plot(df.index, df["Total Equity"], label="Total Equity", linewidth=2, color='black')
ax[0].legend()
ax[0].grid()

# Plot drawdown
ax[1].set_title("Drawdown")
ax[1].set_xlabel("Date")
ax[1].set_ylabel("Drawdown Amount")
ax[1].plot(drawdown.index, drawdown, color='red', linestyle='solid', alpha=0.7, label='Drawdown')
ax[1].fill_between(drawdown.index, drawdown, color='red', alpha=0.3)
ax[1].legend()
ax[1].grid()

plt.show()

def main():
root = tk.Tk()
root.withdraw()
files = filedialog.askopenfilenames(title="Select Equity Files", filetypes=[("CSV files", "*.csv")])

if not files:
print("No files selected.")
return

combined_df = load_equity_data(files)
total_profit, max_drawdown, drawdown = calculate_metrics(combined_df["Total Equity"])

print("\n--- Performance Metrics ---")
print(f"Total Profit: {total_profit:.2f}")
print(f"Maximum Drawdown: {max_drawdown:.2f}")
print("--------------------------")

calculate_correlation(combined_df.drop(columns=["Total Equity"]))
plot_equity_and_drawdown(combined_df, drawdown)

if __name__ == "__main__":
main()
Equity Curve Merge Python Script

4.)  Run it and multi-select all the system/market .csv files

5.)  Examine the results:

Combined equity, maximum draw down, and correlation matrix

How did I get ChatGPT to code this for me.

I pay $20 a month for Chat and it learns from my workflows.  The more I work with it, the more it knows my end goals to the scripts I am asking it to create.

Here are the prompts I provided Chat:

I want the user to be able to use tkinter to select multiple files that contain two columns: 1-date in yyyymmdd format and 2 – the equity value for that date. The filename consists of the system name and the market name and follows the following patterm: system name”-“market name”.csv”. I need you to extract the market from the filename. If the filename is “Gatts-GC.csv”, the market name is “GC.” Once all the files are opened, I need you to align the dates and create a combined equity curve. We can do this in matplotlib if you like. I need you to calculate the total profit and the maximum drawdown among the combined equity curves.

[SCRIPT FAILED]

My data does not included headers. The first column is the date in yyyymmdd with no separators and the second column is a float value. I think your pandas are having a hard time interpreting this

[SCRIPT WORKED]

That is perfect. Can we had a correlation analysis to the equity curves and print that out too.

[SCRIPT WORKED]

Can we plot the draw down on the same canvas as the equity curves?

[SCRIPT WORKED]

Could we put the draw down in a subplot instead of in the profit plot?

[FINAL SCRIPT] Look above

Am I Worried About Being Replaced by Chat GPT?

With Python and its data visualization libraries and EasyLanguage you can overcome some of the limitations of TradeStation.  And of course, ChatGPT.  I have been programming in Python for nine years now and I am very good at base Python.  However, Pandas are still a mystery to me and interfacing with MatPlotLib is not super simple.   Does it frustrate me that I don’t know exactly what ChatGPT is coding?  Yes, it did at first.  But now I use it as a tool.  I may not be coding the Python, but I am managing ChatGPT through my well thought out prompts and my feedback.  Does my knowledge of Python help streamline this process? – I think it does.  And I have trained ChatGPT during the process.  I am becoming a manager-programmer and ChatGPT is my assistant.