Grademark / grademark

An API for backtesting trading strategies in JavaScript and TypeScript.
MIT License
276 stars 33 forks source link

Trades is not iterable #1

Closed nford closed 5 years ago

nford commented 5 years ago

Hi, applying the example directly from https://github.com/Grademark/grademark/blob/master/README.md :

const dataForge = require('data-forge');
require('data-forge-fs'); // For file loading capability.
require('data-forge-indicators'); // For the moving average indicator.
require('data-forge-plot'); // For rendering charts.
const { backtest, analyze, computeEquityCurve, computeDrawdown } = require('grademark');

let inputSeries = dataForge.readFileSync("data/STW.csv")
    .parseCSV()
    .parseDates("date", "DD/MM/YYYY")
    .parseFloats(["open", "high", "low", "close", "volume"])
    .setIndex("date") // Index so we can later merge on date.
    .renameSeries({ date: "time" });

const movingAverage = inputSeries
    .deflate(bar => bar.close)          // Extract closing price series.
    .sma(30);                           // 30 day moving average.

inputSeries = inputSeries
    .withSeries("sma", movingAverage)   // Integrate moving average into data, indexed on date.
    .skip(30)                           // Skip blank sma entries.

const strategy = {
    entryRule: (enterPosition, args) => {
        if (args.bar.close < args.bar.sma) { // Buy when price is below average.
            enterPosition();
        }
    },

    exitRule: (exitPosition, args) => {
        if (args.bar.close > args.bar.sma) {
            exitPosition(); // Sell when price is above average.
        }
    },

    stopLoss: args => { // Optional intrabar stop loss.
        return args.entryPrice * (5 / 100); // Stop out on 5% loss from entry price.
    },
};

const trades = backtest(strategy, inputSeries)
console.log("Made " + trades.count() + " trades!");

const startingCapital = 10000;
const analysis = analyze(startingCapital, trades);
console.log(analysis);

computeEquityCurve(trades)
    .plot()
    .renderImage("output/my-equity-curve.png");

computeDrawdown(trades)
    .plot()
    .renderImage("output/my-drawdown.png");

Output of console.log(analysis):

Made 48 trades!
{ startingCapital: 10000, finalCapital: 12058.427127442317, profit: 2058.427127442317, profitPct: 20.584271274423173, growth: 1.2058427127442317, totalTrades: 48, barCount: 266, maxDrawdown: -656.9843053790391, maxDrawdownPct: -5.93346446008143, maxRiskPct: 5.000000000000007, expectency: 0.08357074385892661, rmultipleStdDev: 0.46717348951547816, systemQuality: 0.178885886580595, profitFactor: 1.6297659075049158, percentProfitable: 81.25, returnOnAccount: 3.469182534572842 }

But I get the following error for computeEquityCurve(trades):

trades is not iterable
at <anonymous> (49:5)

Using version 0.23.0 of the notebook

ashleydavis commented 5 years ago

If this is a problem with Grademark you can see a complete working example here:

https://github.com/Grademark/grademark-first-example

Otherwise, if you are having trouble with Data-Forge Notebook please email me on ashley@codecapers.com.au or log an issue here: https://github.com/data-forge-notebook/wiki/issues/new

nford commented 5 years ago
$ cd grademark-first-example/
$ npm install
audited 2638 packages in 1.639s
found 2 high severity vulnerabilities
  run `npm audit fix` to fix them, or `npm audit` for details
$ node index.js
internal/modules/cjs/loader.js:611
    throw err;
    ^

Error: Cannot find module 'moment'
[snip]
$ npm install moment
+ moment@2.24.0
added 1 package from 6 contributors and audited 2639 packages in 1.779s
found 2 high severity vulnerabilities
  run `npm audit fix` to fix them, or `npm audit` for details
$ npm start

> grademark-first-example@1.0.0 start /Users/nelson/playground/grademark-first-example
> node index.js

Loading and preparing data.
Computing moving average indicator.
Backtesting...
Made 48 trades!
An error occurred.
TypeError: trades.transformSeries(...).asCSV is not a function
nford commented 5 years ago

I have also seen trades.plot is not a function in my adventures today

ashleydavis commented 5 years ago

That's very strange. I've just done a fresh clone to retest and it all seems fine.

This is exactly what I did:

git clone https://github.com/grademark/grademark-first-example grademark-first-example-test
cd grademark-first-example-test
npm install
npm start

This is the result:

> grademark-first-example@1.0.0 start C:\projects\github\grademark\grademar
> node index.js                                                            

Loading and preparing data.                                                
Computing moving average indicator.                                        
Backtesting...                                                             
Made 48 trades!                                                            
Analyzing...                                                               
Metric             Value                                                   
-----------------  -------------------                                     
startingCapital    10000                                                   
finalCapital       12058.427127442317                                      
profit             2058.427127442317                                       
profitPct          20.584271274423173                                      
growth             1.2058427127442317                                      
totalTrades        48                                                      
barCount           266                                                     
maxDrawdown        -656.9843053790391                                      
maxDrawdownPct     -5.93346446008143                                       
maxRiskPct         5.000000000000007                                       
expectency         0.08357074385892661                                     
rmultipleStdDev    0.46717348951547816                                     
systemQuality      0.178885886580595                                       
profitFactor       1.6297659075049158                                      
percentProfitable  81.25                                                   
returnOnAccount    3.469182534572842                                       

>> output/analysis.txt                                                     
Plotting...                                                                
>> output/my-equity-curve.png
>> output/my-equity-curve-pct.png
>> output/my-drawdown.png
Finished

If this doesn't work for you, please give me more details of your setup.

For example I'm running Node.js v10.15.2 on Windows 10.

nford commented 5 years ago

I'm on node 11.9.0 on OS X. It looks like the issue is in my environment in this account because running the steps on the same system in a different account worked as expected.