0

I'm trying to print a simple table with 3 columns: Date, Market Return, and Final value. I'm having a hard time getting the syntax correct to both align a column right or left AND format a number - as decimal or percent:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
investment = 10000
expected_returns = 0.06
volatility = 0.14
duration = 20
sip = 10000

print(f'{"Date":<5}{"Return":>10}{"Value":>12}')

for date in range(duration):
    market_return = np.random.normal(expected_returns, volatility)
    final_value = sip + (1+ market_return)* investment
    print(f'{date:<5.0f}{market_return:>10.1f}{final_value:>10.0f}')
    investment = final_value

So the first column is 5 characters wide (left-aligned) and the 2nd and 3rd are 10 and 12 characters wide respectively - both right-aligned.

I am assuming I don't need to use the tab control "\t"? so the total characters of the print range should be 5+10+12=27.

The print statement outside the function executes fine.

Thx in advance.

whartonone
  • 33
  • 4

1 Answers1

0

I figured 90% of it out, answer below (but one last Q):

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

investment = 10000
expected_returns = 0.06
volatility = 0.14
duration = 20
sip = 10000

print(f"{'Year':<5}{'Return':>10}{'Value':>12}")

for Year in range(duration):
    market_return = np.random.normal(expected_returns, volatility)
    final_value = sip + (1 + market_return) * investment
    print(f"{(Year + 1):>03}{market_return:>12.1%}{final_value:>12,.1f}")
    investment = final_value

Q. How can I format the last column with a leading "$"? (and by leading I mean not in same location, but in front of the highest position in each number (no whitespace)?

Thx.

whartonone
  • 33
  • 4
  • Answers are not for new questions. Your original question isn't clear what you wanted. Instead, edit your question with your final desired output and your attempt so an answer can be provided for the question as asked. – Mark Tolonen Apr 02 '21 at 04:55
  • FYI, you can [nest f-strings](https://stackoverflow.com/q/41215365/235698), but if that looks complicated, format a string `s = f'${value:.2f}'` then print *that* right-justified `f'{s:>12}'`. Nested: `f'{f"${value:.2f}":>12}'` – Mark Tolonen Apr 02 '21 at 05:12
  • Thanks Mark! That worked - awesome! (understood as to the "Answers are not for new questions". Thx!) – whartonone Apr 02 '21 at 06:38