Trying to run IronPython in C#: 'LightException' object has no attribute 'qstkutil'

1.3k Views Asked by At

I am trying to run this code in VS c#:

    //calls script that will be executed as a new Thread
    private void portfolioAnalysisToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Thread myThread = new Thread(new ThreadStart(StartPy));
        myThread.Start();

    }

    //directory and script
    public static void StartPy()
    {

        string filename = "\\Scripts\\HM1.py";
        string path = Assembly.GetExecutingAssembly().Location;
        string rootDir = Directory.GetParent(path).FullName;

        RunPythonFile(rootDir, filename);
    }


    public static double RunPythonFile(string rootDir, string filename)
    {

        ScriptEngine engine = Python.CreateEngine();


        ScriptScope scope = engine.CreateScope();

        ICollection<string> paths = engine.GetSearchPaths();
        string dir = @"C:\Python27\Lib";
        paths.Add(dir);
        string dir2 = @"C:\Python27\Lib\site-packages";
        paths.Add(dir2);
        string dir3 = @"C:\Python27\Dlls";
        paths.Add(dir3);
        engine.SetSearchPaths(paths);

        ScriptSource source;
        source = engine.CreateScriptSourceFromFile(rootDir + filename);

        double result = source.Execute(scope);
        return result;
    }

The error is shown in the line: "double result = source.Execute(scope);" and it says: 'LightException' object has no attribute 'qstkutil'

The python code is:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import QSTK.qstkutil.qsdateutil as du
import QSTK.qstkutil.tsutil as tsu
import QSTK.qstkutil.DataAccess as da

import datetime as dt
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import itertools

def main():
    ''' Main Function'''


ls_symbols = ["AAPL", "GLD", "GOOG","XOM"]
dt_start = dt.datetime(2011, 1, 1)
dt_end = dt.datetime(2011, 12, 31)
dt_timeofday = dt.timedelta(hours=16)
ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt_timeofday)


c_dataobj = da.DataAccess('Yahoo')
ls_keys = ['open', 'high', 'low', 'close', 'volume', 'actual_close']
ldf_data = c_dataobj.get_data(ldt_timestamps, ls_symbols, ls_keys)
d_data = dict(zip(ls_keys, ldf_data))


na_price = d_data['close'].values


na_normalized_price = na_price / na_price[0, :]

cumm_ret = na_normalized_price.copy()
allo=np.arange(0,1.1,0.1)
valid_allocations=[[float('%.1f'%a),float('%.1f'%b),float('%.1f'%c),float('%.1f'%d)] for a in allo for b in allo for c in allo for d in allo if a+b+c+d==1]

sharpe = 0
max_a = 0
avg = 0
std = 0
best_sharpe = 0.0
best_alloc = 0

for i in range(0,len(valid_allocations)-1):

    ls_alloc = valid_allocations[i]

    fund_inv = cumm_ret * ls_alloc

    tot_fund_inv = np.sum(fund_inv,axis=1)

    daily_ret = tsu.returnize0(tot_fund_inv)

    avg_daily_ret = np.average(daily_ret)

    std_dev = np.std(daily_ret)

    sharpe_ratio = np.sqrt(252) * (avg_daily_ret/std_dev)

    if sharpe_ratio > best_sharpe:

        best_sharpe = sharpe_ratio
        best_alloc = ls_alloc

print best_sharpe, best_alloc


if __name__ == '__main__':
    main()

Thank you in advance for the Help!!

Running it with ipy.exe -X:ExceptionDetail -X:ShowClrExceptions, the stack trace is:

