0

It's been a while since I have asked a questions but I am needing help with what I think is a simple task.

I have a list of string values which I have passed into a loop. Each one of the strings pertains to a function of a parent package (in this case, QuantStats).

Code appears as follows:

import QuantStats as qs
list = ['avg_loss', 'avg_gain', 'best']

for l in list:
(>>) print(l)
(>>) print(qs.stats.l(df['returns']) (Error here - 'l' not recognised. no output)

For some reason the qs.stats.l line does not work. I am not sure how to reference each element in the list, such that the qs function can run.

Hopefully there is a simple work around? Any thoughts would be very much appreciated :) thanks.

Kasrel
  • 167
  • 2
  • 12
  • Does this answer your question? [Calling a function of a module by using its name (a string)](https://stackoverflow.com/questions/3061/calling-a-function-of-a-module-by-using-its-name-a-string) – Nick Jul 08 '20 at 03:02
  • Here's a simple example: https://rextester.com/DQYW25147 – Nick Jul 08 '20 at 03:03

2 Answers2

1

Use the getattr() function to get the defined function. Like this:

import QuantStats as qs
list = ['avg_loss', 'avg_gain', 'best']

for l in list:
(>>) print(l)
(>>) print(getattr(qs.stats,l)(df['returns'])
Darsh Reddy
  • 49
  • 1
  • 8
  • 1
    Haha I didn't take note of the ,l and ran into trouble with attribution. Thank you for the suggestion! This solves my problem :) – Kasrel Jul 08 '20 at 05:14
-1

I think you entered 1 instead of i , It should be (for i in List:)

jizhihaoSAMA
  • 12,336
  • 9
  • 27
  • 49