'LightException' object has no attribute 'qstkutil'/Scripts/HM1.py')
   em IronPython.Runtime.Operations.PythonOps.GetBoundAttr(CodeContext context,
  Object o, String name)
   em IronPython.Runtime.Operations.PythonOps.ImportBottom(CodeContext context,
  String fullName, Int32 level)
   em Microsoft.Scripting.Interpreter.FuncCallInstruction`4.Run(InterpretedFrame
 frame)
   em Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   em Microsoft.Scripting.Interpreter.LightLambda.Run2[T0,T1,TRet](T0 arg0, T1 a
  rg1)
   em IronPython.Runtime.FunctionCode.Call(CodeContext context)
   em IronPython.Modules.Builtin.execfile(CodeContext context, Object filename,
  Object globals, Object locals)
   em IronPython.Modules.Builtin.execfile(CodeContext context, Object filename)
   em Microsoft.Scripting.Interpreter.ActionCallInstruction`2.Run(InterpretedFra
  me frame)
   em Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   em Microsoft.Scripting.Interpreter.LightLambda.Run4[T0,T1,T2,T3,TRet](T0 arg0
  , T1 arg1, T2 arg2, T3 arg3)
   em IronPython.Compiler.Ast.CallExpression.Invoke1Instruction.Run(InterpretedF
  rame frame)
   em Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
   em Microsoft.Scripting.Interpreter.LightLambda.Run2[T0,T1,TRet](T0 arg0, T1 a
  rg1)
   em IronPython.Compiler.PythonScriptCode.RunWorker(CodeContext ctx)
   em IronPython.Compiler.PythonScriptCode.Run(Scope scope)
   em IronPython.Hosting.PythonCommandLine.<>c__DisplayClass1.<RunOneInteraction
  >b__0()
  AttributeError: 'LightException' object has no attribute 'qstkutil'
  CLR Exception:
    MissingMemberException
  :
  'LightException' object has no attribute 'qstkutil'

So...by running with the -X:Debug, first of all when I called IronPython, the following showed up:

   Error processing line 1 of C:\Program Files (x86)\IronPython 2.7\lib\site-packag
es\QSTK-0.2.6-py2.7-nspkg.pth:

  Traceback (most recent call last):
    File "C:\Program Files (x86)\IronPython 2.7\Lib\site.py", line 164, in addpackage
      exec line
    File "<string>", line 1, in <module>
  AttributeError: 'module' object has no attribute '_getframe'

Remainder of file ignored
Error processing line 1 of C:\Program Files (x86)\IronPython 2.7\lib\site-         packages\statsmodels-0.4.3-py2.7-nspkg.pth:

  Traceback (most recent call last):
    File "C:\Program Files (x86)\IronPython 2.7\Lib\site.py", line 164, in addpackage
      exec line
    File "<string>", line 1, in <module>
  AttributeError: 'module' object has no attribute '_getframe'

Remainder of file ignored
IronPython 2.7.4 (2.7.0.40) on .NET 4.0.30319.18408 (32-bit)
Type "help", "copyright", "credits" or "license" for more information.

And running the program:

   'LightException' object has no attribute 'qstkutil'
  em IronPython.Runtime.Operations.PythonOps.GetBoundAttr(CodeContext context,
 Object o, String name)
  em IronPython.Runtime.Operations.PythonOps.ImportBottom(CodeContext context,
 String fullName, Int32 level)
  em Microsoft.Scripting.Interpreter.FuncCallInstruction`4.Run(InterpretedFrame
  frame)
  em Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
  em Microsoft.Scripting.Interpreter.LightLambda.Run2[T0,T1,TRet](T0 arg0, T1 a
 rg1)
  em IronPython.Runtime.FunctionCode.Call(CodeContext context)
  em IronPython.Modules.Builtin.execfile(CodeContext context, Object filename,
 Object globals, Object locals)
  em IronPython.Modules.Builtin.execfile(CodeContext context, Object filename)
  em Microsoft.Scripting.Interpreter.ActionCallInstruction`2.Run(InterpretedFra
 me frame)
  em Microsoft.Scripting.Interpreter.Interpreter.Run(InterpretedFrame frame)
  em Microsoft.Scripting.Interpreter.LightLambda.Run4[T0,T1,T2,T3,TRet](T0 arg0
 , T1 arg1, T2 arg2, T3 arg3)
  em System.Dynamic.UpdateDelegates.UpdateAndExecute3[T0,T1,T2,TRet](CallSite s
 ite, T0 arg0, T1 arg1, T2 arg2)
  em <unnamed>$18.<unnamed>(CodeContext $globalContext, FunctionCode $functionC
 ode) na <stdin>:linha 1
  em IronPython.Compiler.PythonScriptCode.RunWorker(CodeContext ctx)
  em IronPython.Compiler.PythonScriptCode.Run(Scope scope)
  em IronPython.Hosting.PythonCommandLine.<>c__DisplayClass1.<RunOneInteraction
 >b__0()
 AttributeError: 'LightException' object has no attribute 'qstkutil'
0

There are 0 best solutions below